Path: blob/master/demo/demo_group_constraints.R
1433 views
#' ---1#' title: "Group Constraints Demo"2#' author: Ross Bennett3#' date: "7/17/2014"4#' ---56#' This script demonstrates how to solve a portfolio optimization problem with7#' group constraints.89#' Load the package and data10library(PortfolioAnalytics)1112data(edhec)13R <- edhec[, 1:5]14colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQM")15funds <- colnames(R)1617#' Set up portfolio with objectives and constraints.18init.portf <- portfolio.spec(assets=funds)19init.portf <- add.constraint(portfolio=init.portf, type="full_investment")20init.portf <- add.constraint(portfolio=init.portf, type="long_only")2122#' Add group constraints such that assets 1, 3, and 5 are in a group called23#' GroupA and assets 2 and 4 are in a group called Group B. The sum of the24#' weights in GroupA must be between 0.05 and 0.7. The sum of the weights in25#' GroupB must be between 0.15 and 0.5.26init.portf <- add.constraint(portfolio=init.portf, type="group",27groups=list(groupA=c(1, 3, 5),28groupB=c(2, 4)),29group_min=c(0.05, 0.15),30group_max=c(0.7, 0.5))31init.portf323334#' Add an objective to minimize portfolio standard deviation.35init.portf <- add.objective(portfolio=init.portf, type="risk", name="StdDev")3637#' The examples here use the obective to minimize standard deviation, but any38#' supported objective can also be used.3940#' Minimizing standard deviation can be formulated as a quadratic programming41#' problem and solved very quickly using optimize_method="ROI". Although "StdDev"42#' was specified as an objective, the quadratic programming problem uses the43#' variance-covariance matrix in the objective function.44minStdDev.ROI <- optimize.portfolio(R=R, portfolio=init.portf, optimize_method="ROI")45minStdDev.ROI46extractGroups(minStdDev.ROI)4748#' The leverage constraints should be relaxed slightly for random portfolios49#' and DEoptim.50init.portf$constraints[[1]]$min_sum=0.9951init.portf$constraints[[1]]$max_sum=1.015253#' Run the optimization with random portfolios as the optimization backend.54#' By construction, the random portfolios will be generated to satisfy the55#' group constraint.56minStdDev.RP <- optimize.portfolio(R=R, portfolio=init.portf,57optimize_method="random", search_size=2000)58minStdDev.RP59extractGroups(minStdDev.RP)6061#' Run the optimization with DEoptim as the optimization backend.62minStdDev.DE <- optimize.portfolio(R=R, portfolio=init.portf,63optimize_method="DEoptim", search_size=2000)64minStdDev.DE65extractGroups(minStdDev.DE)666768