Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/riskbudgetpaper(superseded)/R_interpretation/stackedweightriskcontributionplot.R
1717 views
1
#################################################################################
2
# Create stacked weights and risk contributions plot
3
#################################################################################
4
5
# ! Set your working directory (folder containing the subfolders R_allocation, R_interpretation, data, weights, etc)
6
7
setwd("c:/Documents and Settings/Administrator/Desktop/risk budget programs")
8
9
10
# Options:
11
################
12
13
# specify the number of years used for the estimation
14
estyears = 8;
15
16
# Load programs
17
18
source("R_interpretation/chart.StackedBar.R");
19
library(zoo); library(PerformanceAnalytics)
20
21
# number of risky assets
22
firstyear = 1976 ; firstquarter = 1; lastyear = 2010; lastquarter = 2;
23
cAssets = 4
24
25
# "MinRisk_ReturnTarget" "EqualRisk"
26
# "MinRiskConc_ReturnTarget"
27
28
names = c( "EqualWeight" , "MinRisk" , "MinRisk_PositionLimit" , "MinRisk_RiskLimit" ,
29
"MinRiskConc" , "MinRiskConc_PositionLimit", "EqualRisk" ,
30
"MinRisk_ReturnTarget", "MinRiskConc_ReturnTarget" )
31
32
namelabels = c( "Equal-Weight" , "Min CVaR" , "Min CVaR + 40% Position Limit" , "Min CVaR + 40% CVaR Alloc Limit" ,
33
"Min CVaR Concentration" , "Min CVaR Concentration + 40% Position Limit", "Min CVaR + ERC constraint" , "Min CVaR + Return Target" , "Min CVaR Conc + Return Target" )
34
35
# frequency of rebalancing: yearly of quarterly
36
frequency = "quarterly"
37
# Load portfolio weights:
38
weightsS1 = read.csv( file = paste("weights/", names[1], ".csv" , sep="") );
39
weightsS2 = read.csv( file = paste("weights/", names[2], ".csv" , sep="") );
40
weightsS3 = read.csv( file = paste("weights/", names[3], ".csv" , sep="") );
41
weightsS4 = read.csv( file = paste("weights/", names[4], ".csv" , sep="") );
42
weightsS5 = read.csv( file = paste("weights/", names[5], ".csv" , sep="") );
43
weightsS6 = read.csv( file = paste("weights/", names[6], ".csv" , sep="") );
44
weightsS7 = read.csv( file = paste("weights/", names[7], ".csv" , sep="") );
45
46
47
# Load percentage risk contributions:
48
riskcontS1 = read.csv( file = paste("riskcont/", names[1], ".csv" , sep="") );
49
riskcontS2 = read.csv( file = paste("riskcont/", names[2], ".csv" , sep="") );
50
riskcontS3 = read.csv( file = paste("riskcont/", names[3], ".csv" , sep="") );
51
riskcontS4 = read.csv( file = paste("riskcont/", names[4], ".csv" , sep="") );
52
riskcontS5 = read.csv( file = paste("riskcont/", names[5], ".csv" , sep="") );
53
riskcontS6 = read.csv( file = paste("riskcont/", names[6], ".csv" , sep="") );
54
riskcontS7 = read.csv( file = paste("riskcont/", names[7], ".csv" , sep="") );
55
56
if(frequency=="yearly"){
57
rebal.names = seq( (firstyear+estyears),lastyear+1,1)
58
}else{
59
60
# Name labels using quarters:
61
rebal.names = paste(rep( seq( (firstyear+estyears),lastyear,1) , each=4),c("Q1","Q2","Q3","Q4"),sep="")
62
rebal.names = c( rebal.names , paste( lastyear+1, "Q1" , sep="" ) )
63
rebal.names = rebal.names[firstquarter:(length(rebal.names)-4+lastquarter)]
64
65
# Name labels using months:
66
nominalreturns = TRUE;
67
if(nominalreturns){ load(file="monthlyR.RData") }else{ load(file="monthlyR_real.RData") }
68
ep = endpoints(monthlyR,on='quarters')
69
# select those for estimation period
70
ep.start = ep[1:(length(ep)-estyears*4)]+1
71
from = time(monthlyR)[ep.start]
72
from = seq( as.Date(paste(firstyear,"-01-01",sep="")), as.Date(paste(lastyear-estyears,"-07-01",sep="")), by="3 month")
73
ep.end = ep[(1+estyears*4):length(ep)]
74
to = time(monthlyR)[ep.end]
75
rebal.names = as.yearmon(to+1)
76
77
78
}
79
80
81
rownames(weightsS1) = rownames(weightsS2) = rownames(weightsS3) = rownames(weightsS4) = rebal.names;
82
rownames(weightsS5) = rownames(weightsS6) = rownames(weightsS7) = rebal.names;
83
84
rownames(riskcontS1) = rownames(riskcontS2) = rownames(riskcontS3) = rownames(riskcontS4) = rebal.names;
85
rownames(riskcontS5) = rownames(riskcontS6) = rownames(riskcontS7) = rebal.names;
86
87
88
colorset = gray( seq(0,(cAssets-1),1)/cAssets ) ;
89
#due to rounding, the sum of the risk contributions is sometimes 1 + epsilon: avoid this in plot
90
91
riskcontS1 = riskcontS1/rowSums(riskcontS1); riskcontS2 = riskcontS2/rowSums(riskcontS2);
92
riskcontS3 = riskcontS3/rowSums(riskcontS3); riskcontS4 = riskcontS4/rowSums(riskcontS4);
93
riskcontS5 = riskcontS5/rowSums(riskcontS5); riskcontS6 = riskcontS6/rowSums(riskcontS6);
94
riskcontS7 = riskcontS7/rowSums(riskcontS7);
95
96
w.names = c( "US bond" , "S&P 500", "EAFE" , "GSCI" )
97
l = 2
98
mar1 =c(2,l,2,1.1)
99
mar2 =c(0,l,2,1)
100
mar3 = c(3,l+1,3,0.1)
101
mar4 = c(2,l+1,2,0.1)
102
103
# Stacked weights plot:
104
postscript('stackedweightsriskcont_benchmark.eps')
105
layout( matrix( c(1,2,3,4,5,6,7,4), ncol = 2 ) , height= c(1.5,1.5,1.5,0.7), width=1)
106
107
par(mar=mar3 , cex.main=1)
108
chart.StackedBar2(weightsS2,col=colorset,space=0, main = namelabels[2], ylab="Weight allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
109
chart.StackedBar2(weightsS5,col=colorset,space=0, main = namelabels[5], ylab="Weight allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
110
chart.StackedBar2(weightsS7,col=colorset,space=0, main = namelabels[7], ylab="Weight allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T, legend.loc = NULL,ylim=c(0,1),border = F )
111
112
par(mar=mar1 , cex.main=1)
113
plot.new()
114
legend("center",legend=w.names,col=colorset,lwd=6,ncol=4)
115
116
117
118
par(mar=mar3 , cex.main=1)
119
chart.StackedBar2(riskcontS2,col=colorset,space=0, main = namelabels[2], ylab="CVaR allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
120
chart.StackedBar2(riskcontS5,col=colorset,space=0, main = namelabels[5], ylab="CVaR allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
121
chart.StackedBar2(riskcontS1,col=colorset,space=0, main = namelabels[1], ylab="CVaR allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
122
123
dev.off()
124
125
postscript('MinCVaR_alternatives.eps')
126
layout( matrix( c(1,2,3,4,5,6,7,4), ncol = 2 ) , height= c(1.5,1.5,1.5,0.7), width=1)
127
128
par(mar=mar3 , cex.main=1)
129
chart.StackedBar2(weightsS3,col=colorset,space=0, main = namelabels[3], ylab="Weight allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T, legend.loc = NULL,ylim=c(0,1),border = F )
130
chart.StackedBar2(weightsS4,col=colorset,space=0, main = namelabels[4], ylab="Weight allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
131
chart.StackedBar2(weightsS6,col=colorset,space=0, main = namelabels[6], ylab="Weight allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
132
133
par(mar=mar1 , cex.main=1)
134
plot.new()
135
legend("center",legend=w.names,col=colorset,lwd=6,ncol=4)
136
par(mar=mar3 , cex.main=1)
137
138
chart.StackedBar2(riskcontS3,col=colorset,space=0, main = namelabels[3], ylab="CVaR allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
139
chart.StackedBar2(riskcontS4,col=colorset,space=0, main = namelabels[4], ylab="CVaR allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
140
chart.StackedBar2(riskcontS6,col=colorset,space=0, main = namelabels[6], ylab="CVaR allocation", las=1, l=3.9, r=0, cex.axis=1, cex.lab=1, cex.main=1, axisnames=T,legend.loc = NULL,ylim=c(0,1),border = F )
141
142
dev.off()
143
144
145
#############################################################################################
146
# Plot the CVaR of the portfolios for each period, relatively to CVaR minimum CVaR portfolio
147
148
149
source("R_Allocation/Risk_budget_functions.R");
150
library(zoo); library(fGarch); library("PerformanceAnalytics");
151
152
# downside risk
153
alpha = alphariskbudget = 0.05;
154
155
# Load the data
156
157
nominalreturns = T;
158
if(nominalreturns){ load(file="monthlyR.RData") }else{ load(file="monthlyR_real.RData") }
159
R = monthlyR
160
161
# Define rebalancing periods:
162
163
ep = endpoints(monthlyR,on='quarters')
164
# select those for estimation period
165
ep.start = ep[1:(length(ep)-estyears*4)]+1
166
from = time(monthlyR)[ep.start]; from = seq( as.Date(paste(firstyear,"-01-01",sep="")), as.Date(paste(lastyear-estyears,"-07-01",sep="")), by="3 month")
167
ep.end = ep[(1+estyears*4):length(ep)]
168
to = time(monthlyR)[ep.end]
169
cPeriods = length(from);
170
171
# Loop where for each rebalancing period:
172
# - Compute total CVaR of portfolio
173
174
mCVaR = mMU = c()
175
176
for( per in c(1:cPeriods) ){
177
178
# At the end of each month, we compute the CVaR
179
enddates = na.omit(time(window( monthlyR , start = as.Date(to[per]) , end = as.Date(to[per]+90) ),on='months')[1:3])
180
181
for( enddate in enddates ){
182
183
# add a loop over the next months except when per = cPeriods or -1,-2
184
185
# Estimate GARCH model with data from inception
186
187
inception.R = window(R, start = as.Date(from[1]) , end = enddate );
188
189
# Estimate comoments of innovations with rolling estimation windows
190
in.sample.R = window(R, start = as.Date(from[per]) , end = as.Date(to[per]) );
191
in.sample.R = checkData(in.sample.R, method="matrix");
192
193
# Estimation of mean return
194
M = c();
195
library(TTR)
196
Tmean = 47 # monthly returns: 4 year exponentially weighted moving average
197
for( i in 1:cAssets ){
198
M = cbind( M , as.vector( EMA(x=inception.R[,i],n=Tmean) ) ) #2/(n+1)
199
}
200
M = zoo( M , order.by=time(inception.R) )
201
202
# Center returns (shift by one observations since M[t,] is rolling mean t-Tmean+1,...,t; otherwise lookahead bias)
203
inception.R.cent = inception.R;
204
ZZ = matrix( rep(as.vector( apply( inception.R[1:Tmean, ] , 2 , 'mean' )),Tmean),byrow=T,nrow=Tmean);
205
inception.R.cent[1:Tmean,] = inception.R[1:Tmean, ] - ZZ;
206
if( nrow(inception.R)>(Tmean+1) ){
207
A = M[Tmean:(nrow(inception.R)-1),];
208
A = zoo( A , order.by = time(inception.R[(Tmean+1):nrow(inception.R), ])) ; #shift dates; otherwise zoo poses problem
209
inception.R.cent[(Tmean+1):nrow(inception.R), ] = inception.R[(Tmean+1):nrow(inception.R), ] - A}
210
211
# Garch estimation
212
S = c();
213
for( i in 1:cAssets ){
214
gout = garchFit(formula ~ garch(1,1), data = inception.R.cent[,i],include.mean = F, cond.dist="QMLE", trace = FALSE )
215
if( as.vector(gout@fit$coef["alpha1"]) < 0.01 ){
216
sigmat = rep( sd( as.vector(inception.R.cent[,i])), length(inception.R.cent[,i]) );
217
}else{
218
sigmat = gout@sigma.t
219
}
220
S = cbind( S , sigmat)
221
}
222
S = zoo( S , order.by=time(inception.R.cent) )
223
224
# Estimate correlation, coskewness and cokurtosis matrix locally using cleaned innovation series in three year estimation window
225
selectU = window(inception.R.cent, start = as.Date(from[per]) , end = as.Date(to[per]) )
226
selectU = selectU/window(S, start = as.Date(from[per]) , end = as.Date(to[per]) );
227
selectU = clean.boudt2(selectU , alpha = 0.05 )[[1]];
228
Rcor = cor(selectU)
229
D = diag( as.vector(tail(S,n=1) ),ncol=cAssets )
230
sigma = D%*%Rcor%*%D
231
232
# we only need mean and conditional covariance matrix of last observation
233
mu = matrix(tail(M,n=1),ncol=1 ) ;
234
D = diag( as.vector(as.vector(tail(S,n=1) ) ),ncol=cAssets )
235
sigma = D%*%Rcor%*%D
236
in.sample.T = nrow(selectU);
237
# set volatility of all U to last observation, such that cov(rescaled U)=sigma
238
selectU = selectU*matrix( rep(as.vector(tail(S,n=1)),in.sample.T ) , ncol = cAssets , byrow = T )
239
M3 = PerformanceAnalytics:::M3.MM(selectU)
240
M4 = PerformanceAnalytics:::M4.MM(selectU)
241
242
CVaR_period = c( operPortMES(as.numeric(weightsS1[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,
243
operPortMES(as.numeric(weightsS2[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,
244
operPortMES(as.numeric(weightsS3[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,
245
operPortMES(as.numeric(weightsS4[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,
246
operPortMES(as.numeric(weightsS5[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,
247
operPortMES(as.numeric(weightsS6[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,
248
operPortMES(as.numeric(weightsS7[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] )
249
250
mu_period = c( sum(as.numeric(weightsS1[per,])*mu) , sum(as.numeric(weightsS2[per,])*mu) ,
251
sum(as.numeric(weightsS3[per,])*mu) , sum(as.numeric(weightsS4[per,])*mu) ,
252
sum(as.numeric(weightsS5[per,])*mu) , sum(as.numeric(weightsS6[per,])*mu) ,
253
sum(as.numeric(weightsS7[per,])*mu) )
254
255
mCVaR = rbind( mCVaR , CVaR_period )
256
mMU = rbind( mMU , mu_period )
257
}
258
}
259
260
colnames(mCVaR) = colnames(mMU) = names[1:7]
261
mCVaR = xts( mCVaR ,
262
order.by = as.Date(time( window( monthlyR , start = as.Date(to[1]) , end = as.Date(to[cPeriods]) ))+1))
263
mMU = xts( mMU ,
264
order.by = as.Date(time( window( monthlyR , start = as.Date(to[1]) , end = as.Date(to[cPeriods]) ))+1))
265
266
head(mCVaR[,1:7],2)
267
#> head(mCVaR[,1:7],2)
268
# EqualWeight MinRisk MinRisk_PositionLimit MinRisk_RiskLimit MinRiskConc MinRiskConc_PositionLimit EqualRisk
269
#1984-01-01 0.0492 0.0320 0.0380 0.0333 0.0352 0.0388 0.0352
270
#1984-02-01 0.0490 0.0304 0.0374 0.0322 0.0344 0.0383 0.0344
271
save(mCVaR, file="mCVaR.Rdata")
272
273
274
head(mMU[,1:7],2)
275
#> head(mMU[,1:7],2)
276
# EqualWeight MinRisk MinRisk_PositionLimit MinRisk_RiskLimit MinRiskConc MinRiskConc_PositionLimit EqualRisk
277
#1984-01-01 0.009865862 0.00959764 0.01084905 0.009814883 0.009944563 0.01012198 0.009945766
278
#1984-02-01 0.010176409 0.01003861 0.01105078 0.010193260 0.010297694 0.01042968 0.010299787
279
save(mMU, file="mMU.Rdata")
280
281
###################################################
282
283
load(file="mCVaR.Rdata")
284
load(file="mMU.Rdata")
285
286
postscript(file="portfolioMeanCVaR.eps")
287
par(mfrow=c(2,1),mar=c(3,2,3,2))
288
289
290
291
plot( mMU[,1]*12 , type = "l" , ylim=c(min(mMU),max(mMU))*12,col="darkgray", lwd=1.5 ,
292
main = "Expected annualized portfolio return" )
293
lines( mMU[,2]*12 , type = "l", col="black",lwd=2 , lty=3)
294
lines( mMU[,7]*12 , type = "l", col="darkgray",lwd=4)
295
lines( mMU[,5]*12 , type = "l", col="black", lwd=1.5)
296
297
legend("bottomleft", legend = c("Equal-Weight","Min CVaR Concentration","Min CVaR+ERC constraint","Min CVaR" ),
298
col=c("darkgray","black","darkgray","black"), lty=c("solid","solid","solid","dashed"), lwd=c(2,2,4,2) ,cex=0.7)
299
300
plot( mCVaR[,1] , type = "l" , ylim=c(0,max(mCVaR)),col="darkgray", lwd=1.5 , main = "Portfolio CVaR" )
301
lines( mCVaR[,2] , type = "l", col="black",lwd=1.5 , lty=3)
302
lines( mCVaR[,7] , type = "l", col="darkgray",lwd=4)
303
lines( mCVaR[,5] , type = "l", col="black", lwd=1.5)
304
dev.off()
305
306
# do not plot the last month such that it is fully comparable with out-of-sample plots
307
308
sel = c( 1 : (nrow(mCVaR)-1) );
309
310
311
# Bear periods
312
sp500 = window (monthlyR , start = from[1] , end = to[ length(to) ] )[,2]
313
bear = c(1:length(sp500))[sp500<mean(sp500)]
314
bear = c(1:length(sp500))[sp500<(-0.12)]
315
m.bear.dates = list();
316
i=1;
317
for( b in bear){
318
m.bear.dates[[i]] = c( b-0.5, b+0.5)
319
i = i + 1;
320
}
321
322
out = table.Drawdowns(sp500,top=10)
323
start.bear = out$From[out$Depth<(-0.12)]
324
end.bear = out$Trough[out$Depth<(-0.12)]
325
start.bear.index = c(1:length(sp500))[ time(sp500) ]
326
m.bear.dates = list()
327
v.bear.dates = c()
328
for( i in 1:length(start.bear) ){
329
m.bear.dates[[i]] = c( as.yearmon(start.bear[i]) , as.yearmon(end.bear[i]) )
330
v.bear.dates = c( v.bear.dates , seq(start.bear[i],end.bear[i],"days") )
331
}
332
v.bear.dates = as.Date( v.bear.dates )
333
334
335
postscript(file="portfolioCVaR.eps")
336
par(mfrow=c(2,1),mar=c(3,4,1,2))
337
338
chart.TimeSeries( mCVaR[sel,c(1,5,2)] , ylim=c(0,max(mCVaR)), ylab = "Portfolio CVaR" , main = "",
339
col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2,2) ,
340
auto.grid = TRUE, minor.ticks = FALSE ,
341
period.areas = m.bear.dates , period.color="lightgray",
342
date.format.in = "%Y-%m-%d",date.format = "%b %Y")
343
344
legend("topleft", legend = namelabels[c(1,5,2)],
345
col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2) ,cex=0.7)
346
347
chart.TimeSeries( mCVaR[sel,c(4,3,6)] , type = "l" , ylim=c(0,max(mCVaR)), ylab = "Portfolio CVaR" , main = "",
348
col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2,2) ,
349
auto.grid = TRUE, minor.ticks = FALSE ,
350
period.areas = m.bear.dates , period.color="lightgray",
351
date.format.in = "%Y-%m-%d",date.format = "%b %Y")
352
353
legend("topleft", legend = namelabels[c(4,3,6)],
354
col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2) ,cex=0.7)
355
356
357
dev.off()
358
359
360
361
362
363