Path: blob/master/sandbox/paper_analysis/R_interpretation/stackedweightriskcontributionplot.R
1433 views
#################################################################################1# Create stacked weights and risk contributions plot2#################################################################################34# ! Set your working directory (folder containing the subfolders R_allocation, R_interpretation, data, weights, etc)56setwd("c:/Documents and Settings/Administrator/Desktop/risk budget programs")7#setwd("c:/Documents and Settings/n06054/Desktop/risk budget programs")8910# Options:11################1213# specify the number of years used for the estimation14estyears = 5;15Tstart = 1+(8-estyears)*416CC = T17# Load programs1819source("R_interpretation/chart.StackedBar.R");20library(zoo); library(PerformanceAnalytics)2122# number of risky assets23firstyear = 1976 ; firstquarter = 1; lastyear = 2010; lastquarter = 2;24cAssets = 42526# "MinRisk_ReturnTarget" "EqualRisk"27# "MinRiskConc_ReturnTarget"2829names = c( "EqualWeight" , "MinRisk" , "MinRisk_PositionLimit" , "MinRisk_RiskLimit" ,30"MinRiskConc" , "MinRiskConc_PositionLimit", "EqualRisk" ,31"MinRisk_ReturnTarget", "MinRiskConc_ReturnTarget" )32if(CC){ names[1:length(names)] = paste( names[1:length(names)], "_CC", sep="") }3334namelabels = c( "Equal-Weight" , "Min CVaR" , "Min CVaR + 40% Position Limit" , "Min CVaR + 40% CVaR Alloc Limit" ,35"Min CVaR Concentration" , "Min CVaR Concentration + 40% Position Limit", "Min CVaR + ERC constraint" , "Min CVaR + Return Target" , "Min CVaR Conc + Return Target" )3637riskcrit = "mES"3839# frequency of rebalancing: yearly of quarterly40frequency = "quarterly"41# Load portfolio weights:42weightsS1 = read.csv( file = paste("weights/", riskcrit , "/", names[1], ".csv" , sep="") );43weightsS2 = read.csv( file = paste("weights/", riskcrit , "/", names[2], ".csv" , sep="") );44weightsS3 = read.csv( file = paste("weights/", riskcrit , "/", names[3], ".csv" , sep="") );45weightsS4 = read.csv( file = paste("weights/", riskcrit , "/", names[4], ".csv" , sep="") );46weightsS5 = read.csv( file = paste("weights/", riskcrit , "/", names[5], ".csv" , sep="") );47weightsS6 = read.csv( file = paste("weights/", riskcrit , "/", names[6], ".csv" , sep="") );48weightsS7 = read.csv( file = paste("weights/", riskcrit , "/", names[7], ".csv" , sep="") );4950# rownames(weightsS7) = weightsS7[,1] ;weightsS7 = weightsS7[,2:5]; colnames(weightsS7) = colnames(weightsS6)51# write.table( weightsS7 , file = paste("weights/", riskcrit , "/", names[7], ".csv" , sep="") ,52# append = FALSE, quote = TRUE, sep = ",", eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = "escape")535455# Load percentage risk contributions:56riskcontS1 = read.csv( file = paste("riskcont/", riskcrit , "/", names[1], ".csv" , sep="") );57riskcontS2 = read.csv( file = paste("riskcont/", riskcrit , "/", names[2], ".csv" , sep="") );58riskcontS3 = read.csv( file = paste("riskcont/", riskcrit , "/", names[3], ".csv" , sep="") );59riskcontS4 = read.csv( file = paste("riskcont/", riskcrit , "/", names[4], ".csv" , sep="") );60riskcontS5 = read.csv( file = paste("riskcont/", riskcrit , "/", names[5], ".csv" , sep="") );61riskcontS6 = read.csv( file = paste("riskcont/", riskcrit , "/", names[6], ".csv" , sep="") );62riskcontS7 = read.csv( file = paste("riskcont/", riskcrit , "/", names[7], ".csv" , sep="") );6364#rownames(riskcontS7) = riskcontS7[,1] ;riskcontS7 = riskcontS7[,2:5]65# write.table( riskcontS7 , file = paste("riskcont/", riskcrit , "/", names[7], ".csv" , sep="") ,66# append = FALSE, quote = TRUE, sep = ",", eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = "escape")6768if(frequency=="yearly"){69rebal.names = seq( (firstyear+estyears),lastyear+1,1)70}else{7172# Name labels using quarters:73rebal.names = paste(rep( seq( (firstyear+estyears),lastyear,1) , each=4),c("Q1","Q2","Q3","Q4"),sep="")74rebal.names = c( rebal.names , paste( lastyear+1, "Q1" , sep="" ) )75rebal.names = rebal.names[firstquarter:(length(rebal.names)-4+lastquarter)]7677# Name labels using months:78nominalreturns = TRUE;79if(nominalreturns){ load(file="monthlyR.RData") }else{ load(file="monthlyR_real.RData") }80ep = endpoints(monthlyR,on='quarters')81# select those for estimation period82ep.start = ep[1:(length(ep)-estyears*4)]+183from = time(monthlyR)[ep.start]84from = seq( as.Date(paste(firstyear,"-01-01",sep="")), as.Date(paste(lastyear-estyears,"-07-01",sep="")), by="3 month")85ep.end = ep[(1+estyears*4):length(ep)]86to = time(monthlyR)[ep.end]87rebal.names = as.yearmon(to+1)888990}919293rownames(weightsS1) = rownames(weightsS2) = rownames(weightsS3) = rownames(weightsS4) = rebal.names;94rownames(weightsS5) = rownames(weightsS6) = rownames(weightsS7) = rebal.names;9596rownames(riskcontS1) = rownames(riskcontS2) = rownames(riskcontS3) = rownames(riskcontS4) = rebal.names;97rownames(riskcontS5) = rownames(riskcontS6) = rownames(riskcontS7) = rebal.names;9899100colorset = sort(gray( 1-(seq(1,cAssets,1)/(cAssets))^1.5 )) ;101#due to rounding, the sum of the risk contributions is sometimes 1 + epsilon: avoid this in plot102103riskcontS1 = riskcontS1/rowSums(riskcontS1); riskcontS2 = riskcontS2/rowSums(riskcontS2);104riskcontS3 = riskcontS3/rowSums(riskcontS3); riskcontS4 = riskcontS4/rowSums(riskcontS4);105riskcontS5 = riskcontS5/rowSums(riskcontS5); riskcontS6 = riskcontS6/rowSums(riskcontS6);106riskcontS7 = riskcontS7/rowSums(riskcontS7);107108Tend = nrow(weightsS1)109110w.names = c( "US bond" , "S&P 500", "NAREIT" , "GSCI" )111l = 2112mar1 =c(2,l,2,1.1)113mar2 =c(0,l,2,1)114mar3 = c(3,l+1,3,0.1)115mar4 = c(2,l+1,2,0.1)116117# Stacked weights plot:118if(!CC){119postscript('stackedweightsriskcont_benchmark.eps')120}else{121postscript('stackedweightsriskcont_benchmark_CC.eps')122}123layout( matrix( c(1,2,3,4,5,6,7,4), ncol = 2 ) , height= c(1.5,1.5,1.5,0.7), width=1)124125par(mar=mar3 , cex.main=1)126chart.StackedBar2(weightsS1[Tstart:Tend,],col=colorset,space=0, main = namelabels[1], 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 )127128chart.StackedBar2(weightsS2[Tstart:Tend,],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 )129chart.StackedBar2(weightsS5[Tstart:Tend,],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 )130#chart.StackedBar2(weightsS7[Tstart:Tend,],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 )131132par(mar=mar1 , cex.main=1)133plot.new()134legend("center",legend=w.names,col=colorset,lwd=6,ncol=4)135136137138par(mar=mar3 , cex.main=1)139chart.StackedBar2(riskcontS1[Tstart:Tend,],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 )140chart.StackedBar2(riskcontS2[Tstart:Tend,],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 )141chart.StackedBar2(riskcontS5[Tstart:Tend,],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 )142#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 )143144dev.off()145146if(!CC){147postscript('MinCVaR_alternatives.eps')148}else{149postscript('MinCVaR_alternatives_CC.eps')150}151layout( matrix( c(1,2,3,4,5,6,7,4), ncol = 2 ) , height= c(1.5,1.5,1.5,0.7), width=1)152153par(mar=mar3 , cex.main=1)154chart.StackedBar2(weightsS3[Tstart:Tend,],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 )155chart.StackedBar2(weightsS4[Tstart:Tend,],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 )156chart.StackedBar2(weightsS6[Tstart:Tend,],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 )157158par(mar=mar1 , cex.main=1)159plot.new()160legend("center",legend=w.names,col=colorset,lwd=6,ncol=4)161par(mar=mar3 , cex.main=1)162163chart.StackedBar2(riskcontS3[Tstart:Tend,],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 )164chart.StackedBar2(riskcontS4[Tstart:Tend,],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 )165chart.StackedBar2(riskcontS6[Tstart:Tend,],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 )166167dev.off()168169170#############################################################################################171# Plot the CVaR of the portfolios for each period, relatively to CVaR minimum CVaR portfolio172173174source("R_Allocation/Risk_budget_functions.R");175library(zoo); library(fGarch); library("PerformanceAnalytics");176177# downside risk178alpha = alphariskbudget = 0.05;179CC=T180if(CC){ source( paste( getwd(),"/R_allocation/coskewkurtosis.R" ,sep="") ) }181182183# Load the data184185nominalreturns = T;186if(nominalreturns){ load(file="monthlyR.RData") }else{ load(file="monthlyR_real.RData") }187R = monthlyR188cAssets = ncol(monthlyR)189190# Define rebalancing periods:191192ep = endpoints(monthlyR,on='quarters')193# select those for estimation period194ep.start = ep[1:(length(ep)-estyears*4)]+1195from = time(monthlyR)[ep.start]; from = seq( as.Date(paste(firstyear,"-01-01",sep="")), as.Date(paste(lastyear-estyears,"-07-01",sep="")), by="3 month")196ep.end = ep[(1+estyears*4):length(ep)]197to = time(monthlyR)[ep.end]198cPeriods = length(from);199200# Loop where for each rebalancing period:201# - Compute total CVaR of portfolio202203mCVaR = mMU = c()204205for( per in c(1:cPeriods) ){206207# At the end of each month, we compute the CVaR208enddates = na.omit(time(window( monthlyR , start = as.Date(to[per]) , end = as.Date(to[per]+90) ),on='months')[1:3])209210for( enddate in enddates ){211212# add a loop over the next months except when per = cPeriods or -1,-2213214# Estimate GARCH model with data from inception215216inception.R = window(R, start = as.Date(from[1]) , end = enddate );217218# Estimate comoments of innovations with rolling estimation windows219in.sample.R = window(R, start = as.Date(from[per]) , end = as.Date(to[per]) );220in.sample.R = checkData(in.sample.R, method="matrix");221222# Estimation of mean return223M = c();224library(TTR)225Tmean = 47 # monthly returns: 4 year exponentially weighted moving average226for( i in 1:cAssets ){227M = cbind( M , as.vector( EMA(x=inception.R[,i],n=Tmean) ) ) #2/(n+1)228}229M = zoo( M , order.by=time(inception.R) )230231# Center returns (shift by one observations since M[t,] is rolling mean t-Tmean+1,...,t; otherwise lookahead bias)232inception.R.cent = inception.R;233ZZ = matrix( rep(as.vector( apply( inception.R[1:Tmean, ] , 2 , 'mean' )),Tmean),byrow=T,nrow=Tmean);234inception.R.cent[1:Tmean,] = inception.R[1:Tmean, ] - ZZ;235if( nrow(inception.R)>(Tmean+1) ){236A = M[Tmean:(nrow(inception.R)-1),];237A = zoo( A , order.by = time(inception.R[(Tmean+1):nrow(inception.R), ])) ; #shift dates; otherwise zoo poses problem238inception.R.cent[(Tmean+1):nrow(inception.R), ] = inception.R[(Tmean+1):nrow(inception.R), ] - A}239240# Garch estimation241S = c();242for( i in 1:cAssets ){243gout = garchFit(formula ~ garch(1,1), data = inception.R.cent[,i],include.mean = F, cond.dist="QMLE", trace = FALSE )244if( as.vector(gout@fit$coef["alpha1"]) < 0.01 ){245sigmat = rep( sd( as.vector(inception.R.cent[,i])), length(inception.R.cent[,i]) );246}else{247sigmat = gout@sigma.t248}249S = cbind( S , sigmat)250}251S = zoo( S , order.by=time(inception.R.cent) )252253# Estimate correlation, coskewness and cokurtosis matrix locally using cleaned innovation series in three year estimation window254selectU = window(inception.R.cent, start = as.Date(from[per]) , end = as.Date(to[per]) )255selectU = selectU/window(S, start = as.Date(from[per]) , end = as.Date(to[per]) );256selectU = clean.boudt2(selectU , alpha = 0.05 )[[1]];257Rcor = cor(selectU)258D = diag( as.vector(tail(S,n=1) ),ncol=cAssets )259sigma = D%*%Rcor%*%D260261# we only need mean and conditional covariance matrix of last observation262mu = matrix(tail(M,n=1),ncol=1 ) ;263D = diag( as.vector(as.vector(tail(S,n=1) ) ),ncol=cAssets )264sigma = D%*%Rcor%*%D265in.sample.T = nrow(selectU);266# set volatility of all U to last observation, such that cov(rescaled U)=sigma267selectU = selectU*matrix( rep(as.vector(tail(S,n=1)),in.sample.T ) , ncol = cAssets , byrow = T )268if(CC){269M3 = coskewCC(selectU); M4 = cokurtCC(selectU);270}else{271M3 = PerformanceAnalytics:::M3.MM(selectU)272M4 = PerformanceAnalytics:::M4.MM(selectU)273}274CVaR_period = c( operPortMES(as.numeric(weightsS1[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,275operPortMES(as.numeric(weightsS2[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,276operPortMES(as.numeric(weightsS3[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,277operPortMES(as.numeric(weightsS4[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,278operPortMES(as.numeric(weightsS5[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,279operPortMES(as.numeric(weightsS6[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] ,280operPortMES(as.numeric(weightsS7[per,]),mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[1]] )281282mu_period = c( sum(as.numeric(weightsS1[per,])*mu) , sum(as.numeric(weightsS2[per,])*mu) ,283sum(as.numeric(weightsS3[per,])*mu) , sum(as.numeric(weightsS4[per,])*mu) ,284sum(as.numeric(weightsS5[per,])*mu) , sum(as.numeric(weightsS6[per,])*mu) ,285sum(as.numeric(weightsS7[per,])*mu) )286287mCVaR = rbind( mCVaR , CVaR_period )288mMU = rbind( mMU , mu_period )289}290}291292colnames(mCVaR) = colnames(mMU) = names[1:7]293mCVaR = xts( mCVaR ,294order.by = as.Date(time( window( monthlyR , start = as.Date(to[1]) , end = as.Date(to[cPeriods]) ))+1))295mMU = xts( mMU ,296order.by = as.Date(time( window( monthlyR , start = as.Date(to[1]) , end = as.Date(to[cPeriods]) ))+1))297298head(mCVaR[,1:7],2)299#> head(mCVaR[,1:7],2)300# EqualWeight MinRisk MinRisk_PositionLimit MinRisk_RiskLimit MinRiskConc MinRiskConc_PositionLimit EqualRisk301#1984-01-01 0.0492 0.0320 0.0380 0.0333 0.0352 0.0388 0.0352302#1984-02-01 0.0490 0.0304 0.0374 0.0322 0.0344 0.0383 0.0344303304305if(CC){306save(mCVaR, file="mCVaR_CC.Rdata")307save(mMU, file="mMU_CC.Rdata")308}else{309save(mCVaR, file="mCVaR.Rdata")310save(mMU, file="mMU.Rdata")311}312313head(mMU[,1:7],2)314#> head(mMU[,1:7],2)315# EqualWeight MinRisk MinRisk_PositionLimit MinRisk_RiskLimit MinRiskConc MinRiskConc_PositionLimit EqualRisk316#1984-01-01 0.009865862 0.00959764 0.01084905 0.009814883 0.009944563 0.01012198 0.009945766317#1984-02-01 0.010176409 0.01003861 0.01105078 0.010193260 0.010297694 0.01042968 0.010299787318319320###################################################321322if(CC){323load( file="mCVaR_CC.Rdata")324load( file="mMU_CC.Rdata")325}else{326load( file="mCVaR.Rdata")327load( file="mMU.Rdata")328}329330mMU = window(mMU , start=as.Date("1984-01-01") , end=tail(time(mMU),1) )331mCVaR = window(mCVaR , start=as.Date("1984-01-01") , end=tail(time(mCVaR),1) )332333if(CC){334postscript(file="portfolioMeanCVaR_CC.eps")335}else{336postscript(file="portfolioMeanCVaR.eps")337}338par(mfrow=c(2,1),mar=c(3,2,3,2))339340341342plot( mMU[,1]*12 , type = "l" , ylim=c(min(mMU),max(mMU))*12,col="darkgray", lwd=1.5 ,343main = "Expected annualized portfolio return" )344lines( mMU[,2]*12 , type = "l", col="black",lwd=2 , lty=3)345lines( mMU[,7]*12 , type = "l", col="darkgray",lwd=4)346lines( mMU[,5]*12 , type = "l", col="black", lwd=1.5)347348legend("bottomleft", legend = c("Equal-Weight","Min CVaR Concentration","Min CVaR+ERC constraint","Min CVaR" ),349col=c("darkgray","black","darkgray","black"), lty=c("solid","solid","solid","dashed"), lwd=c(2,2,4,2) ,cex=0.7)350351plot( mCVaR[,1] , type = "l" , ylim=c(0,max(mCVaR)),col="darkgray", lwd=1.5 , main = "Portfolio CVaR" )352lines( mCVaR[,2] , type = "l", col="black",lwd=1.5 , lty=3)353lines( mCVaR[,7] , type = "l", col="darkgray",lwd=4)354lines( mCVaR[,5] , type = "l", col="black", lwd=1.5)355dev.off()356357# do not plot the last month such that it is fully comparable with out-of-sample plots358359sel = c( 1 : (nrow(mCVaR)-1) );360361362# Bear periods363sp500 = window (monthlyR , start = from[1] , end = to[ length(to) ] )[,2]364bear = c(1:length(sp500))[sp500<mean(sp500)]365bear = c(1:length(sp500))[sp500<(-0.12)]366m.bear.dates = list();367i=1;368for( b in bear){369m.bear.dates[[i]] = c( b-0.5, b+0.5)370i = i + 1;371}372373out = table.Drawdowns(sp500,top=10)374start.bear = out$From[out$Depth<(-0.12)]375end.bear = out$Trough[out$Depth<(-0.12)]376start.bear.index = c(1:length(sp500))[ time(sp500) ]377m.bear.dates = list()378v.bear.dates = c()379for( i in 1:length(start.bear) ){380m.bear.dates[[i]] = c( as.yearmon(start.bear[i]) , as.yearmon(end.bear[i]) )381v.bear.dates = c( v.bear.dates , seq(start.bear[i],end.bear[i],"days") )382}383v.bear.dates = as.Date( v.bear.dates )384385386if(CC){387postscript(file="portfolioCVaR_CC.eps")388}else{389postscript(file="portfolioCVaR.eps")390}391par(mfrow=c(2,1),mar=c(3,4,1,2))392393chart.TimeSeries( mCVaR[sel,c(1,5,2)] , ylim=c(0,max(mCVaR)), ylab = "Portfolio CVaR" , main = "",394col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2,2) ,395auto.grid = TRUE, minor.ticks = FALSE ,396period.areas = m.bear.dates , period.color="lightgray",397date.format.in = "%Y-%m-%d",date.format = "%b %Y")398399legend("topleft", legend = namelabels[c(1,5,2)],400col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2) ,cex=0.7)401402chart.TimeSeries( mCVaR[sel,c(4,3,6)] , type = "l" , ylim=c(0,max(mCVaR)), ylab = "Portfolio CVaR" , main = "",403col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2,2) ,404auto.grid = TRUE, minor.ticks = FALSE ,405period.areas = m.bear.dates , period.color="lightgray",406date.format.in = "%Y-%m-%d",date.format = "%b %Y")407408legend("topleft", legend = namelabels[c(4,3,6)],409col=c("black","black","darkgray"), lty=c("dashed","solid","solid"), lwd=c(2,2,2) ,cex=0.7)410411412dev.off()413414415416417418419