您好我在尝试优化投资组合以获得最小差异时遇到此错误:
Error in seq.default(from = round(min, rounding), to = round(max, rounding), :
'from' cannot be NA, NaN or infinite
使用ROI,Simplex和grid可以很好地运行优化,但所有这些方法都忽略了位置约束。随机和DEOPtim上的相同错误。这是我正在运行的确切代码:
tickers = c("AMJ", "AMLP", "ASHR", "DIA", "DUST", "DXJ", "EEM", "EFA",
"EPI", "ERX", "EWG", "EWI", "EWJ", "EWU", "EWW", "EWY", "EWZ",
"FAS", "FAZ", "FEZ", "FXE", "FXI", "FXY", "GDX", "GDXJ", "GLD",
"GREK", "HEDJ", "HYG", "IAU", "IBB", "ITB", "IWM", "IYR", "JDST",
"JNUG", "KRE", "MDY", "NUGT", "OIH", "QQQ", "SCO", "SDS", "SLV",
"SPY", "SSO", "SVXY", "TBT", "TLT", "TNA", "TQQQ", "TZA", "UCO",
"UNG", "UPRO", "USO", "UUP", "UVXY", "VIXY", "VWO", "VXX", "XBI",
"XHB", "XLB", "XLE", "XLF", "XLI", "XLK", "XLP", "XLU", "XLV",
"XLY", "XME", "XOP", "XRT")
data = lapply(tickers, function(sym) {
getSymbols(sym, src="google", auto.assign=FALSE)
})
close = lapply(data, function(frame) {
frame[,4]
})
merged = do.call(merge, close)
returns = CalculateReturns(merged)
returns = na.omit(returns)
portfolio = portfolio.spec(assets=colnames(returns))
portfolio = add.constraint(portfolio = portfolio, type="leverage", min_sum=0.99, max_sum=1.01)
portfolio = add.constraint(portfolio, type="position_limit", max_pos=8)
minvar = add.objective(portfolio, type="risk", name="var")
opt = optimize.portfolio(returns, minvar, optimize_method="random")
以下是当前加载的软件包:
R version 3.3.3 (2017-03-06)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages:
[1] parallel stats graphics grDevices utils datasets methods base
other attached packages:
[1] MASS_7.3-45 quadprog_1.5-5 Rglpk_0.6-3
[4] slam_0.1-40 iterators_1.0.8 ROI.plugin.quadprog_0.2-5
[7] ROI.plugin.glpk_0.2-5 ROI_0.2-6 DEoptim_2.2-4
[10] readr_1.1.1 quantmod_0.4-8 TTR_0.23-1
[13] PortfolioAnalytics_1.0.3636 foreach_1.4.3 PerformanceAnalytics_1.4.3541
[16] xts_0.9-7 zoo_1.8-0
loaded via a namespace (and not attached):
[1] Rcpp_0.12.10 lattice_0.20-34 codetools_0.2-15 grid_3.3.3 R6_2.2.1 registry_0.3 tools_3.3.3
[8] hms_0.3 tibble_1.3.0
答案 0 :(得分:1)
似乎您需要设置资产权重的界限。这可以通过添加type="box"
约束来完成。我稍微重写了代码并删除了minvar
变量。
portfolio <- portfolio.spec(assets=colnames(returns))
portfolio <- add.constraint(portfolio = portfolio, type="leverage",
min_sum=0.99, max_sum=1.01)
portfolio <- add.constraint(portfolio, type="position_limit", max_pos=8)
portfolio <- add.constraint(portfolio, type="box", min=0, max=0.5) # <-------
portfolio <- add.objective(portfolio, type="risk", name="var")
opt <- optimize.portfolio(R=returns, portfolio=portfolio, optimize_method="random")
opt