使用optimize_method="random"
运行port_spec <- portfolio.spec(assets=colnames(asset_returns), weight_seq=generatesequence(min=0, max=1, by=0.002))
port_spec$constraints[[1]]$min_sum=0.99
port_spec$constraints[[1]]$max_sum=1.01
port_spec <- add.constraint(portfolio=port_spec, type="box", min=0, max=0.5)
时出现错误。错误是:
“杠杆约束min_sum和max_sum是限制性的,请考虑放松。例如'full_investment'约束应为min_sum = 0.99和max_sum = 1.01”。
我尝试使用以下内容修改代码:
library(PortfolioAnalytics)
data(edhec)
asset_returns <- edhec
port_spec <- portfolio.spec(assets=colnames(asset_returns))
# Add a full investment constraint such that the weights sum to 1
port_spec <- add.constraint(portfolio=port_spec, type="full_investment")
# Add a long only constraint such that the weight of an asset is between 0 and 1
port_spec <- add.constraint(portfolio=port_spec, type="long_only")
# Add an objective to minimize portfolio standard deviation
port_spec <- add.objective(portfolio=port_spec, type="risk", name="StdDev")
# Add a risk budget objective
port_spec <- add.objective(portfolio = port_spec,
type = "risk_budget",
name = "StdDev",
min_prisk = 0.01,
max_prisk = 0.4)
# Print the portfolio specification
print(port_spec)
# Run the optimization
rp <- 50
opt_rebal_rb <- optimize.portfolio.rebalancing(R = asset_returns,
portfolio = port_spec,
optimize_method = "random", rp =rp,
trace = TRUE,
rebalance_on = "quarters",
training_period = 60,
rolling_window = 60)
print(opt_rebal_rb)
# Chart the weights
chart.Weights(opt_rebal_rb)
# Chart the percentage contribution to risk
chart.RiskBudget(opt_rebal_rb, match.col = "StdDev", risk.type = "percentage")
# Compute the portfolio returns
returns_rb <- Return.portfolio(R = asset_returns, weights = extractWeights(opt_rebal_rb))
colnames(returns_rb) <- "risk_budget"
,但是代码仍然无法正常工作。任何建议将不胜感激!
原始代码如下:
arrow