Path: blob/master/sandbox/riskbudgetpaper(superseded)/R_interpretation/performanceanalysis.R
1719 views
1# ----------------------------------------------------------------------------------2# In this script the out-of-sample returns of the optimized portfolios is analyzed3#4# ----------------------------------------------------------------------------------56setwd("c:/Documents and Settings/Administrator/Desktop/risk budget programs")78# Optimized portfolio you want to analyse out-of-sample performance through (Component) Sharpe ratios910estyears = 8;11percriskcontribcriterion = "mES"12frequency = "quarterly" ;yearly = F;1314# Load additional programs to interpret the data1516library(zoo); library("PerformanceAnalytics"); source("R_interpretation/pfolioreturn.R");17source("R_Allocation/estimators.R"); library(zoo);18histVaR = function( series ){ return(-quantile(series,probs=0.05) ) }19histCVaR = function( series ){ series = as.numeric(series) ; q = as.numeric(histVaR(series)) ; return( -mean( series[series<(-q)] )) }2021# Define optimization criteria2223names = c( "EqualWeight" , "MinRisk" , "MinRisk_PositionLimit" , "MinRisk_RiskLimit" ,24"MinRiskConc" , "MinRiskConc_PositionLimit", "EqualRisk" ,25"MinRisk_ReturnTarget", "MinRiskConc_ReturnTarget" )2627namelabels = c( "Equal Weight" , "Min CVaR" , "Min CVaR + Position Limit" , "Min CVaR + CVaR Alloc Limit" ,28"Min CVaR Conc" , "Min CVaR Conc + 40% Position Limit", "Min CVaR + ERC constraint" , "Min CVaR + Return Target" , "Min CVaR Conc + Return Target" )2930criteria = paste( rep("weights/",8) , names , sep="")3132# Load the data3334firstyear = 1976 ; firstquarter = 1; lastyear = 2010; lastquarter = 2;35data = read.table( file= paste("data/","data.txt",sep="") ,header=T)36date = as.Date(data[,1],format="%Y-%m-%d")3738nominalreturns = T;39if(nominalreturns){ monthlyR = zoo( data[,2:ncol(data)] , order.by = date ) }else{40monthlyR = zoo( data[,2:(ncol(data)-1)] , order.by = date ) - zoo( data[,ncol(data)] , order.by = date )41}42monthlyR = monthlyR[,1:4]4344summarystats_assets = FALSE;45if(summarystats_assets){46apply( monthlyR , 2 , 'mean' )*100 ; apply( monthlyR , 2 , 'sd' )*10047apply( monthlyR , 2 , 'skew' ) ; apply( monthlyR , 2 , 'exkur' )48apply( monthlyR , 2 , 'histCVaR' ) ; cor(monthlyR)49}505152# Define the out-of-sample periods5354# Define rebalancing periods:5556ep = endpoints(monthlyR,on='quarters')57# select those for estimation period58ep.start = ep[(1+estyears*4):(length(ep)-1)]+159from = time(monthlyR)[ep.start]60from = seq( as.Date("1984-01-01"), as.Date("2010-04-01"), by="3 month")61ep.end = ep[(1+estyears*4):(length(ep)-1)]+362to = time(monthlyR)[ep.end]63646566# Compute daily out of sample returns, accounting for compounding effects6768Returns.rebalancing( R = monthlyR , criteria = criteria, from = from, to = to , folder="/oosreturns/" )69oosdates = time( window (monthlyR , start = from[1] , end = to[ length(to) ] ) )7071load(paste(getwd(),"/","/oosreturns/", "simplereturns.Rdata" ,sep="") )7273colnames(simplereturns) = names74date = time(simplereturns)757677# Bear periods78sp500 = window (monthlyR , start = from[1] , end = to[ length(to) ] )[,2]79bear = c(1:length(sp500))[sp500<mean(sp500)]80bear = c(1:length(sp500))[sp500<(-0.12)]81m.bear.dates = list();82i=1;83for( b in bear){84m.bear.dates[[i]] = c( b-0.5, b+0.5)85i = i + 1;86}8788# http://www.aheadofthecurve-thebook.com/charts.html89# Vertical yellow bars in most charts denote bear markets (declines in the S&P 500 Index of 12% or more).90# IMPORTANT: The leading edge (left side) of the vertical yellow bars are thus stock market peaks,91# and the trailing edge (right side) are stock market troughs.9293#source( paste(getwd(),"/R_interpretation/findDrawdowns.R",sep="") )94out = table.Drawdowns(sp500,top=10)95start.bear = out$From[out$Depth<(-0.12)]96end.bear = out$Trough[out$Depth<(-0.12)]97start.bear.index = c(1:length(sp500))[ time(sp500) ]98m.bear.dates = list()99v.bear.dates = c()100for( i in 1:length(start.bear) ){101m.bear.dates[[i]] = c( as.yearmon(start.bear[i]) , as.yearmon(end.bear[i]) )102v.bear.dates = c( v.bear.dates , seq(start.bear[i],end.bear[i],"days") )103}104v.bear.dates = as.Date( v.bear.dates )105106107# Chart of relative performance strategies vs Equal-Weight108109postscript( file="RelPerf_EW.eps" )110# zelf opslaan anders worden de cijfers niet gedraaid in de y-as111par( mfrow = c(2,1) , mar =c(2,5,2,2), cex.axis = 0.7 , cex.main=0.7 )112# EqualWeight, MinCVaR, MinCVaRConcentration113chart.RelativePerformance( simplereturns[,c(2,3,4)] , simplereturns[,c(1)] ,114main = "" , lty=c("solid","solid","solid") , ylab="Relative performance vs equal-weight", xlab="",115col=c("black","darkgray","darkgray") , las=1, lwd=c(2,2,5) ,116auto.grid = TRUE, minor.ticks = FALSE ,ylim=c(0.7,1.65),117period.areas = m.bear.dates , period.color="lightgray",118date.format.in = "%Y-%m-%d",date.format = "%b %Y")119legend("topleft", legend = c("Min CVaR","Min CVaR + 40% Position Limit", "Min CVaR + 40% Risk Allocation Limit"),120col=c("black","darkgray","darkgray"), lty=c("solid","solid","solid"), lwd=c(2,2,5) ,cex=0.7)121122chart.RelativePerformance( simplereturns[,c(5,6,7)] , simplereturns[,c(1)] ,123main = "" , lty=c("solid","solid","solid") , ylab="Relative performance vs equal-weight",124col=c("black","darkgray","darkgray") , lwd=c(2,2,5), las=1 ,125auto.grid = TRUE, minor.ticks = FALSE , ylim=c(0.7,1.65),126period.areas = m.bear.dates , period.color="lightgray",127date.format.in = "%Y-%m-%d",date.format = "%b %Y")128129legend("topleft", legend = c("Min CVaR Concentration","Min CVaR Concentration + 40% Position Limit", "Min CVaR + ERC constraint"),130col=c("black","darkgray","darkgray"), lty=c("solid","solid","solid"), lwd=c(2,2,5) ,cex=0.7)131dev.off()132133134# Table of summary statistics on out-of-sample returns135136library(PerformanceAnalytics)137library(zoo)138oosreturns = zoo(simplereturns[,c(1:7)],order.by = seq.Date(as.Date(from[1])+31, as.Date(tail(to,1)) + 1, by ="month") - 1)139140v.nobear.dates = as.Date(setdiff( time(oosreturns) , v.bear.dates ))141142# Mean, Standard Deviation, CVaR143histVaR = function( series ){ return(-quantile(series,probs=0.05) ) }144histCVaR = function( series ){ series = as.numeric(series) ; q = as.numeric(histVaR(series)) ; return( -mean( series[series<(-q)] )) }145146print("Full period") #median, skew; exkur; histVaR147apply( oosreturns , 2 , 'mean' )*100*12 ;148apply( oosreturns , 2 , 'sd' )*100*sqrt(12)149100*apply( oosreturns , 2 , 'histCVaR')150151oosreturns_bear = oosreturns[ v.bear.dates ]152oosreturns_bull = oosreturns[ v.nobear.dates ]153154print("Bear market")155apply( oosreturns_bear , 2 , 'mean' )*100*12;156apply( oosreturns_bear , 2 , 'sd' )*100*sqrt(12)157100*apply( oosreturns_bear , 2 , 'histCVaR')158159print("Bull market")160apply( oosreturns_bull , 2 , 'mean' )*100*12 ;161apply( oosreturns_bull , 2 , 'sd' )*100*sqrt(12)162100*apply( oosreturns_bull , 2 , 'histCVaR')163164for( i in 1:7 ){ # Print the drawdowns165print( namelabels[i] )166print( table.Drawdowns(oosreturns[,i],top=10) )167}168169# Risk concentration170171for( strat in 1:7 ){172criterion = criteria[strat];173print( criterion );174weightedR = c(); portfolioVaR = c();175weights = read.csv( file = paste( criterion,".csv",sep=""),header = TRUE, sep = ",", na.strings = "NA", dec = ".")176177# Step 1: compute for each optimal weight the corresponding historical quantile178179for (row in 1:length(from)){180# For the determination of the historical quantile all returns preceding the rebalancing period are taken181previousR = window(monthlyR, start = time(monthlyR)[1] , end = as.Date(from[row]-1)) ;182pfoosR = rowSums( matrix( rep( as.numeric(weights[row,]),nrow(previousR)) , nrow = nrow(previousR) )*previousR )183# The weighted returns need the returns of the rebalancing period184Rrebalperiod = window(monthlyR, start = as.Date(from[row]) , end = as.Date(to[row])) ;185weightedR = rbind( weightedR , matrix( rep( as.numeric(weights[row,]),nrow(Rrebalperiod)) , nrow = nrow(Rrebalperiod) )*Rrebalperiod );186portfolioVaR = c( portfolioVaR , histVaR( pfoosR ) ) ;187}188189# Step 2: compute the mean squared weighted return over months with beyond VaR losses190191series = rowSums(weightedR) ;192#out = mean(weightedR[series<(-portfolioVaR),]^2);193downsidelosses = weightedR[series<(-portfolioVaR),]194downsidelosses = weightedR[series<=-0.10,]195vES = rowSums(downsidelosses)196197print("Total portfolio loss")198print( summary( apply( -downsidelosses , 1 , 'sum') ))199print("Max percentage loss")200print( summary( apply( downsidelosses/ apply( downsidelosses , 1 , 'sum') , 1 , 'max') ))201202}203204205# Portfolio turnover per strategy:206207turnover = c();208209# Compute for each rebalancing period, the cumulative return:210211cumR = c()212oosR = window (monthlyR , start = from[1] , end = to[ length(to) ] )213cRebalancing = length(from)214215for( i in 1:cRebalancing ){216sel = seq( (i-1)*3+1 , i*3 )217cumR = rbind( cumR , apply((1+oosR[sel,]),2,'cumprod')[3,] )218}219220# Load portfolio weights:221222for( strat in 1:7 ){223criterion = criteria[strat];224wstart = read.csv( file = paste( criterion,".csv",sep=""),header = TRUE, sep = ",", na.strings = "NA", dec = ".")225wend = (wstart[1:cRebalancing,]*cumR)/rowSums( wstart[1:cRebalancing,]*cumR )226out = mean( abs( wstart[2:cRebalancing,]-wend[1:(cRebalancing-1),] ))227turnover = c( turnover , mean(out) )228}229230print( rbind( namelabels[1:7] , turnover*100) );231232233