Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/symposium2013/analyze.HFindexes.R
1433 views
1
### For Presentation at FactSet's 2013 US Investment Process Symposium
2
# November 10 - 12 , 2013
3
# Peter Carl
4
5
### Description
6
# This script will generate a series of plots and csv data in the resultsdir
7
# for possible inclusion in slides.
8
9
### Make needed changes to workspace here ###
10
#
11
datadir = "./data/"
12
resultsdir = "./results/"
13
functionsdir = "./R/"
14
15
### Load the necessary packages
16
require(PerformanceAnalytics)
17
require(vcd) # for color palates
18
require(corrplot) # for correlation charts
19
require(gplots)
20
require(extrafont)
21
require(Cairo)
22
require(Hmisc)
23
24
### Graphics
25
# To insert in Powerpoint 2007 (gah!), graphics should be rendered as pdf objects using the Cario package for better font handling:
26
# > CairoPDF(file="ConcPercESContrib-mETL-wHull.pdf", height=5.5, width=9, family="Cambria")
27
# then, do post-processing with ImageMagick on Linux:
28
# $ convert -density 300 ConcPercESContrib-mETL-wHull.pdf -quality 100 -sharpen 0x1.0 ConcPercESContrib-mETL-wHull.png
29
# That appears to give a sharp, dense picture that shows well on slides. Use the pdf directly if possible, of course.
30
31
# Corporate colors and fonts
32
wb13color = c(
33
rgb(0,65,101, max=255), # Blair Blue
34
rgb(129,147,219, max=255), # Light Purple
35
rgb(0,133,102, max=255), # Dark Green
36
rgb(0,0,0, max=255), # Black
37
rgb(154,155,156, max=255), # Light Grey
38
rgb(0,122,201, max=255), # Dark Cyan
39
rgb(240,171,0, max=255), # Bright Orange
40
rgb(72,72,74, max=255), # Dark Grey
41
rgb(122,184,0, max=255), # Bright Green
42
rgb(87,6,140, max=255), # Dark Purple
43
rgb(220,80,52, max=255), # Dark Orange
44
rgb(243,211,17, max=255), # Yellow
45
rgb(61,183,228, max=255) # Bright Cyan
46
)
47
48
# Skewed-scale GrYlRd in WmB colors for correlation charts
49
skewedWB20 = c(colorpanel(16, "#008566","#E1E56D"), colorpanel(5, "#E1E56D", "#742414")[-1])
50
51
CairoFonts(
52
regular="Cambria:style=Regular",
53
bold="Cambria:style=Bold",
54
italic="Cambria:style=Italic",
55
bolditalic="Cambria:style=Bold Italic,BoldItalic",
56
symbol="Symbol"
57
)
58
59
par(las=1) # axis labels all horizontal
60
par(cex.lab=.8) # shrink axis labels
61
op <- par(no.readonly = TRUE)
62
63
### Set up color palates
64
pal <- function(col, border = "light gray", ...){
65
n <- length(col)
66
plot(0, 0, type="n", xlim = c(0, 1), ylim = c(0, 1),
67
axes = FALSE, xlab = "", ylab = "", ...)
68
rect(0:(n-1)/n, 0, 1:n/n, 1, col = col, border = border)
69
}
70
71
# Qualitative color scheme by Paul Tol
72
tol1qualitative=c("#4477AA")
73
tol2qualitative=c("#4477AA", "#CC6677")
74
tol3qualitative=c("#4477AA", "#DDCC77", "#CC6677")
75
tol4qualitative=c("#4477AA", "#117733", "#DDCC77", "#CC6677")
76
tol5qualitative=c("#332288", "#88CCEE", "#117733", "#DDCC77", "#CC6677")
77
tol6qualitative=c("#332288", "#88CCEE", "#117733", "#DDCC77", "#CC6677","#AA4499")
78
tol7qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#DDCC77", "#CC6677","#AA4499")
79
tol8qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677","#AA4499")
80
tol9qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677", "#882255", "#AA4499")
81
tol10qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#661100", "#CC6677", "#882255", "#AA4499")
82
83
# Constants
84
p=1-(1/12) #
85
Rf=.03/12 # Monthly risk free rate
86
colorset = wb13color
87
dataname="EDHEC"
88
89
########################################################################
90
# Load data
91
########################################################################
92
# Load the data objects from downloaded and parsed files
93
## See 'parse.EDHEC.R' and 'download.SP500TR.R'
94
95
# Load data from cache
96
load("./cache/edhec.RData")
97
load("./cache/SP500TR.RData")
98
99
# Drop some indexes and reorder
100
R = edhec[,c("Convertible Arbitrage", "Equity Market Neutral","Fixed Income Arbitrage", "Event Driven", "CTA Global", "Global Macro", "Long/Short Equity")]
101
R.names = colnames(R)
102
R.foldednames = sapply(colnames(R), function(x) paste(strwrap(x,10), collapse = "\n"), USE.NAMES=FALSE)
103
104
########################################################################
105
# Returns-based performance analysis
106
########################################################################
107
# --------------------------------------------------------------------
108
# Returns through time
109
# --------------------------------------------------------------------
110
CairoPDF(file=paste(resultsdir, dataname, "-Cumulative-Returns.pdf", sep=""), height=5.5, width=9)
111
layout(matrix(c(1, 2)), height = c(2, 1.3), width = 1)
112
par(mar = c(1, 4, 1, 2)) #c(bottom, left, top, right)
113
chart.CumReturns(R, main = "", xaxis = FALSE, legend.loc = "topleft", ylab = "Cumulative Return", colorset= wb13color, ylog=TRUE, wealth.index=TRUE, cex.legend=.7, cex.axis=.6, cex.lab=.7, las=1, pch="")
114
par(mar = c(4, 4, 0, 2))
115
chart.Drawdown(edhec.R, main = "", ylab = "Drawdown", colorset = wb13color, cex.axis=.6, cex.lab=.7, las=1)
116
par(op)
117
dev.off()
118
119
# --------------------------------------------------------------------
120
# Monthly Returns and Risk
121
# --------------------------------------------------------------------
122
# Done
123
CairoPDF(file=paste(resultsdir, dataname, "-BarVaR.pdf", sep=""), height=5.5, width=9)
124
# Generate charts of returns with ETL and VaR through time
125
par(mar=c(3, 4, 0, 2) + 0.1) #c(bottom, left, top, right)
126
charts.BarVaR(R[,1:4], p=p, gap=36, main="", show.greenredbars=TRUE,
127
methods=c("ModifiedES", "ModifiedVaR"), show.endvalue=TRUE,
128
colorset=rep("Black",7), ylim=c(-.1,.15), las=1, clean="boudt")
129
par(op)
130
dev.off()
131
CairoPDF(file=paste(resultsdir, dataname, "-BarVaR2.pdf", sep=""), height=5.5, width=9)
132
# Generate charts of returns with ETL and VaR through time
133
par(mar=c(3, 4, 0, 2) + 0.1) #c(bottom, left, top, right)
134
charts.BarVaR(R[,5:7], p=p, gap=36, main="", show.greenredbars=TRUE,
135
methods=c("ModifiedES", "ModifiedVaR"), show.endvalue=TRUE,
136
colorset=rep("Black",7), ylim=c(-.1,.15), las=1, clean="boudt")
137
par(op)
138
dev.off()
139
140
# --------------------------------------------------------------------
141
# Rolling Performance
142
# --------------------------------------------------------------------
143
CairoPDF(file=paste(resultsdir, dataname, "-RollPerf.pdf", sep=""), height=5.5, width=9)
144
# Generate charts of EDHEC index returns with ETL and VaR through time
145
par(mar=c(5, 4, 0, 2) + 0.1) #c(bottom, left, top, right)
146
charts.RollingPerformance(R, width=36, main="", pch="", colorset=wb13color, legend.loc="topleft", las=1)
147
par(op)
148
dev.off()
149
150
# --------------------------------------------------------------------
151
# Returns and Risk Scatter
152
# --------------------------------------------------------------------
153
CairoPDF(file=paste(resultsdir, dataname, "-Scatter36m.pdf", sep=""), height=5.5, width=4.5)
154
chart.RiskReturnScatter(last(edhec.R,36), main="EDHEC Index Trailing 36-Month Performance", colorset=wb13color, ylim=c(0,.2), xlim=c(0,.12), las=1)
155
dev.off()
156
CairoPDF(file=paste(resultsdir, dataname, "-ScatterSinceIncept.pdf", sep=""), height=5.5, width=4.5)
157
chart.RiskReturnScatter(edhec.R, main="EDHEC Index Since Inception Performance", colorset=wb13color, ylim=c(0,.2), xlim=c(0,.12), las=1)
158
dev.off()
159
160
# --------------------------------------------------------------------
161
# Table of Return and Risk Statistics
162
# --------------------------------------------------------------------
163
# @TODO: Too small, break into two panels?
164
source(paste(functionsdir,'table.RiskStats.R', sep=""))
165
incept.stats = t(table.RiskStats(R=R, p=p, Rf=Rf))
166
write.csv(incept.stats, file=paste(resultsdir, dataname, "-inception-stats.csv", sep=""))
167
CairoPDF(file=paste(resultsdir, dataname, "-InceptionStats.pdf", sep=""), height=5.5, width=4.5)
168
textplot(format.df(incept.stats, na.blank=TRUE, numeric.dollar=FALSE, cdec=c(3,3,1,3,1,3,3,1,3,3,1,1,3,3,1,0), rmar = 0.8, cmar = 1, max.cex=.9, halign = "center", valign = "top", row.valign="center", wrap.rownames=20, wrap.colnames=10, mar = c(0,0,4,0)+0.1))
169
dev.off()
170
171
# --------------------------------------------------------------------
172
# Compare Distributions
173
# --------------------------------------------------------------------
174
#
175
CairoPDF(file=paste(resultsdir, dataname, "-Distributions.pdf", sep=""), height=5.5, width=9)
176
#source(paste(functionsdir, "/page.Distributions", sep=""))
177
page.Distributions(R[,1:4], colorset=wb13color, las=1)
178
dev.off()
179
180
CairoPDF(file=paste(resultsdir, dataname, "-Distributions2.pdf", sep=""), height=5.5, width=9)
181
#source(paste(functionsdir, "/page.Distributions", sep=""))
182
page.Distributions(R[,5:7], colorset=wb13color, las=1)
183
dev.off()
184
185
# --------------------------------------------------------------------
186
# Correlation Panels
187
# --------------------------------------------------------------------
188
# col3 <- colorRampPalette(c("darkgreen", "white", "darkred"))
189
M <- cor(R)
190
colnames(M) = rownames(M)
191
order.hc2 <- corrMatOrder(M, order="hclust", hclust.method="complete")
192
M.hc2 <- M[order.hc2,order.hc2]
193
CairoPDF(file=paste(resultsdir, dataname, "-cor-inception.pdf", sep=""), height=5.5, width=4.5)
194
corrplot(M.hc2, tl.col="black", tl.cex=0.8, method="shade", col=skewedWB20, cl.offset=.75, cl.cex=.7, cl.align.text="l", cl.ratio=.25, shade.lwd=0, cl.length=11)
195
corrRect.hclust(M.hc2, k=3, method="complete", col="blue")
196
dev.off()
197
198
M36 <- cor(last(R,36))
199
colnames(M36) = rownames(M36) = rownames(M)
200
order36.hc2 <- corrMatOrder(M36, order="hclust", hclust.method="complete")
201
M36.hc2 <- M36[order36.hc2,order36.hc2]
202
CairoPDF(file=paste(resultsdir, dataname, "-cor-tr36m.pdf", sep=""), height=5.5, width=4.5)
203
corrplot(M36.hc2, tl.col="black", tl.cex=0.8, method="shade", col=skewedWB20, cl.offset=.75, cl.cex=.7, cl.align.text="l", cl.ratio=.25, shade.lwd=0, cl.length=11)
204
corrRect.hclust(M36.hc2, k=3, method="complete", col="blue")
205
dev.off()
206
207
# --------------------------------------------------------------------
208
# Table of Return correlations
209
# --------------------------------------------------------------------
210
211
write.csv(M, file=paste(resultsdir, dataname, "-inception-cor.csv", sep=""))
212
colnames(M)=R.foldednames
213
# write(print(xtable(M, digits=1, align=rep("c",8)), type="html", html.table.attributes = "border = '0', align = 'center'"), file=paste(resultsdir, dataname, "-inception-cor.html", sep=""))
214
# write(print(xtable(M, digits=1, align=rep("c",8))), file=paste(resultsdir, dataname, "-inception-cor.latex", sep=""))
215
# write(pandoc.table.return(M, digits=1, split.tables=Inf), file=paste(resultsdir, dataname, "-inception-cor.md", sep=""))
216
217
# --------------------------------------------------------------------
218
# Rolling Correlation to S&P500 TR
219
# --------------------------------------------------------------------
220
221
CairoPDF(file=paste(resultsdir, dataname, "-RollCorr.pdf", sep=""), height=5.5, width=9)
222
chart.RollingCorrelation(R,SP500.TR, width=24, legend.loc=NULL, colorset=wb13color, main="Rolling 24-Month Correlation to S&P500 TR", las=1)
223
legend("bottomleft", legend=colnames(R), inset = 0.02, border.col="darkgrey", lwd=3, col=wb13color, cex=0.7, y.intersp=1.1)
224
dev.off()
225
226
# --------------------------------------------------------------------
227
# Autocorrelation
228
# --------------------------------------------------------------------
229
230
# require(Hmisc)
231
AC.stats = t(table.Autocorrelation(R=R))
232
write.csv(AC.stats, file=paste(resultsdir, dataname, "-AC-stats.csv", sep=""))
233
CairoPDF(file=paste(resultsdir, dataname, "-ACStats.pdf", sep=""), height=5.5, width=4.5)
234
# sort by p-value
235
AC.order = order(AC.stats[,7], decreasing=FALSE)
236
textplot(format.df(AC.stats[AC.order,], na.blank=TRUE, numeric.dollar=FALSE, rdec=c(rep(4,dim(AC.stats)[1])), col.just=rep("nc",dim(AC.stats)[2])), rmar = 0.7, cmar = 0.9, max.cex=1, halign = "center", valign = "center", row.valign="center", wrap.rownames=50, wrap.colnames=10)
237
dev.off()
238
239
CairoPDF(file=paste(resultsdir, dataname, "-ACStackedBars.pdf", sep=""), height=5.5, width=9)
240
rownames(AC.stats)= sapply(colnames(R), function(x) paste(strwrap(x,10), collapse = "\n"), USE.NAMES=FALSE)
241
chart.StackedBar(as.matrix(AC.stats[,1:6]), colorset=bluemono, main="Observed Autocorrelation", las=1)
242
dev.off()
243
244
# --------------------------------------------------------------------
245
# ETL parameterization charts
246
# --------------------------------------------------------------------
247
# Requires a recent modification to the chart in PerformanceAnalytics to make the y-axes match; in revision 3191
248
source('./R/chart.VaRSensitivity.R')
249
CairoPDF(file=paste(resultsdir, dataname, "-ETL-sensitivity.pdf", sep=""), height=5.5, width=9)
250
layout(matrix(c(1:8), nrow=2))
251
par(mar = c(4, 4, 5, 2)+0.1) #c(bottom, left, top, right)
252
for(i in 1:NCOL(R)){
253
chart.VaRSensitivity(R[,i], methods=c("ModifiedES","HistoricalES", "GaussianES"), legend.loc=NULL, clean="boudt", colorset=wb13color, lty=c(2,1,2), lwd=3, main=R.names[i], ylim=c(-0.09,0), ylab="Expected Tail Loss", las=1) #c("orange", "black", "darkgray")
254
abline(v = 1-1/12, col = wb13color[11], lty = 2, lwd=1)
255
}
256
plot.new()
257
legend("center", legend=c("Modified \nETL","Historical \nETL", "Gaussian \nETL"), lty=c(2,1,2), lwd=3, col=wb13color, cex=1.2, y.intersp=2, box.col="darkgrey")
258
par(op)
259
dev.off()
260
261
262