Path: blob/master/sandbox/paper_analysis/R_interpretation/old/getRiskContrib.R
1433 views
1# ! Set your working directory (folder containing the subfolders R_allocation, R_interpretation, data, weights, etc)23setwd("c:/Documents and Settings/Administrator/Desktop/risk budget programs")45# Programs:67source("R_Allocation/allocation_functions_monthly.R"); source("R_Allocation/estimators.R");8library(zoo); library(fGarch); library("PerformanceAnalytics");9memory.limit(2048)1011# Choose data12datacase = "equitybondscommodity" # "equitybondscommodity" or "equitybondscommodity"1314# Define optimization criteria15criteria = c( "EW" )1617# Yearly or quarterly rebalancing18yearly = F;1920# Length estimation period21estyears = 42223source("R_Allocation/allocation_functions_monthly.R"); source("R_Allocation/estimators.R");24library(zoo); library(fGarch); library("PerformanceAnalytics");25memory.limit(2048)2627#############################################################################28# Load the data29#############################################################################3031firstyear = 1976 ; firstquarter = 1; lastyear = 2009; lastquarter = 2;3233data = read.table( file= paste("data/",datacase,"/data.txt",sep="") ,header=T)34date = as.Date(data[,1],format="%Y-%m-%d")35data = zoo( data[,2:ncol(data)] , order.by = date )3637# "Bond" "SP500" "EAFE" "SPGSCI" "TBill" "Inflation"3839cAssets = ncol(data)-2; # number of risky assets4041# The loaded data has monthly frequency4243# Estimation uses real returns4445monthlyR = data[,(1:(cAssets+1))]-data[,cAssets+2]46monthlyR.cash = monthlyR[,cAssets+1]47R = monthlyR[,1:cAssets]48plot(R)4950head(R);tail(R)5152from=to=c();5354if(yearly){55for( year in firstyear:(lastyear-estyears+1) ){56from = c( from , paste( year,"-01-01",sep="" ) );57to = c( to , paste( (year+estyears-1),"-12-31",sep="" ) ) }58nsamples = length(from);59names.input = paste( rep("y_",nsamples) , seq( (firstyear+estyears),lastyear+1,1) , sep="" );60}else{61for( year in firstyear:(lastyear-estyears) ){62from = c( from , paste( year,"-01-01",sep="" ) , paste( year,"-04-01",sep="" ) , paste( year,"-07-01",sep="" ) , paste( year,"-10-01",sep="" ) );63to = c( to , paste( (year+estyears-1),"-12-31",sep="" ), paste( (year+estyears),"-03-31",sep="" ), paste( (year+estyears),"-06-30",sep="" ),64paste( (year+estyears),"-09-30",sep="" ) ) }65from = c( from , paste( year+1,"-01-01",sep="" ) ); to = c( to , paste( (year+estyears),"-12-31",sep="" ) )66nsamples = length(from);67#names of quarters for which the forecast is made:68names.input = paste( c("Q1y_","Q2y_","Q3y_","Q4y_") , rep(seq( (firstyear+estyears),lastyear,1),each=4) , sep="" );69names.input = c( names.input , paste( "Q1y_" , lastyear+1, sep="" ) );70# this is assuming estimation window runs from firstyearQ1 to lastyearQ471from = from[firstquarter:(length(from)-4+lastquarter)]; to = to[firstquarter:(length(to)-4+lastquarter)]72names.input = names.input[firstquarter:(length(names.input)-4+lastquarter)]73}7475cPeriods = length(to) ; cCriteria = length(criteria) ;7677percriskcontribcriterion = "mES";7879RCout = matrix( rep(0,cPeriods*cAssets) , ncol= cAssets );8081#wper = matrix(rep(1/cAssets, cAssets),ncol=1)8283W = read.csv( file = paste("C:\\Documents and Settings\\Administrator\\Desktop\\risk budget programs\\weights\\mES\\equitybondscommodity\\quarterly\\unconstrained\\", "mES.4yr-InfInf" , ".csv" , sep="") );848586RCout = matrix( rep(0, cCriteria*cPeriods*(cAssets)) , ncol= (cAssets) ); # add possibility of cash if risk budget constraints are infeasible.878889# downside risk90alpha = 0.05;9192# Estimation of the return mean vector, covariance, coskewness and cokurtosis matrix939495for( per in c(1:cPeriods) ){9697print("-----------New estimation period ends on observation------------------")98print( paste(to[per],"out of total number of obs equal to", max(to) ));99print("----------------------------------------------------------------")100101matrix(as.vector(wper[1:4]),ncol=1)102103# Estimate GARCH model with data from inception104105inception.R = window(R, start = as.Date(from[1]) , end = as.Date(to[per]) );106107# Estimate comoments of innovations with rolling estimation windows108in.sample.R = window(R, start = as.Date(from[per]) , end = as.Date(to[per]) );109in.sample.R = checkData(in.sample.R, method="matrix");110111112# Estimation of mean return113M = c();114library(TTR)115Tmean = 47 # monthly returns: 4 year exponentially weighted moving average116for( i in 1:cAssets ){117# M = cbind( M , as.vector( rollmean(x=inception.R[,i],k=Tmean, align="right",na.pad=T) ) ) #2/(n+1)118M = cbind( M , as.vector( EMA(x=inception.R[,i],n=Tmean) ) ) #2/(n+1)119# M = cbind( M , as.vector(cumsum())/c(1:length(inception.R[,i])) )120}121M = zoo( M , order.by=time(inception.R) )122123# Center returns (shift by one observations since M[t,] is rolling mean t-Tmean+1,...,t; otherwise lookahead bias)124inception.R.cent = inception.R;125ZZ = matrix( rep(as.vector( apply( inception.R[1:Tmean, ] , 2 , 'mean' )),Tmean),byrow=T,nrow=Tmean);126inception.R.cent[1:Tmean,] = inception.R[1:Tmean, ] - ZZ;127if( nrow(inception.R)>(Tmean+1) ){128A = M[Tmean:(nrow(inception.R)-1),];129A = zoo( A , order.by = time(inception.R[(Tmean+1):nrow(inception.R), ])) ; #shift dates; otherwise zoo poses problem130inception.R.cent[(Tmean+1):nrow(inception.R), ] = inception.R[(Tmean+1):nrow(inception.R), ] - A}131132# Garch estimation133S = c();134for( i in 1:cAssets ){135gout = garchFit(formula ~ garch(1,1), data = inception.R.cent[,i],include.mean = F, cond.dist="QMLE", trace = FALSE )136if( as.vector(gout@fit$coef["alpha1"]) < 0.01 ){137sigmat = rep( sd( as.vector(inception.R.cent[,i])), length(inception.R.cent[,i]) );138}else{139sigmat = gout@sigma.t140}141S = cbind( S , sigmat)142}143S = zoo( S , order.by=time(inception.R.cent) )144#plot(S, main="Check visually garch volatility estimates \n If estimated alpha < 0.01, the standard deviation is used. " )145146147# Estimate correlation, coskewness and cokurtosis matrix locally using cleaned innovation series in three year estimation window148selectU = window(inception.R.cent, start = as.Date(from[per]) , end = as.Date(to[per]) )149selectU = selectU/window(S, start = as.Date(from[per]) , end = as.Date(to[per]) );150selectU = clean.boudt2(selectU , alpha = alpha )[[1]];151in.sample.T = nrow(selectU);152Rcor = matrix(rep(0,cAssets^2),nrow=cAssets,ncol=cAssets)153M3 = matrix(rep(0,cAssets^3),nrow=cAssets,ncol=cAssets^2)154M4 = matrix(rep(0,cAssets^4),nrow=cAssets,ncol=cAssets^3)155156for(t in c(1:in.sample.T)){157centret = as.vector(selectU[t,]);158Rcor = Rcor + centret%*%t(centret)159M3 = M3 + ( centret%*%t(centret) )%x%t(centret)160M4 = M4 + ( centret%*%t(centret) )%x%t(centret)%x%t(centret)161}162resSigma = Rcor = 1/in.sample.T*Rcor163sdzero = function(data){ return( sqrt(mean(data^2)) ) }164D = diag( apply(selectU,2,'sdzero')^(-1),ncol=cAssets )165Rcor = D%*%Rcor%*%D166M3 = 1/in.sample.T*M3167M4 = 1/in.sample.T*M4168169# we only need mean and conditional covariance matrix of last observation170mu = matrix(tail(M,n=1),ncol=1 ) ;171D = diag( as.vector(as.vector(tail(S,n=1) ) ),ncol=cAssets )172sigma = D%*%Rcor%*%D173174switch( percriskcontribcriterion ,175StdDev = { percriskcontrib = function(w){ cont = Portsd(w,mu=mu,sigma=sigma)[[3]] ; return( cont ) }},176GVaR = {percriskcontrib = function(w){ cont = PortgausVaR(w,alpha=alpha,mu=mu,sigma=sigma)[[3]] ; return( cont ) }},177GES = {percriskcontrib = function(w){ cont = PortgausES(w,mu=mu,alpha=alpha,sigma=sigma)[[3]] ; return( cont ) }},178mVaR = {percriskcontrib = function(w){ cont = resPortMVaR(w,mu=mu,alpha=alpha,sigma=sigma,resSigma=resSigma,M3=M3,M4=M4)[[3]] ; return( cont ) }},179mES = {percriskcontrib = function(w){ cont = resoperPortMES(w,mu=mu,alpha=alpha,sigma=sigma,resSigma=resSigma,M3=M3,M4=M4)[[3]] ; return( cont ) }}180)181RCout[ per , ] = as.vector(percriskcontrib(wper))182183} # end loop periods184185186#write.table( RCout , paste("riskcont/", percriskcontribcriterion,"/",datacase,"/",frequency,"/EW.csv" , sep=""),187# append = FALSE, quote = TRUE, sep = ",", eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = "escape")188189write.table( RCout ,file = paste("C:\\Documents and Settings\\Administrator\\Desktop\\risk budget programs\\riskcont\\mES\\equitybondscommodity\\quarterly\\unconstrained\\", "mES.4yr-InfInf" , ".csv" , sep="") );190append = FALSE, quote = TRUE, sep = ",", eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = "escape")191192193194195196197198199