r - solve.QP - Constraints are Inconsistent -
i attempting use solve.qp solve quadratic program there 3 constraints:
- all sum 1 (this works fine)
- all must greater 0 (this works fine well)
- all must less .30 (this not working)
first, test data:
n <- 6 r <- array(rnorm(n^2, mean=1), c(100,n)) # 'returns' colnames(r) <- c("a", "b", "c", "d", "e", "f")
my function:
eff.frontier <- function (returns, short="no", max.allocation=null, risk.premium.up=.5, risk.increment=.005){ covariance <- cov(returns) n <- ncol(covariance) amat <- matrix (1, nrow=n) bvec <- 1 meq <- 1 if(short=="no"){ amat <- cbind(1, diag(n)) bvec <- c(bvec, rep(0, n)) } if(!is.null(max.allocation)){ if(max.allocation > 1 | max.allocation <0){ stop("max.allocation must greater 0 , less 1") } amat <- cbind(amat, -1*diag(n)) # seems issue area.... bvec <- c(bvec, rep(-max.allocation, n)) print(bvec) } loops <- risk.premium.up / risk.increment + 1 loop <- 1 #initialize matrix contain allocation , statistics eff <- matrix(nrow=loops, ncol=n+3) # need give matrix column names colnames(eff) <- c(colnames(returns), "std.dev", "exp.return", "sharpe") # loop through quadratic program solver (i in seq(from=0, to=risk.premium.up, by=risk.increment)){ dvec <- colmeans(returns) * sol <- solve.qp(covariance, dvec=dvec, amat=amat, bvec=bvec, meq=meq) eff[loop,"std.dev"] <- sqrt(sum(sol$solution *colsums((covariance * sol$solution)))) eff[loop,"exp.return"] <- as.numeric(sol$solution %*% colmeans(returns)) eff[loop,"sharpe"] <- eff[loop,"exp.return"] / eff[loop,"std.dev"] eff[loop,1:n] <- sol$solution loop <- loop+1 } return(as.data.frame(eff)) }
when don't try set allocation maximum, works fine. no matter try set max.allocation, fails.
am setting amat or bvec incorrectly?
here error:
> eff <- eff.frontier(returns=r, short="yes", risk.premium.up=.5, risk.increment=.001, max.allocation=.15) error in solve.qp(covariance, dvec = dvec, amat = amat, bvec = bvec, meq = meq) : constraints inconsistent, no solution!
here amat:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 1 -1 0 0 0 0 0 [2,] 1 0 -1 0 0 0 0 [3,] 1 0 0 -1 0 0 0 [4,] 1 0 0 0 -1 0 0 [5,] 1 0 0 0 0 -1 0 [6,] 1 0 0 0 0 0 -1
and here bvec:
[1] 1.00 -0.15 -0.15 -0.15 -0.15 -0.15 -0.15
how these inconsistent??
thank you,
andrew
Comments
Post a Comment