问题
I've been struggling with optimization problems in R for months now. I've finally figured out lpSolve
for linear problems, thanks to examples on data for fantasy sports. However, my original and (still) current problem is trying nonlinear optimization with equality constraints using nloptr
in R.
What I'm trying to do is minimize the variance of a two-stock portfolio, in which the two stocks' returns are almost perfectly negatively correlated (for those that are familiar with academic finance, the end goal is to prove/disprove whether or not arbitrage opportunities exist). I want to minimize the variance, subject to the sum of the two weights being exactly equal to 1, while being between 0 and 1. Below is the exact code I am using, which should be easily reproducible:
sd1 <- 0.01
sd2 <- 0.025
corr.lo <- -0.999
# Objective function
eval.f <- function(w) {
return(
(w[1]*sd1)^2 +
(w[2]*sd2)^2 +
(2*w[1]*w[2]*sd1*sd2*corr.lo)
)
}
# Constraint function
eval.g <- function(w) {
return(w[1] + w[2] - 1)
}
w0 <- c(0.5, 0.5)
opts <- list('algorithm' = 'NLOPT_GN_ISRES', 'xtol_rel' = 1.0e-8)
res <- nloptr(
x0 = w0,
eval_f = eval.f,
lb = c(0,0),
ub = c(1,1),
eval_g_eq = eval.g,
opts = opts
)
The optimization runs without errors, and generates the following:
> res
Call:
nloptr(x0 = w0, eval_f = eval.f, lb = c(0, 0), ub = c(1, 1), eval_g_eq = eval.g, opts = opts)
Minimization using NLopt version 2.4.0
NLopt solver status: 5 ( NLOPT_MAXEVAL_REACHED: Optimization stopped because maxeval (above) was reached. )
Number of Iterations....: 100
Termination conditions: xtol_rel: 1e-08
Number of inequality constraints: 0
Number of equality constraints: 1
Current value of objective function: 0.000125508655202602
Current value of controls: 0.5 0.5
I'm using the above algorithm because that's one that runs without telling me I need a gradient (which I am not familiar with). The problem is, the initial values of w0
DO NOT change from 50% each. Can anyone either reproduce this and offer advice, or try and point me in the right direction?
Thanks in advance!
回答1:
I've found the answer my own question. The optimization wasn't running long enough, I think. By specifying maxeval = 1000000
in the opts
list, I got an answer that satisfied the constraints.
来源:https://stackoverflow.com/questions/34796173/no-change-to-initial-values-using-nloptr-in-r