Path: blob/master/sandbox/symposium2013/analyze.HFindexes.R
1433 views
### For Presentation at FactSet's 2013 US Investment Process Symposium1# November 10 - 12 , 20132# Peter Carl34### Description5# This script will generate a series of plots and csv data in the resultsdir6# for possible inclusion in slides.78### Make needed changes to workspace here ###9#10datadir = "./data/"11resultsdir = "./results/"12functionsdir = "./R/"1314### Load the necessary packages15require(PerformanceAnalytics)16require(vcd) # for color palates17require(corrplot) # for correlation charts18require(gplots)19require(extrafont)20require(Cairo)21require(Hmisc)2223### Graphics24# To insert in Powerpoint 2007 (gah!), graphics should be rendered as pdf objects using the Cario package for better font handling:25# > CairoPDF(file="ConcPercESContrib-mETL-wHull.pdf", height=5.5, width=9, family="Cambria")26# then, do post-processing with ImageMagick on Linux:27# $ convert -density 300 ConcPercESContrib-mETL-wHull.pdf -quality 100 -sharpen 0x1.0 ConcPercESContrib-mETL-wHull.png28# That appears to give a sharp, dense picture that shows well on slides. Use the pdf directly if possible, of course.2930# Corporate colors and fonts31wb13color = c(32rgb(0,65,101, max=255), # Blair Blue33rgb(129,147,219, max=255), # Light Purple34rgb(0,133,102, max=255), # Dark Green35rgb(0,0,0, max=255), # Black36rgb(154,155,156, max=255), # Light Grey37rgb(0,122,201, max=255), # Dark Cyan38rgb(240,171,0, max=255), # Bright Orange39rgb(72,72,74, max=255), # Dark Grey40rgb(122,184,0, max=255), # Bright Green41rgb(87,6,140, max=255), # Dark Purple42rgb(220,80,52, max=255), # Dark Orange43rgb(243,211,17, max=255), # Yellow44rgb(61,183,228, max=255) # Bright Cyan45)4647# Skewed-scale GrYlRd in WmB colors for correlation charts48skewedWB20 = c(colorpanel(16, "#008566","#E1E56D"), colorpanel(5, "#E1E56D", "#742414")[-1])4950CairoFonts(51regular="Cambria:style=Regular",52bold="Cambria:style=Bold",53italic="Cambria:style=Italic",54bolditalic="Cambria:style=Bold Italic,BoldItalic",55symbol="Symbol"56)5758par(las=1) # axis labels all horizontal59par(cex.lab=.8) # shrink axis labels60op <- par(no.readonly = TRUE)6162### Set up color palates63pal <- function(col, border = "light gray", ...){64n <- length(col)65plot(0, 0, type="n", xlim = c(0, 1), ylim = c(0, 1),66axes = FALSE, xlab = "", ylab = "", ...)67rect(0:(n-1)/n, 0, 1:n/n, 1, col = col, border = border)68}6970# Qualitative color scheme by Paul Tol71tol1qualitative=c("#4477AA")72tol2qualitative=c("#4477AA", "#CC6677")73tol3qualitative=c("#4477AA", "#DDCC77", "#CC6677")74tol4qualitative=c("#4477AA", "#117733", "#DDCC77", "#CC6677")75tol5qualitative=c("#332288", "#88CCEE", "#117733", "#DDCC77", "#CC6677")76tol6qualitative=c("#332288", "#88CCEE", "#117733", "#DDCC77", "#CC6677","#AA4499")77tol7qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#DDCC77", "#CC6677","#AA4499")78tol8qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677","#AA4499")79tol9qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677", "#882255", "#AA4499")80tol10qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#661100", "#CC6677", "#882255", "#AA4499")8182# Constants83p=1-(1/12) #84Rf=.03/12 # Monthly risk free rate85colorset = wb13color86dataname="EDHEC"8788########################################################################89# Load data90########################################################################91# Load the data objects from downloaded and parsed files92## See 'parse.EDHEC.R' and 'download.SP500TR.R'9394# Load data from cache95load("./cache/edhec.RData")96load("./cache/SP500TR.RData")9798# Drop some indexes and reorder99R = edhec[,c("Convertible Arbitrage", "Equity Market Neutral","Fixed Income Arbitrage", "Event Driven", "CTA Global", "Global Macro", "Long/Short Equity")]100R.names = colnames(R)101R.foldednames = sapply(colnames(R), function(x) paste(strwrap(x,10), collapse = "\n"), USE.NAMES=FALSE)102103########################################################################104# Returns-based performance analysis105########################################################################106# --------------------------------------------------------------------107# Returns through time108# --------------------------------------------------------------------109CairoPDF(file=paste(resultsdir, dataname, "-Cumulative-Returns.pdf", sep=""), height=5.5, width=9)110layout(matrix(c(1, 2)), height = c(2, 1.3), width = 1)111par(mar = c(1, 4, 1, 2)) #c(bottom, left, top, right)112chart.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="")113par(mar = c(4, 4, 0, 2))114chart.Drawdown(edhec.R, main = "", ylab = "Drawdown", colorset = wb13color, cex.axis=.6, cex.lab=.7, las=1)115par(op)116dev.off()117118# --------------------------------------------------------------------119# Monthly Returns and Risk120# --------------------------------------------------------------------121# Done122CairoPDF(file=paste(resultsdir, dataname, "-BarVaR.pdf", sep=""), height=5.5, width=9)123# Generate charts of returns with ETL and VaR through time124par(mar=c(3, 4, 0, 2) + 0.1) #c(bottom, left, top, right)125charts.BarVaR(R[,1:4], p=p, gap=36, main="", show.greenredbars=TRUE,126methods=c("ModifiedES", "ModifiedVaR"), show.endvalue=TRUE,127colorset=rep("Black",7), ylim=c(-.1,.15), las=1, clean="boudt")128par(op)129dev.off()130CairoPDF(file=paste(resultsdir, dataname, "-BarVaR2.pdf", sep=""), height=5.5, width=9)131# Generate charts of returns with ETL and VaR through time132par(mar=c(3, 4, 0, 2) + 0.1) #c(bottom, left, top, right)133charts.BarVaR(R[,5:7], p=p, gap=36, main="", show.greenredbars=TRUE,134methods=c("ModifiedES", "ModifiedVaR"), show.endvalue=TRUE,135colorset=rep("Black",7), ylim=c(-.1,.15), las=1, clean="boudt")136par(op)137dev.off()138139# --------------------------------------------------------------------140# Rolling Performance141# --------------------------------------------------------------------142CairoPDF(file=paste(resultsdir, dataname, "-RollPerf.pdf", sep=""), height=5.5, width=9)143# Generate charts of EDHEC index returns with ETL and VaR through time144par(mar=c(5, 4, 0, 2) + 0.1) #c(bottom, left, top, right)145charts.RollingPerformance(R, width=36, main="", pch="", colorset=wb13color, legend.loc="topleft", las=1)146par(op)147dev.off()148149# --------------------------------------------------------------------150# Returns and Risk Scatter151# --------------------------------------------------------------------152CairoPDF(file=paste(resultsdir, dataname, "-Scatter36m.pdf", sep=""), height=5.5, width=4.5)153chart.RiskReturnScatter(last(edhec.R,36), main="EDHEC Index Trailing 36-Month Performance", colorset=wb13color, ylim=c(0,.2), xlim=c(0,.12), las=1)154dev.off()155CairoPDF(file=paste(resultsdir, dataname, "-ScatterSinceIncept.pdf", sep=""), height=5.5, width=4.5)156chart.RiskReturnScatter(edhec.R, main="EDHEC Index Since Inception Performance", colorset=wb13color, ylim=c(0,.2), xlim=c(0,.12), las=1)157dev.off()158159# --------------------------------------------------------------------160# Table of Return and Risk Statistics161# --------------------------------------------------------------------162# @TODO: Too small, break into two panels?163source(paste(functionsdir,'table.RiskStats.R', sep=""))164incept.stats = t(table.RiskStats(R=R, p=p, Rf=Rf))165write.csv(incept.stats, file=paste(resultsdir, dataname, "-inception-stats.csv", sep=""))166CairoPDF(file=paste(resultsdir, dataname, "-InceptionStats.pdf", sep=""), height=5.5, width=4.5)167textplot(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))168dev.off()169170# --------------------------------------------------------------------171# Compare Distributions172# --------------------------------------------------------------------173#174CairoPDF(file=paste(resultsdir, dataname, "-Distributions.pdf", sep=""), height=5.5, width=9)175#source(paste(functionsdir, "/page.Distributions", sep=""))176page.Distributions(R[,1:4], colorset=wb13color, las=1)177dev.off()178179CairoPDF(file=paste(resultsdir, dataname, "-Distributions2.pdf", sep=""), height=5.5, width=9)180#source(paste(functionsdir, "/page.Distributions", sep=""))181page.Distributions(R[,5:7], colorset=wb13color, las=1)182dev.off()183184# --------------------------------------------------------------------185# Correlation Panels186# --------------------------------------------------------------------187# col3 <- colorRampPalette(c("darkgreen", "white", "darkred"))188M <- cor(R)189colnames(M) = rownames(M)190order.hc2 <- corrMatOrder(M, order="hclust", hclust.method="complete")191M.hc2 <- M[order.hc2,order.hc2]192CairoPDF(file=paste(resultsdir, dataname, "-cor-inception.pdf", sep=""), height=5.5, width=4.5)193corrplot(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)194corrRect.hclust(M.hc2, k=3, method="complete", col="blue")195dev.off()196197M36 <- cor(last(R,36))198colnames(M36) = rownames(M36) = rownames(M)199order36.hc2 <- corrMatOrder(M36, order="hclust", hclust.method="complete")200M36.hc2 <- M36[order36.hc2,order36.hc2]201CairoPDF(file=paste(resultsdir, dataname, "-cor-tr36m.pdf", sep=""), height=5.5, width=4.5)202corrplot(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)203corrRect.hclust(M36.hc2, k=3, method="complete", col="blue")204dev.off()205206# --------------------------------------------------------------------207# Table of Return correlations208# --------------------------------------------------------------------209210write.csv(M, file=paste(resultsdir, dataname, "-inception-cor.csv", sep=""))211colnames(M)=R.foldednames212# 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=""))213# write(print(xtable(M, digits=1, align=rep("c",8))), file=paste(resultsdir, dataname, "-inception-cor.latex", sep=""))214# write(pandoc.table.return(M, digits=1, split.tables=Inf), file=paste(resultsdir, dataname, "-inception-cor.md", sep=""))215216# --------------------------------------------------------------------217# Rolling Correlation to S&P500 TR218# --------------------------------------------------------------------219220CairoPDF(file=paste(resultsdir, dataname, "-RollCorr.pdf", sep=""), height=5.5, width=9)221chart.RollingCorrelation(R,SP500.TR, width=24, legend.loc=NULL, colorset=wb13color, main="Rolling 24-Month Correlation to S&P500 TR", las=1)222legend("bottomleft", legend=colnames(R), inset = 0.02, border.col="darkgrey", lwd=3, col=wb13color, cex=0.7, y.intersp=1.1)223dev.off()224225# --------------------------------------------------------------------226# Autocorrelation227# --------------------------------------------------------------------228229# require(Hmisc)230AC.stats = t(table.Autocorrelation(R=R))231write.csv(AC.stats, file=paste(resultsdir, dataname, "-AC-stats.csv", sep=""))232CairoPDF(file=paste(resultsdir, dataname, "-ACStats.pdf", sep=""), height=5.5, width=4.5)233# sort by p-value234AC.order = order(AC.stats[,7], decreasing=FALSE)235textplot(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)236dev.off()237238CairoPDF(file=paste(resultsdir, dataname, "-ACStackedBars.pdf", sep=""), height=5.5, width=9)239rownames(AC.stats)= sapply(colnames(R), function(x) paste(strwrap(x,10), collapse = "\n"), USE.NAMES=FALSE)240chart.StackedBar(as.matrix(AC.stats[,1:6]), colorset=bluemono, main="Observed Autocorrelation", las=1)241dev.off()242243# --------------------------------------------------------------------244# ETL parameterization charts245# --------------------------------------------------------------------246# Requires a recent modification to the chart in PerformanceAnalytics to make the y-axes match; in revision 3191247source('./R/chart.VaRSensitivity.R')248CairoPDF(file=paste(resultsdir, dataname, "-ETL-sensitivity.pdf", sep=""), height=5.5, width=9)249layout(matrix(c(1:8), nrow=2))250par(mar = c(4, 4, 5, 2)+0.1) #c(bottom, left, top, right)251for(i in 1:NCOL(R)){252chart.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")253abline(v = 1-1/12, col = wb13color[11], lty = 2, lwd=1)254}255plot.new()256legend("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")257par(op)258dev.off()259260261262