[R] how to use solve.QP

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Thu Jan 13 19:58:33 CET 2005


On Thu, 13 Jan 2005 13:44:58 -0500 roger bos wrote:

> At the risk of ridicule for my deficient linear algebra skills, I ask
> for help using the solve.QP function to do portfolio optimization.  I
> am trying to following a textbook example and need help converting the
> problem into the format required by solve.QP.  Below is my sample code
> if anyone is willing to go through it.  This problem will not solve
> because it is not set up properly.  I hope I included enough details
> for someone to deciper it.  Or does anyone have a good example they
> can send me?

You can look at the man page, code and example of the function
portfolio.optim() in package tseries which does portfolio optimization
based on solve.QP from quadprog.

hth,
Z

> Thanks so much for any hints and suggestions, Roger.
> 
> 
> 
> library(quadprog, lib.loc="C:\\Program Files\\R\\tools")
> library(MASS, lib.loc="C:\\Program Files\\R\\tools")
> n<-100
> m<-200
> rho<-0.7
> sigma<-0.2
> mu<-0.1
> Cov <- matrix(rho*sigma*sigma, ncol=n, nrow=n)
> diag(Cov) <- rep(sigma*sigma, n)
> S <- 1+matrix(mvrnorm(m, rep(mu, n), Sigma=Cov), ncol=n)
> 
> #The problem is formulated as minimize t(b) Cov b
> #subject to cLo <= A <= cUp
> #and bLo=0 <= w <= 1=bUp
> 
> Cov <- var(S)
> mu <- apply(S, 2, mean)
> mu.target <- 0.1
> #subject to cLo <= A <= cUp and bLo=0 <= b <= 1=bUp
> A <- rbind(1,mu)
> cLo <- c(1, mu.target)
> cUp <- c(1, Inf)
> bLo <- rep(0, n)
> bUp <- rep(1, n)
> 
> #I convert [cLo <= A <= cUp] to Amat >= bvec and [bLo=0 <= w #<=1=bUp]
> #to
> Amat <- rbind(-1, 1, -mu, mu)
> dim(bLo) <- c(n,1)
> dim(bUp) <- c(n,1)
> bvec <- rbind(-1, 1, mu.target, Inf, bLo, -bUp)
> zMat <- matrix(rep(0,2*n*n),ncol=n, nrow=n*2)
> zMat[,1] <- c(rep(1,n), rep(-1,n))
> Amat <- t(rbind(Amat, zMat))
> 
> #So I set Dmat=Cov and set dvec=0
> Dmat=Cov
> dvec=rep(0, nrow(Amat))
> 
> #The first two rows of Amat should be equality constraints (so weights
> #sum to 1)
> meq <- 2
> 					
> sol <- solve.QP(Dmat=Dmat, dvec=dvec, Amat=Amat, bvec=bvec, meq)
> sol
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list