Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/demo/demo_group_constraints.R
1433 views
1
#' ---
2
#' title: "Group Constraints Demo"
3
#' author: Ross Bennett
4
#' date: "7/17/2014"
5
#' ---
6
7
#' This script demonstrates how to solve a portfolio optimization problem with
8
#' group constraints.
9
10
#' Load the package and data
11
library(PortfolioAnalytics)
12
13
data(edhec)
14
R <- edhec[, 1:5]
15
colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQM")
16
funds <- colnames(R)
17
18
#' Set up portfolio with objectives and constraints.
19
init.portf <- portfolio.spec(assets=funds)
20
init.portf <- add.constraint(portfolio=init.portf, type="full_investment")
21
init.portf <- add.constraint(portfolio=init.portf, type="long_only")
22
23
#' Add group constraints such that assets 1, 3, and 5 are in a group called
24
#' GroupA and assets 2 and 4 are in a group called Group B. The sum of the
25
#' weights in GroupA must be between 0.05 and 0.7. The sum of the weights in
26
#' GroupB must be between 0.15 and 0.5.
27
init.portf <- add.constraint(portfolio=init.portf, type="group",
28
groups=list(groupA=c(1, 3, 5),
29
groupB=c(2, 4)),
30
group_min=c(0.05, 0.15),
31
group_max=c(0.7, 0.5))
32
init.portf
33
34
35
#' Add an objective to minimize portfolio standard deviation.
36
init.portf <- add.objective(portfolio=init.portf, type="risk", name="StdDev")
37
38
#' The examples here use the obective to minimize standard deviation, but any
39
#' supported objective can also be used.
40
41
#' Minimizing standard deviation can be formulated as a quadratic programming
42
#' problem and solved very quickly using optimize_method="ROI". Although "StdDev"
43
#' was specified as an objective, the quadratic programming problem uses the
44
#' variance-covariance matrix in the objective function.
45
minStdDev.ROI <- optimize.portfolio(R=R, portfolio=init.portf, optimize_method="ROI")
46
minStdDev.ROI
47
extractGroups(minStdDev.ROI)
48
49
#' The leverage constraints should be relaxed slightly for random portfolios
50
#' and DEoptim.
51
init.portf$constraints[[1]]$min_sum=0.99
52
init.portf$constraints[[1]]$max_sum=1.01
53
54
#' Run the optimization with random portfolios as the optimization backend.
55
#' By construction, the random portfolios will be generated to satisfy the
56
#' group constraint.
57
minStdDev.RP <- optimize.portfolio(R=R, portfolio=init.portf,
58
optimize_method="random", search_size=2000)
59
minStdDev.RP
60
extractGroups(minStdDev.RP)
61
62
#' Run the optimization with DEoptim as the optimization backend.
63
minStdDev.DE <- optimize.portfolio(R=R, portfolio=init.portf,
64
optimize_method="DEoptim", search_size=2000)
65
minStdDev.DE
66
extractGroups(minStdDev.DE)
67
68