问题
I am trying to replicate with R this optimization problem for which the XL solver seems to do the job (I am assuming it's a decent one); I seem to fail getting the package/function ticking all the relevant boxes.
It is essentially a non-linear optimization problem with inequality constraints.
The relevant elements of the problem can be replicated with this snippet:
varCovar <- matrix(data = c(0.000576046, 0.000126261, 0.00012385, 0.000104201, 5.57911E-05,
0.000126261, 0.000411463, 9.88479E-05, 0.000100924, 0.000109183,
0.00012385, 9.88479E-05, 0.00038341, 6.42237E-05, 5.20799E-05,
0.000104201, 0.000100924, 6.42237E-05, 0.000291617, 4.6866E-05,
5.57911E-05, 0.000109183, 5.20799E-05, 4.6866E-05, 0.000155289),
nrow = 5)
ret <- c(0.01,0.05,0.02,0.035,0.0136)
wgt <- c(0,0.3,0.3,0.3,0.1)
minWgt <- 0
maxWgt <- 0.3
rf <- 0.03
ptfRet <- sum(ret*wgt)
retVar <- sqrt(t(wgt) %*% varCovar %*% wgt)
sr <- (ptfRet-rf)/retVar
I need to maximize sr
by changing wgt
with the following constraints:
sum(wgt) = 1
wgt <= maxWgt
wgt >= minWgt
This would be the equivalent screenshot (which has an error!) with the XL-based solution.
Thanks.
回答1:
This can be achieved using NlcOptim::solnl()
function.
This is what I ended up doing:
obj <- function(wgt) {
ptfRet <- sum(ret*wgt)
retVar <- sqrt(t(wgt) %*% varCovar %*% wgt)
sr <- -(ptfRet-rf)/retVar
return(sr)
}
con <- function(wgt) {
f = NULL
f = rbind(f, sum(wgt)-1)
return(list(ceq = f, c = NULL))
}
result <- solnl(X = wgt, objfun = obj, confun = con,
lb = rep(minWgt, length(wgt)), ub = rep(maxWgt, length(wgt)))
solWgt <- result$par
solSR <- -result$fn
The only catch seems to be the function returns a minimum (as per CRAN doc). If you set the objective as -objective you will get the maximum.
来源:https://stackoverflow.com/questions/56684023/replicate-xl-grg-nonlinear-solver-in-r-example-provided