Path: blob/master/sandbox/riskbudgetpaper(superseded)/R_Allocation/bondequity.R
1433 views
setwd("c:/Documents and Settings/Administrator/Desktop/risk budget programs")12# Equal risk portfolio3cAssets = 2;4p = priskbudget = 0.95;56mincriterion = "mES" ; percriskcontribcriterion = "mES";78# Load programs910source("R_Allocation/Risk_budget_functions.R");11library(zoo); library(fGarch); library("PerformanceAnalytics"); library("DEoptim")1213# Load the data1415firstyear = 1976 ; firstquarter = 1; lastyear = 2010; lastquarter = 2;1617data = read.table( file= paste("data/","/data.txt",sep="") ,header=T)18date = as.Date(data[,1],format="%Y-%m-%d")19monthlyR = indexes = zoo( data[,2:5] , order.by = date )2021clean = TRUE22if(clean){ # multivariate cleaning, on all assets s.t. same value in efficient frontier23monthlyR = clean.boudt2(monthlyR,alpha=0.05)[[1]]24}25monthlyR = indexes = monthlyR[,1:2]2627mu = apply(indexes,2,'mean')28# > mu*1229# Bond SP50030# 0.0754596 0.102493431sigma = cov(indexes)32M3 = PerformanceAnalytics:::M3.MM(indexes)33M4 = PerformanceAnalytics:::M4.MM(indexes)3435# Summary stats individual assets3637head(indexes[,1:2],2); tail(indexes[,1:2],2)38apply(indexes[,1:2],2,'mean')*1239apply(indexes[,1:2],2,'sd')40ES(indexes[,1],method="modified")41ES(indexes[,2],method="modified")42434445#################################################################################46# Make Exhibit 2 Risk budget paper: weight and CVaR allocation static portfolios47#################################################################################4849# Equal-weight portfolio50w5050 <- c(0.5,0.5)51sum( w5050*mu*12 ) ;52#VaR(R=indexes[,1:2], weights=w5050, portfolio_method="component")53ES(R=indexes[,1:2], weights=w5050, portfolio_method="component", mu = mu, sigma = sigma, m3=M3, m4=M4,invert=FALSE)5455# 60/40 bond equity allocation56w6040 <- c(0.6,0.4);57sum( w6040*mu*12 ) ;58#VaR(R=indexes[,1:2], weights=w6040, portfolio_method="component")59ES(R=indexes[,1:2], weights=w6040, portfolio_method="component", mu = mu, sigma = sigma, m3=M3, m4=M4,invert=FALSE)606162# Min CVaR portfolio636465library(DEoptim)66obj <- function(w) {67if (sum(w) == 0) { w <- w + 1e-2 }68w <- w / sum(w)69ES(R=indexes[,1:2],weights = matrix(w,ncol=1), mu = mu, sigma = sigma, m3=M3, m4=M4,invert=FALSE)70}71out <- DEoptim(fn = obj, lower = rep(0, 2), upper = rep(1, 2),72DEoptim.control(itermax=100))73wstar <- out$optim$bestmem74wMinCVaR <- wstar / sum(wstar)75print(wMinCVaR)76# par1 par277#0.96864323 0.0313567778# wMinCVaR = c( 0.96864323 , 0.03135677 )79print(sum(wMinCVaR*mu*12))80ES(R=indexes[,1:2], weights=matrix(wMinCVaR,ncol=1),portfolio_method="component", mu = mu, sigma = sigma, m3=M3, m4=M4)818283# Min CVaR Concentration portfolio8485obj <- function(w) {86if (sum(w) == 0) { w <- w + 1e-2 }87w <- w / sum(w)88CVaR <- ES(R=indexes[,1:2], weights=matrix(w,ncol=1),portfolio_method="component", mu = mu, sigma = sigma, m3=M3, m4=M4)89out <- max(CVaR$contribution)90}91out <- DEoptim(fn = obj, lower = rep(0, 2), upper = rep(1, 2),92DEoptim.control(itermax=100))93wstar <- out$optim$bestmem94wMinCVaRConc <- wstar / sum(wstar)95print(wMinCVaRConc)96#> print(wMinCVaRConc)97# par1 par298#0.7700542 0.229945899# wMinCVaRConc = c( 00.7700542 , 0.2299458 )100print(sum(wMinCVaRConc*mu*12))101ES(R=indexes[,1:2], weights=wMinCVaRConc, portfolio_method="component")102103104# 60/40 Risk allocation portfolio105obj <- function(w) {106if (sum(w) == 0) { w <- w + 1e-2 }107w <- w / sum(w)108CVaR <- ES(R=indexes[,1:2], weights=matrix(w,ncol=1),portfolio_method="component", mu = mu, sigma = sigma, m3=M3, m4=M4)109tmp1 <- CVaR$MES110tmp2 <- max(CVaR$pct_contrib_MES - c(0.601,0.401 ) , 0)111tmp3 <- max(c(0.599,0.399 ) - CVaR$pct_contrib_MES , 0)112out <- tmp1 + 1e3 * tmp2 + 1e3 * tmp3113}114out <- DEoptim(fn = obj, lower = rep(0, 2), upper = rep(1, 2),115DEoptim.control(itermax=100))116wstar <- out$optim$bestmem117w6040riskalloc <- wstar / sum(wstar)118print(w6040riskalloc)119# par1 par2120#0.8123427 0.1876573121print(sum(w6040riskalloc*mu*12))122# w6040riskalloc = c( 0.7290461 , 0.2709539 )123ES(R=indexes[,1:2], weights=w6040riskalloc, portfolio_method="component", mu = mu, sigma = sigma, m3=M3, m4=M4)124125#################################################################################126# Make Exhibit 3 Risk budget paper: Efficient frontier plot127#################################################################################128129# Construct efficient frontier: given a return target minimize the largest percentage CVaR in the portfolio130131mESfun = function( series ){ return( operMES( series , alpha = 0.05 , r = 2 ) ) }132assetmu = apply( monthlyR , 2 , 'mean' )133assetCVaR = apply( monthlyR , 2 , 'mESfun' )134minmu = min(assetmu); maxmu = max(assetmu); print(minmu*12); print(maxmu*12);135136# unconstrained solution is Minimum CVaR Concentration portfolio (having the equal risk contribution property):137# sol = MinMaxCompCVaRconportfolio(R=monthlyR, Riskupper = Inf ,Returnlower= -Inf )138minmu = min( apply(monthlyR,2,'mean' ));139sol = PortfolioOptim( minriskcriterion = "mES" , MinMaxComp = T, percriskcontribcriterion = "mES" ,140Riskupper = Inf ,Returnlower= minmu,141mu = mu, sigma = sigma, M3=M3, M4=M4)142143W = as.vector( sol[[1]] ) ; vmu = as.vector( sol[[2]] )144vrisk = as.vector( sol[[3]] ) ; vmaxpercrisk = max( sol[[4]] )145vmaxriskcontrib = max( sol[[5]] )146147# mutarget = 0.0047478;148149for( mutarget in seq(minmu+0.00001,maxmu,0.00001) ){150sol = PortfolioOptim( minriskcriterion = "mES" , MinMaxComp = T, percriskcontribcriterion = "mES" ,151Riskupper = Inf ,Returnlower= mutarget,152mu = mu, sigma = sigma, M3=M3, M4=M4)153W = rbind( W, as.vector( sol[[1]] ) )154vmu = c( vmu , as.vector( sol[[2]] ))155vrisk = c( vrisk , as.vector( sol[[3]] ) )156vmaxpercrisk = c( vmaxpercrisk , max( sol[[4]] ) )157vmaxriskcontrib = c( vmaxriskcontrib , max( sol[[5]] ) )158}159160# For the highest return targets, a very high penalty parameter is needed161162for( mutarget in c(seq( max(vmu) , maxmu, 0.000001),maxmu) ){163print( c("mutarget equal to",mutarget) )164sol = PortfolioOptim( minriskcriterion = "mES" , MinMaxComp = T, percriskcontribcriterion = "mES" ,165Riskupper = Inf ,Returnlower= mutarget, penalty = 1e9,166mu = mu, sigma = sigma, M3=M3, M4=M4)167W = rbind( W, as.vector( sol[[1]] ) )168vmu = c( vmu , as.vector( sol[[2]] ))169vrisk = c( vrisk , as.vector( sol[[3]] ) )170vmaxpercrisk = c( vmaxpercrisk , max( sol[[4]] ) )171vmaxriskcontrib = c( vmaxriskcontrib , max( sol[[5]] ) )172}173174175176177write.csv( W , file = "EffFrontierMinCVaRConc _weights_biv.csv" )178EffFrontier_stats = cbind( vmu , vrisk , vmaxpercrisk , vmaxriskcontrib)179write.csv( EffFrontier_stats , file = "EffFrontierMinCVaRConc_stats_biv.csv" )180181# Min CVaR portfolio182sol = PortfolioOptim( minriskcriterion = "mES" , MinMaxComp = F, percriskcontribcriterion = "mES" ,183R=monthlyR, Riskupper = Inf ,Returnlower= minmu)184185W = as.vector( sol[[1]] )186vmu = as.vector( sol[[2]] )187vrisk = as.vector( sol[[3]] )188vmaxpercrisk = max( sol[[4]] )189vmaxriskcontrib = max( sol[[5]] )190191for( mutarget in seq(minmu+0.00001,maxmu,0.00001) ){192print( c("mutarget equal to",mutarget) )193sol = PortfolioOptim( minriskcriterion = "mES" , MinMaxComp = F, percriskcontribcriterion = "mES" ,194Riskupper = Inf ,Returnlower= mutarget,195mu = mu, sigma = sigma, M3=M3, M4=M4)196W = rbind( W, as.vector( sol[[1]] ) )197vmu = c( vmu , as.vector( sol[[2]] ))198vrisk = c( vrisk , as.vector( sol[[3]] ) )199vmaxpercrisk = c( vmaxpercrisk , max( sol[[4]] ) )200vmaxriskcontrib = c( vmaxriskcontrib , max( sol[[5]] ) )201}202203204# For the highest return targets, a very high penalty parameter is needed205206for( mutarget in c(seq( max(vmu) , maxmu, 0.000001),maxmu) ){207print( c("mutarget equal to",mutarget) )208sol = PortfolioOptim( minriskcriterion = "mES" , MinMaxComp = F, percriskcontribcriterion = "mES" ,209Riskupper = Inf ,Returnlower= mutarget , penalty = 1e9,210mu = mu, sigma = sigma, M3=M3, M4=M4)211W = rbind( W, as.vector( sol[[1]] ) )212vmu = c( vmu , as.vector( sol[[2]] ))213vrisk = c( vrisk , as.vector( sol[[3]] ) )214vmaxpercrisk = c( vmaxpercrisk , max( sol[[4]] ) )215vmaxriskcontrib = c( vmaxriskcontrib , max( sol[[5]] ) )216}217218219write.csv( W , file = "EffFrontierMinCVaR _weights_biv.csv" )220EffFrontier_stats = cbind( vmu , vrisk , vmaxpercrisk , vmaxriskcontrib)221write.csv( EffFrontier_stats , file = "EffFrontierMinCVaR_stats_biv.csv" )222223224# Plotting225226227postscript('frontier_bondequity.eps')228layout( matrix( c(1,2,3), ncol = 1 ) , height= c(4,3.6,0.4), width=1)229####################################230# Min CVaR Concentration231####################################232labelnames = c( "US bond" , "S&P 500" )233W = read.csv(file = "EffFrontierMinCVaRConc _weights_biv.csv")[,2:3]234EffFrontier_stats = read.csv(file = "EffFrontierMinCVaRConc_stats_biv.csv")[,2:5]235vmu = EffFrontier_stats[,1] ;236vrisk = EffFrontier_stats[,2] ;237vmaxpercrisk = EffFrontier_stats[,3] ;238vriskconc = EffFrontier_stats[,4] ;239240Wsel = vmusel = vrisksel = vriskconcsel = c();241lm = minmu = min(vmu) ; maxmu = max(vmu);242ylim = c( min(assetmu) - 0.0003 , max(assetmu) + 0.0003 )243xlim = c( 0 , max(assetCVaR) + 0.01 )244245# seq( minmu + 0.00005 , maxmu , 0.00005 )246for( rm in seq( minmu + 0.00005 , maxmu , 0.00005 ) ){247selection = c(vmu >= lm & vmu < rm) ;248if( any(selection) ){249vmusel = c( vmusel , mean(vmu[ selection ] ));250Wsel = rbind( Wsel , apply( W[selection,] ,2,'mean' ))251vrisksel = c( vrisksel , mean(vrisk[ selection ]) );252vriskconcsel = c( vriskconcsel , mean(vriskconc[ selection ]) )253}254lm = rm;255}256257cAssets = ncol(monthlyR)258colorset = gray( seq(0,(cAssets-1),1)/cAssets ) ;259colnames( Wsel ) = c("US bond", "S&P 500")260rownames( Wsel ) = vmusel;261262par( mar = c(4,5,3,1), las=1 ,cex=0.9 , cex.axis=0.9)263plot( vriskconcsel, vmusel*12 , type="l", lty = 2 ,264main = "Minimum CVaR concentration efficient frontier" ,265ylab="Annualized mean return" , xlab="" ,266lwd=2, xlim = xlim , ylim = ylim*12 )267lines( vrisksel , vmusel*12, lty = 1, lwd=2 ) # , col="darkgray" )268legend("bottomright",legend=c("Total Portfolio CVaR" , "Largest Component CVaR" ),lty=c(1,2), cex=0.8,ncol=1,lwd=2)269270for( c in 1:2 ){ text(y=assetmu[c]*12,x= assetCVaR[c] , label=labelnames[c] , cex = 0.8) };271272par( mar = c(5,5,3,1) , las=1 )273274barplot( t(Wsel) , axisnames=T ,col=colorset,space=0 , names.arg = round(vmusel*12,3), xlab="Annualized mean return" ,275ylab="Weight allocation" , main = "Minimum CVaR concentration efficient portfolios" )276277par( mar = c(0,5,0,1) )278plot.new()279legend("center",legend=c("US bond", "S&P 500"),fill=colorset[1:2],cex=0.8,ncol=2)280281dev.off()282283# Other layout284285286postscript('frontier_bondequity.eps')287layout( matrix( c(1,2,3,4), ncol = 2 ) , height= c(4,0.4,4,0.4), width=1 )288####################################289# Min CVaR Concentration290####################################291labelnames = c( "US bond" , "S&P 500" )292W = read.csv(file = "EffFrontierMinCVaRConc _weights_biv.csv")[,2:3]293EffFrontier_stats = read.csv(file = "EffFrontierMinCVaRConc_stats_biv.csv")[,2:5]294vmu = EffFrontier_stats[,1] ;295vrisk = EffFrontier_stats[,2] ;296vmaxpercrisk = EffFrontier_stats[,3] ;297vriskconc = EffFrontier_stats[,4] ;298299Wsel = vmusel = vrisksel = vriskconcsel = c();300lm = minmu = min(vmu) ; maxmu = max(vmu);301ylim = c( min(assetmu) - 0.0003 , max(assetmu) + 0.0003 )302xlim = c( 0 , max(assetCVaR) + 0.01 )303304# seq( minmu + 0.00005 , maxmu , 0.00005 )305for( rm in seq( minmu + 0.000005 , maxmu , 0.000005 ) ){306selection = c(vmu >= lm & vmu < rm) ;307if( any(selection) ){308vmusel = c( vmusel , mean(vmu[ selection ] ));309Wsel = rbind( Wsel , apply( W[selection,] ,2,'mean' ))310vrisksel = c( vrisksel , mean(vrisk[ selection ]) );311vriskconcsel = c( vriskconcsel , mean(vriskconc[ selection ]) )312}313lm = rm;314}315316317# add the full investment in the S&P500 NEW ATTENTION318vmusel = c( vmusel , max(assetmu) )319Wsel = rbind( Wsel , c(0,1) )320vrisksel = c( vrisksel , max(assetCVaR) )321vriskconcsel = c( vriskconcsel , max(assetCVaR) )322323cAssets = ncol(monthlyR)324colorset = gray( seq(0,(cAssets-1),1)/cAssets ) ;325colnames( Wsel ) = c("US bond", "S&P 500")326rownames( Wsel ) = vmusel;327328par( mar = c(4,5,5,1), las=1 ,cex=0.9 , cex.axis=0.9, cex.main=0.95)329plot( vriskconcsel, vmusel*12 , type="l", lty = 2 ,330main = "Ann. Return vs total CVaR and Largest Component CVaR \n for minimum CVaR concentration efficient portfolios" ,331ylab="Annualized mean return" , xlab="" ,332lwd=2, xlim = xlim , ylim = ylim*12 )333lines( vrisksel , vmusel*12, lty = 1, lwd=2 ) # , col="darkgray" )334for( c in 1:2 ){ text(y=assetmu[c]*12,x= assetCVaR[c] , label=labelnames[c] , cex = 0.8, offset = 0) };335336par( mar = c(0,5,0,1) )337plot.new()338legend("center",legend=c("Total Portfolio CVaR" , "Largest Component CVaR" ),lty=c(1,2), cex=0.8,ncol=1,lwd=2)339340341par( mar = c(5,5,5,1) , las=1 )342343barplot( t(Wsel) , axisnames=T ,col=colorset,space=0 , names.arg = round(vmusel*12,3), xlab="Annualized mean return" ,344ylab="Weight allocation" , main = "Weight allocation of\n minimum CVaR concentration efficient portfolios" )345346par( mar = c(0,5,0,1) )347plot.new()348legend("center",legend=c("US bond", "S&P 500"),fill=colorset[1:2],cex=0.8,ncol=1)349350dev.off()351352353# Layout 3354source("R_interpretation/chart.StackedBar.R");355356mESfun = function( series ){ return( operMES( series , alpha = 0.05 , r = 2 ) ) }357assetmu = apply( monthlyR , 2 , 'mean' )358assetCVaR = apply( monthlyR , 2 , 'mESfun' )359minmu = min(assetmu); maxmu = max(assetmu); print(minmu*12); print(maxmu*12);360361362postscript('frontier_bondequity.eps')363layout( matrix( c(1,2,3,4,5,6), ncol = 3 ) , height= c(4,0.4,4.25,0.15,4.25,0.15), width=c(1,0.78,0.78) )364####################################365# Min CVaR Concentration366####################################367labelnames = c( "US bond" , "S&P 500" )368W = read.csv(file = "EffFrontierMinCVaRConc _weights_biv.csv")[,2:3]369EffFrontier_stats = read.csv(file = "EffFrontierMinCVaRConc_stats_biv.csv")[,2:5]370vmu = EffFrontier_stats[,1] ;371vrisk = EffFrontier_stats[,2] ;372vmaxpercrisk = EffFrontier_stats[,3] ;373vmaxriskcontrib = vriskconc = EffFrontier_stats[,4] ;374375order = sort(vmu,index.return=T)$ix376vmu = vmu[order]377vrisk = vrisk[order]378vmaxpercrisk = vmaxpercrisk[order]379vmaxriskcontrib = vmaxriskcontrib[order]380W = W[order,]381a = duplicated(vmu)382vmu = vmu[!a]383vrisk = vrisk[!a]384vmaxpercrisk = vmaxpercrisk[!a]385vriskconc = vmaxriskcontrib = vmaxriskcontrib[!a]386W = W[!a,]387388# Discontinuity in the frontier: For return targets in between389# vmu[41:42]*12390# the solution is no longer on the frontier of the feasible space391392393Wsel = vmusel = vrisksel = vriskconcsel = CVaRsel = c();394lm = minmu = min(vmu) ; maxmu = max(vmu);395ylim = c( min(assetmu) - 0.0003 , max(assetmu) + 0.0003 )396xlim = c( 0 , max(assetCVaR) + 0.01 )397398binning = T # for the weight plots, binned data such that no visual misinterpretation is possible399step = 0.000015400if( binning ){401for( rm in seq( minmu+step , maxmu , step ) ){402selection = c(vmu >= lm & vmu < rm) ;403if( any(selection) ){404vmusel = c( vmusel , mean(vmu[ selection ] ));405Wsel = rbind( Wsel , apply( W[selection,] ,2,'mean' ))406vrisksel = c( vrisksel , mean(vrisk[ selection ]) );407vriskconcsel = c( vriskconcsel , mean(vriskconc[ selection ]) )408CVaRsel = rbind( CVaRsel , c( 1-mean(vriskconc[ selection ]/vrisk[selection]) , mean(vriskconc[ selection ]/vrisk[selection]) ) )409}else{410vmusel = c( vmusel , NA );411Wsel = rbind( Wsel , rep(NA,2) )412vrisksel = c( vrisksel , NA );413vriskconcsel = c( vriskconcsel , NA )414CVaRsel = rbind( CVaRsel , rep(NA,2) )415416}417lm = rm;418}419}else{420vmusel = vmu;421Wsel = W422vrisksel = vrisk423vriskconcsel = vriskconc424CVaRsel = cbind( 1-vriskconc/vrisk , vriskconc/vrisk )425}426427# add the full investment in the S&P500 NEW ATTENTION428#vmusel = c( vmusel , max(assetmu) )429#Wsel = rbind( Wsel , c(0,1) )430#vrisksel = c( vrisksel , max(assetCVaR) )431#vriskconcsel = c( vriskconcsel , max(assetCVaR) )432#CVaRsel = rbind( CVaRsel , c(0,1) )433434435cAssets = ncol(monthlyR)436colorset = gray( seq(0,(cAssets-1),1)/cAssets ) ;437colnames( Wsel ) = c("US bond", "S&P 500")438rownames( Wsel ) = vmusel;439440par( mar = c(4,5,5,0), las=1 ,cex=0.9 , cex.axis=0.9, cex.main=0.95)441plot( vriskconc, vmu*12 , type="l", lty = 1,442main = "Ann. Return vs CVaR (concentration) " ,443ylab="Annualized mean return" , xlab="" ,444lwd=2, xlim = xlim , ylim = ylim*12 , col="darkgray" )445points( vriskconc, vmu*12 , pch=21 , col="darkgray")446lines( vrisk , vmu*12, lty = 1, lwd=2 ) # , col="darkgray" )447points( vrisk , vmu*12 , pch=21 )448for( c in 1:2 ){ text(y=assetmu[c]*12,x= assetCVaR[c] , label=labelnames[c] , cex = 0.7, offset = 0) };449450par( mar = c(0,5,0,0) )451plot.new()452legend("center",legend=c("CVaR" , "CVaR concentration" ),lty=c(1,1), cex=0.8,ncol=1,lwd=2,453col=c("black","darkgray"))454455456par( mar = c(5,1,14,0) , las=1 )457458chart.StackedBar2(Wsel , axisnames=T ,col=colorset,space=0 , names.arg = round(vmusel*12,3), xlab="Annualized mean return" ,459ylab="" , main = "Weight allocation " ,460las=1, l=2.5, r=0, u = 5, legend.loc = NULL,ylim=c(0,1),border = F)461abline(h=0);abline(h=1)462par( mar = c(0,1,0,0) )463plot.new()464legend("center",legend=c("US bond", "S&P 500"),fill=colorset[1:2],cex=0.8,ncol=2)465466467par( mar = c(5,1,14,0) , las=1 ) # top programmeren in chart.StackedBar2468469chart.StackedBar2(CVaRsel , axisnames=T ,col=colorset,space=0 , names.arg = round(vmusel*12,3), xlab="Annualized mean return" ,470ylab="" , main = "CVaR allocation " ,471las=1, l=2.5, r=0, u = 5, legend.loc = NULL,ylim=c(0,1),border = F)472abline(h=0);abline(h=1)473474par( mar = c(0,1,0,0) )475plot.new()476legend("center",legend=c("US bond", "S&P 500"),fill=colorset[1:2],cex=0.8,ncol=2)477478dev.off()479480481482483