让我们看看我是否可以在您的帮助下解决这个问题。PortfolioAnalytics
用于优化投资组合的 R 包似乎有一个错误。很可能是我,但可以肯定的是,我想看看是否有其他人遇到同样的问题并可能找到解决方案。
在为每个资产的最小和最大分配添加约束时,我收到以下错误:
Error in sample.int(length(x), size, replace, prob) :
invalid first argument
这是所述错误的代码:
c.min = c(0.10,0.15,0.10,0.50,0.15,0,0,0,0,0)
c.max = c(.20,.20,.20,.20,.20,.20,.20,.20,.20,.20)
port_spec <- add.constraint(portfolio = port_spec,type = "box",enabled = TRUE,min = c.min,
max = c.max) #Min Position & Max position
10 是正确的资产数量,当我使用以下代码时,代码运行良好:
port_spec <- add.constraint(portfolio = port_spec,type = "box",enabled = TRUE,min = .00, max = .25) #Min Position & Max position
此外,我通过以下链接使用发布者请求的确切语法:publishers doc
有没有人见过这个问题?
以下是用于投资组合优化的完整代码:
port_spec <- NULL
port_spec <- portfolio.spec(colnames(returns.monthly))
## Add constraints
#add constraint "full_invested" portfolio must equal 100% allocation
port_spec <- add.constraint(portfolio = port_spec,type = "weight_sum",min_sum = .97, max_sum = 1.01)
port_spec <- add.constraint(portfolio = port_spec,type = "long_only")#add constriant "long_only" not allowing the portfolio to go short
c.min = c(0.10,0.15,0.10,0.50,0.15,0,0,0,0,0)
c.max = c(.20,.20,.20,.20,.20,.20,.20,.20,.20,.20)
port_spec <- add.constraint(portfolio = port_spec,type = "box",enabled = TRUE,min = c.min,
max = c.max) #Min Posiyion & Max position
port_spec <- add.constraint(port_spec,type = "return",return_target=mean.return)
port_spec <- add.constraint(port_spec,type = "risk",risk_target=mean.risk)
##Add portfolio objectives
#port_spec <- add.objective(portfolio = port_spec,type = "return",name = "sr_annualized",arguments = list(scale = 12,rfr = .02))
port_spec <- add.objective(portfolio = port_spec,type = "return",name = "mean")
#port_spec <- add.objective(portfolio = port_spec,type = "risk",name = "StdDev")
#port_spec <- add.objective(portfolio = port_spec,type = "risk",name = "ES",arguments = list(p=0.90,method = "gaussian"))
# Add dummy objectives for plotting
port_spec <- add.objective(portfolio = port_spec,type = "risk",name = "StdDev",multiplier=0)
#port_spec <- add.objective(portfolio = port_spec,type = "return",name = "mean",multiplier=0)
print(port_spec)
## Run optimization
opt <- optimize.portfolio(returns.monthly, portfolio = port_spec,optimize_method="DEoptim",trace = TRUE)