2017-04-18 49 views
0

試圖在R中運行簡單的ROI優化,但經過數小時的煩躁後,我不知所措。我不斷收到錯誤:R中使用多參數F_objective函數進行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

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) 
+0

我使用F_constraints()碰上了相關的問題,但提出了另外一個問題。我真的希望你能幫助,但不確定如何標記你,因此這個評論。真的很感激任何意見:https://stackoverflow.com/questions/44932853/roi-optimisation-in-r-using-f-constraint – csrvermaak