R中的ROI优化使用多参数F_objective函数

时间:2017-04-18 08:00:27

标签: r optimization nonlinear-optimization r-optimization

尝试在R中运行简单的ROI优化,但经过数小时的烦躁不安后,我感到很茫然。我一直收到错误:

Error in .check_function_for_sanity(F, n) : 
  cannot evaluate function 'F' using 'n' = 5 parameters.

以下是示例代码:

library(ROI)
library(nloptr)
library(ROI.plugin.nloptr)

#Generate some random data for this example
set.seed(3142)
myRet = matrix(runif(100 * 5, -0.1, 0.1), ncol = 5)
myCovMatrix = cov(myRet)

myRet <- myRet
myCovMatrix <- myCovMatrix

# Sample weights
w <-  rep(1/ncol(myRet), ncol(myRet))

#Define functions for the optimisation
diversificationRatio = function(w, covMatrix)
{
  weightedAvgVol = sum(w * sqrt(diag(covMatrix)))

  portfolioVariance = (w %*% covMatrix %*% w)[1,1]

  - 1 * weightedAvgVol / sqrt(portfolioVariance)

}

# Check that the F_objective function works:
diversificationRatio(w, myCovMatrix)

# Now construct the F_objective
foo <- F_objective(F = diversificationRatio, n = (ncol(myRet)))

有关传递给n的参数数量的任何想法?

1 个答案:

答案 0 :(得分:1)

F_objective期望一个函数只有一个参数,所以你必须编写一个包装函数。

#Define functions for the optimisation
diversificationRatio <- function(w, covMatrix) {
    weightedAvgVol <- sum(w * sqrt(diag(covMatrix)))
    portfolioVariance <- (w %*% covMatrix %*% w)[1,1]
    - 1 * weightedAvgVol / sqrt(portfolioVariance)
}

# Check that the F_objective function works:
wrapper <- function(x) diversificationRatio(x, myCovMatrix)

# Now construct the F_objective
o <- OP(F_objective(F = wrapper, n = (ncol(myRet))))

ROI_applicable_solvers(o)

start <- runif(ncol(myRet))
s <- ROI_solve(o, solver = "nloptr", start = start, method = "NLOPT_LD_SLSQP")
s
solution(s)