Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/demo/constrained_optim.R
1433 views
1
#' ---
2
#' title: "Constrained Optimization Demo"
3
#' ---
4
5
#' This script demonstrates how to set up and solve constrained optimization
6
#' problems. Note that this script using the pre version 0.8.3 syntax.
7
8
library(PortfolioAnalytics)
9
require(DEoptim)
10
11
#' Load the data
12
data(edhec)
13
14
#' Set up the constraints and objectives to define the optimization problem
15
constraints <- constraint(assets = colnames(edhec[, 1:10]), min = 0.01,
16
max = 0.4, min_sum=0.99, max_sum=1.01,
17
weight_seq = generatesequence())
18
19
constraints <- add.objective(constraints=constraints,
20
type="return",
21
name="mean")
22
23
constraints <- add.objective(constraints=constraints,
24
type="risk_budget",
25
name="ES", arguments=list(clean="boudt", p=0.95),
26
min_prisk=.05,
27
max_prisk=.15,
28
target=0.05)
29
30
#' We'll use a search_size parameter of 1000 for this demo, but realistic
31
#' portfolios will likely require search_size parameters much larger, the
32
#' default is 20000 which is almost always large enough for any realistic
33
#' portfolio and constraints, but will take substantially longer to run.
34
35
#' Look for a solution using both DEoptim and random portfolios
36
opt_out <- optimize.portfolio(R=edhec[,1:10],
37
constraints=constraints,
38
optimize_method="DEoptim",
39
search_size=1000,
40
trace=TRUE)
41
42
opt_out_random <- optimize.portfolio(R=edhec[,1:10],
43
constraints=constraints,
44
optimize_method="random",
45
search_size=1000,
46
trace=TRUE)
47
48
#' Optimize a portfolio that rebalances quarterly
49
opt_out_rebalancing <- optimize.portfolio.rebalancing(R=edhec[,1:10],
50
constraints=constraints,
51
optimize_method="random",
52
search_size=1000,
53
trace=FALSE,
54
rebalance_on='quarters')
55
56
#' Extract the optimal weights at each rebalance date and compute the returns
57
rebalancing_weights <- extractWeights(opt_out_rebalancing)
58
rebalancing_returns <- Return.rebalancing(R=edhec,weights=rebalancing_weights)
59
charts.PerformanceSummary(rebalancing_returns)
60
61
#' Optimize a portfolio that rebalances quarterly with 48 month trailing
62
opt_out_trailing <- optimize.portfolio.rebalancing(R=edhec[,1:10],
63
constraints=constraints,
64
optimize_method="random",
65
search_size=1000,
66
trace=FALSE,
67
rebalance_on='quarters',
68
trailing_periods=48,
69
training_period=48)
70
71