Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/demo/demo_DEoptim.R
1433 views
1
#' ---
2
#' title: "Differential Evolution Optimization Demo"
3
#' date: "7/17/2014"
4
#' ---
5
6
#' This script demonstrates several optimization problems using Differential
7
#' Evolution as the optimization engine. This script is based heavily on
8
#' http://www.rinfinance.com/agenda/2012/workshop/Carl+Peterson.pdf.
9
10
#' The following optimization problems will be run
11
#' * mean-mETL: maximize mean-to-ETL (i.e. reward-to-risk)
12
#' * MinSD: minimize annualized standard deviation
13
#' * eqStdDev: equal risk (volatility)
14
#' * MeanRL: maximize mean with mETL risk limits
15
16
#' Include optimizer and multi-core packages
17
library(PortfolioAnalytics)
18
require(DEoptim)
19
require(foreach)
20
21
#' The multicore package, and therefore registerDoMC, should not be used in a
22
#' GUI environment, because multiple processes then share the same GUI. Only use
23
#' when running from the command line.
24
# require(doMC)
25
# registerDoMC(3)
26
27
#' Load the data
28
data(edhec)
29
edhec.R <- edhec[,c("Convertible Arbitrage", "Equity Market Neutral",
30
"Fixed Income Arbitrage", "Event Driven", "CTA Global",
31
"Global Macro", "Long/Short Equity")]
32
33
#' Define function to compute annualized standard deviation
34
pasd <- function(R, weights){
35
as.numeric(StdDev(R=R, weights=weights)*sqrt(12)) # hardcoded for monthly data
36
# as.numeric(StdDev(R=R, weights=weights)*sqrt(4)) # hardcoded for quarterly data
37
}
38
39
#' Set some parameters
40
rebalance_period = 'quarters' # uses endpoints identifiers from xts
41
clean = "none" #"boudt"
42
permutations = 4000
43
44
#' Create initial portfolio object used to initialize ALL the bouy portfolios
45
init.portf <- portfolio.spec(assets=colnames(edhec.R),
46
weight_seq=generatesequence(by=0.005))
47
#' Add leverage constraint
48
init.portf <- add.constraint(portfolio=init.portf,
49
type="leverage",
50
min_sum=0.99,
51
max_sum=1.01)
52
#' Add box constraint
53
init.portf <- add.constraint(portfolio=init.portf,
54
type="box",
55
min=0.05,
56
max=0.3)
57
58
#' Add measure 1, mean return
59
init.portf <- add.objective(portfolio=init.portf,
60
type="return", # the kind of objective this is
61
name="mean", # name of the function
62
enabled=TRUE, # enable or disable the objective
63
multiplier=0 # calculate it but don't use it in the objective
64
)
65
66
#' Add measure 2, annualized standard deviation
67
init.portf <- add.objective(portfolio=init.portf,
68
type="risk", # the kind of objective this is
69
name="pasd", # to minimize from the sample
70
enabled=TRUE, # enable or disable the objective
71
multiplier=0 # calculate it but don't use it in the objective
72
)
73
74
#' Add measure 3, ES with confidence level p=(1-1/12)
75
p <- 1-1/12 # for monthly
76
77
init.portf <- add.objective(portfolio=init.portf,
78
type="risk", # the kind of objective this is
79
name="ES", # the function to minimize
80
enabled=FALSE, # enable or disable the objective
81
multiplier=0, # calculate it but don't use it in the objective
82
arguments=list(p=p)
83
)
84
85
#' Set up portfolio for Mean-mETL
86
MeanmETL.portf <- init.portf
87
MeanmETL.portf$objectives[[1]]$multiplier=-1 # mean
88
MeanmETL.portf$objectives[[3]]$enabled=TRUE # mETL
89
MeanmETL.portf$objectives[[3]]$multiplier=1 # mETL
90
91
#' Set up portfolio for min pasd
92
MinSD.portf <- init.portf
93
MinSD.portf$objectives[[2]]$multiplier=1
94
95
#' Set up portfolio for eqStdDev
96
EqSD.portf <- add.objective(portfolio=init.portf,
97
type="risk_budget",
98
name="StdDev",
99
min_concentration=TRUE,
100
arguments = list(p=(1-1/12)))
101
#' Without a sub-objective, we get a somewhat undefined result, since
102
#' there are (potentially) many Equal SD contribution portfolios.
103
EqSD.portf$objectives[[2]]$multiplier=1 # min pasd
104
105
#' Set up portfolio to maximize mean with mETL risk limit
106
MeanRL.portf <- add.objective(portfolio=init.portf,
107
type='risk_budget',
108
name="ES",
109
min_prisk=-Inf,
110
max_prisk=0.4,
111
arguments=list(method="modified", p=p))
112
MeanRL.portf$objectives[[1]]$multiplier=-1 # mean
113
#' Change box constraints max to vector of 1s
114
MeanRL.portf$constraints[[2]]$max=rep(1, 7)
115
116
#' Set the 'R' variable
117
R <- edhec.R
118
119
#' Start the optimizations
120
start_time<-Sys.time()
121
print(paste('Starting optimization at',Sys.time()))
122
123
#' Run the optimization
124
##### mean-mETL #####
125
MeanmETL.DE <- optimize.portfolio(R=R,
126
portfolio=MeanmETL.portf,
127
optimize_method="DEoptim",
128
trace=TRUE,
129
search_size=2000,
130
traceDE=5)
131
print(MeanmETL.DE)
132
print(MeanmETL.DE$elapsed_time)
133
chart.Weights(object=MeanmETL.DE, main="Mean-mETL Weights")
134
chart.RiskReward(object=MeanmETL.DE, return.col="mean", risk.col="ES")
135
# save(MeanmETL.DE, file=paste('MeanmETL',Sys.Date(),'rda',sep='.'))
136
137
# Evaluate the objectives with DE through time
138
# MeanmETL.DE.t <- optimize.portfolio.rebalancing(R=R,
139
# portfolio=MeanSD.portf,
140
# optimize_method="random",
141
# trace=TRUE,
142
# search_size=2000,
143
# rebalance_on=rebalance_period,
144
# training_period=36)
145
# MeanmETL.w = extractWeights.rebal(MeanmETL.DE.t)
146
# MeanmETL=Return.rebalancing(edhec.R, MeanmETL)
147
# colnames(MeanmETL) = "MeanmETL"
148
# save(MeanmETL.DE, MeanmETL.DE.t, MeanmETL.w, MeanmETL, file=paste('MeanmETL',Sys.Date(),'rda',sep='.'))
149
150
print(paste('Completed MeanmETL optimization at',Sys.time(),'moving on to MinSD'))
151
152
#' Run the optimization
153
##### min pasd #####
154
MinSD.DE <- optimize.portfolio(R=R,
155
portfolio=MinSD.portf,
156
optimize_method="DEoptim",
157
trace=TRUE,
158
search_size=2000,
159
traceDE=5)
160
print(MinSD.DE)
161
print(MinSD.DE$elapsed_time)
162
chart.Weights(object=MinSD.DE, plot.type="barplot", legend.loc=NULL)
163
chart.RiskReward(object=MinSD.DE, return.col="mean", risk.col="pasd")
164
# save(MinSD.DE, file=paste('MinSD',Sys.Date(),'rda',sep='.'))
165
166
print(paste('Completed MinSD optimization at',Sys.time(),'moving on to EqSD'))
167
168
#' Run the optimization
169
##### EqSD #####
170
EqSD.DE <- optimize.portfolio(R=R,
171
portfolio=EqSD.portf,
172
optimize_method="DEoptim",
173
trace=TRUE,
174
search_size=2000,
175
traceDE=5)
176
print(EqSD.DE)
177
print(EqSD.DE$elapsed_time)
178
# save(EqSD.DE, file=paste('EqSD',Sys.Date(),'rda',sep='.'))
179
180
chart.Weights(object=EqSD.DE)
181
chart.RiskReward(object=EqSD.DE, return.col="mean", risk.col="StdDev")
182
chart.RiskBudget(object=EqSD.DE, risk.type="absolute")
183
chart.RiskBudget(object=EqSD.DE, risk.type="pct_contrib")
184
185
print(paste('Completed EqSD optimization at',Sys.time(),'moving on to MeanRL'))
186
187
#' Run the optimization
188
##### MeanRL.DE #####
189
MeanRL.DE <- optimize.portfolio(R=R,
190
portfolio=MeanRL.portf,
191
optimize_method="DEoptim",
192
trace=TRUE,
193
search_size=2000,
194
traceDE=5)
195
print(MeanRL.DE)
196
print(MeanRL.DE$elapsed_time)
197
# save(MeanRL.DE, file=paste('MeanRL',Sys.Date(),'rda',sep='.'))
198
199
chart.Weights(object=MeanRL.DE)
200
chart.RiskBudget(object=MeanRL.DE, risk.type="pct_contrib", neighbors=25)
201
202
end_time<-Sys.time()
203
print("Optimization Complete")
204
print(end_time-start_time)
205
206