Skip to content

adding overall constraint in optim()

2 messages · Ravi Varadhan

#
Hi,

You can use the projectLinear argument in BB::spg to optimize with linear equality/inequality constraints.



Here is how you implement the constraint that all parameters sum to 1.



require(BB)

spg(par=p0, fn=myFn, project="projectLinear", projectArgs=list(A=matrix(1, 1, length(p0)), b=1, meq=1))



Hope this is helpful,

Ravi
#
Here is what you do for your problem:



require(BB)

Mo.vect <- as.vector(tail(head(mo,i),1))
     wgt.vect <- as.vector(tail(head(moWeightsMax,i),1))
     cov.mat <- cov(tail(head(morets,i+12),12))
     opt.fun <- function(wgt.vect) -sum(Mo.vect %*% wgt.vect) / (t(wgt.vect) %*% (cov.mat %*% wgt.vect))

     LowerBounds<-c(0.2,0.05,0.1,0,0,0)
     UpperBounds<-c(0.6,0.3,0.6,0.15,0.1,0.2)

      spgSolution <- spg(wgt.vect, fn=opt.fun, lower=LowerBounds, upper=UpperBounds, project="projectLinear", projectArgs=list(A=matrix(1, 1, length(wgt.vect)), b=1, meq=1)))





Ravi