简体   繁体   中英

Replicate XL GRG Nonlinear solver in R (example provided)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM