Path: blob/master/demo/constrained_optim.R
1433 views
#' ---1#' title: "Constrained Optimization Demo"2#' ---34#' This script demonstrates how to set up and solve constrained optimization5#' problems. Note that this script using the pre version 0.8.3 syntax.67library(PortfolioAnalytics)8require(DEoptim)910#' Load the data11data(edhec)1213#' Set up the constraints and objectives to define the optimization problem14constraints <- constraint(assets = colnames(edhec[, 1:10]), min = 0.01,15max = 0.4, min_sum=0.99, max_sum=1.01,16weight_seq = generatesequence())1718constraints <- add.objective(constraints=constraints,19type="return",20name="mean")2122constraints <- add.objective(constraints=constraints,23type="risk_budget",24name="ES", arguments=list(clean="boudt", p=0.95),25min_prisk=.05,26max_prisk=.15,27target=0.05)2829#' We'll use a search_size parameter of 1000 for this demo, but realistic30#' portfolios will likely require search_size parameters much larger, the31#' default is 20000 which is almost always large enough for any realistic32#' portfolio and constraints, but will take substantially longer to run.3334#' Look for a solution using both DEoptim and random portfolios35opt_out <- optimize.portfolio(R=edhec[,1:10],36constraints=constraints,37optimize_method="DEoptim",38search_size=1000,39trace=TRUE)4041opt_out_random <- optimize.portfolio(R=edhec[,1:10],42constraints=constraints,43optimize_method="random",44search_size=1000,45trace=TRUE)4647#' Optimize a portfolio that rebalances quarterly48opt_out_rebalancing <- optimize.portfolio.rebalancing(R=edhec[,1:10],49constraints=constraints,50optimize_method="random",51search_size=1000,52trace=FALSE,53rebalance_on='quarters')5455#' Extract the optimal weights at each rebalance date and compute the returns56rebalancing_weights <- extractWeights(opt_out_rebalancing)57rebalancing_returns <- Return.rebalancing(R=edhec,weights=rebalancing_weights)58charts.PerformanceSummary(rebalancing_returns)5960#' Optimize a portfolio that rebalances quarterly with 48 month trailing61opt_out_trailing <- optimize.portfolio.rebalancing(R=edhec[,1:10],62constraints=constraints,63optimize_method="random",64search_size=1000,65trace=FALSE,66rebalance_on='quarters',67trailing_periods=48,68training_period=48)697071