[R] Help with constrained portfolio optimization

Enrico Schumann es at enricoschumann.net
Sat Jul 9 21:16:17 CEST 2016


On Fri, 08 Jul 2016, Paulino Levara <paulino.levara at gmail.com> writes:

> Dear R community,
>
> I am a beginner in portfolio optimization and I would appreciate your help
> with the next problem:given a set of 10 variables (X), I would like to
> obtain the efficient portfolio that minimize the variance taking the
> expected return as mean(X), subject to the next constraints:
>
> a) Limit the sum of the weights of the first five variables to 30%
> b) Limit the sum of the weights of the last five variables to 70%
>
> What is your suggestion? Can I do this with the portfolio.optim function of
> the tseries package?
>
> How Can I do that?
>
> Thanks in advance.
>
> Regards.
>

Such a problem can be solved via quadratic programming. I would
start with package 'quadprog' and its function 'solve.QP' (which
is actually what tseries::portfolio.optim uses). You can find
many tutorials on the web on how to use this function for
portfolio optimisation.

The tricky part is setting up the constraint matrices. Here is
some code that may help you get started. (It is adapted from one
of the code examples in package "NMOF".) 

require("quadprog")

## create random returns data
na  <- 10  ## number of assets 
ns  <- 60  ## number of observations
R   <- array(rnorm(ns * na, 
                   mean = 0.005, sd = 0.015), 
             dim = c(ns, na)) ## roughly like monthly equity returns
m    <- colMeans(R)  ## asset means
rd   <- mean(m)      ## desired mean
wmax <- 1            ## maximum holding size
wmin <- 0.0          ## minimum holding size

## set up matrices
A <- rbind(1, c(rep(1,5), rep(0,5)), m,
           -diag(na), diag(na))

bvec <- c(1, 0.3, rd,
          rep(-wmax, na),
          rep(wmin, na))

result <- solve.QP(Dmat = 2*cov(R),
                   dvec = rep(0, na),
                   Amat = t(A),
                   bvec = bvec,
                   meq  = 2)

w <- result$solution 

## check results
sum(w)         ## check budget constraint
sum(w[1:5])    ## check sum-of-weights constraint
w %*% m >= rd  ## check return constraint
summary(w)     ## check holding size constraint


-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list