Path: blob/master/sandbox/paper_analysis/R_Allocation/prepare_data_bis.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")4# setwd("c:/Documents and Settings/n06054/Desktop/risk budget programs")56# Options:78# Length estimation period9estyears = 510CC = T;11mean_EMA = FALSE # use exponentially weighted moving average or not1213# Load programs1415source("R_Allocation/Risk_budget_functions.R");16library(zoo); library(fGarch); library("PerformanceAnalytics");1718if(CC){ source( paste( getwd(),"/R_allocation/coskewkurtosis.R" ,sep="") ) }19source( paste( getwd(),"/R_allocation/estimationfunctions.R" ,sep="") )2021# Load the data2223nominal = T;24newdata = T;25firstyear = 1976 ; firstquarter = 1; lastyear = 2010; lastquarter = 2;2627if(newdata){28data = read.table( file= paste("data/","data.txt",sep="") ,header=T)29# "Bond" "SP500" "NAREIT" "SPGSCI" "TBill" "Inflation" "EAFE"30date = as.Date(data[,1],format="%Y-%m-%d")31data = zoo( data[,2:ncol(data)] , order.by = date )32# "Bond" "SP500" "EAFE" "SPGSCI" "TBill" "Inflation" "EAFE"33cAssets = ncol(data)-3; # number of risky assets34# The loaded data has monthly frequency35if(!nominal){ monthlyR = data[,(1:(cAssets))]-data[,cAssets+2] }else{ monthlyR = data[,1:cAssets] }36plot(monthlyR)37if(nominal){ save(monthlyR,file="data/monthlyR.RData") }else{ save(monthlyR,file="data/monthlyR_real.RData") }38}else{39if(nominal){ load(file="data/monthlyR.RData") }else{ load(file="data/monthlyR_real.RData") }40}4142# Define rebalancing periods:4344ep = endpoints(monthlyR,on='quarters')45# select those for estimation period46ep.start = ep[1:(length(ep)-estyears*4)]+147from = time(monthlyR)[ep.start]48from = seq( as.Date(paste(firstyear,"-01-01",sep="")), as.Date(paste(lastyear-estyears,"-07-01",sep="")), by="3 month")49ep.end = ep[(1+estyears*4):length(ep)]50to = time(monthlyR)[ep.end]51cPeriods = length(from);5253estimateMoments = TRUE;5455matrix.sqrt = function(A){56# Function that computes the square root of a symmetric, positive definite matrix:57sva = La.svd(A);58if( min(sva$d)>=0 ){59Asqrt = sva$u%*%diag(sqrt(sva$d)) }else{60stop("Matrix square root is not defined")}61return(Asqrt)62}6364comoments_inception = TRUE65N = ncol (monthlyR)6667if(estimateMoments){6869R = monthlyR7071mulist = sigmalist = M3list = M4list = {}7273for( per in c(1:cPeriods) ){7475print("-----------New estimation period ends on observation------------------")76print( paste(to[per],"out of total number of obs equal to", max(to) ));77print("----------------------------------------------------------------")7879# Estimate GARCH model with data from inception8081inception.R = window(R, start = as.Date(from[1]) , end = as.Date(to[per]) );8283# Estimate comoments of innovations with rolling estimation windows84if(comoments_inception){85in.sample.R = inception.R;86}else{87in.sample.R = window(R, start = as.Date(from[per]) , end = as.Date(to[per]) );88in.sample.R = checkData(in.sample.R, method="matrix");89}9091# Estimation of mean return92if( mean_EMA ){93M = c();94library(TTR)95Tmean = 47 # monthly returns: 4 year exponentially weighted moving average96for( i in 1:cAssets ){97M = cbind( M , as.vector( EMA(x=inception.R[,i],n=Tmean) ) ) #2/(n+1)98M = zoo( M , order.by=time(inception.R) )99}100mulist[[per]] = matrix(tail(M,n=1),ncol=1 ) ;101102# Center returns (shift by one observations since M[t,] is rolling mean t-Tmean+1,...,t; otherwise lookahead bias)103inception.R.cent = inception.R;104ZZ = matrix( rep(as.vector( apply( inception.R[1:Tmean, ] , 2 , 'mean' )),Tmean),byrow=T,nrow=Tmean);105inception.R.cent[1:Tmean,] = inception.R[1:Tmean, ] - ZZ;106if( nrow(inception.R)>(Tmean+1) ){107A = M[Tmean:(nrow(inception.R)-1),];108A = zoo( A , order.by = time(inception.R[(Tmean+1):nrow(inception.R), ])) ; #shift dates; otherwise zoo poses problem109inception.R.cent[(Tmean+1):nrow(inception.R), ] = inception.R[(Tmean+1):nrow(inception.R), ] - A}110111}else{112mu = apply( inception.R , 2 , 'mean' )113mulist[[per]] = mu114ZZ = matrix( rep( mu , nrow(inception.R) ),byrow=T,nrow=nrow(inception.R));115inception.R.cent = inception.R - ZZ;116}117118119120# Garch estimation121S = S_forecast = c();122123124hatsigma <- function( par , x ){125alpha = par[1] ; beta = par[2];126omega = uncH*(1-alpha-beta)127T = length(x)128s2 = rep( uncH , T )129# Include the FILTER here to replace the loop130e2 <- x^2131# If the index is negative, it would strip the member whose position has the same absolute value as the negative index.132e2t <- omega + alpha*c(mean(e2),e2[-length(x)])133s2 <- filter(e2t, beta, "recursive", init = mean(e2))134return(s2)135}136137llhGarch11N <- function(par, x)138{139s2 = hatsigma( par = par , x = x )140-sum(log(dnorm(x, mean = 0, sd = sqrt(abs(s2)))))141}142143parN = c(0.04,0.95)144small <- 1e-3145lowN <- c( small, small)146upN <- c( 1-small, 1-small)147148vuncH = rep(NA,cAssets)149for( i in 1:cAssets ){150#k = qchisq(0.99,df=1) ;151#jumpIndicator = ( (inception.R.cent[,i]/mad(inception.R.cent[,i]))^2<=k )152#xfilt = inception.R.cent[jumpIndicator,i]153#uncH = mean(xfilt^2)*(0.99/pchisq(k,df=3))154uncH = mean(inception.R.cent[,i]^2)155fitN <- nlminb(start=parN, objective=llhGarch11N , x = inception.R.cent[,i], lower=lowN, upper=upN,156control=list(x.tol = 1e-8,trace=1))157par <- round(fitN$par,6)158x = inception.R.cent[,i]159# Likelihood ratio test statistic for the case of time-varying garch effects160161# if less than 1% improvement wrt constant, we use the constant162sigmat = sqrt(hatsigma( par = par , x = inception.R.cent[,i]) )163e2 = as.numeric(tail(inception.R.cent[,i],1)^2)164S_forecast = c( S_forecast ,165sqrt( uncH*(1-sum(par))+ par[1]*e2+ par[2]*tail(sigmat,1)^2 ) )166167S = cbind( S , sigmat)168#gout = garchFit(formula ~ garch(1,1), data = inception.R.cent[,i],include.mean = F, cond.dist="QMLE", trace = FALSE )169vuncH[i] = uncH170}171S = zoo( S , order.by=time(inception.R.cent) )172plot(S)173print( sqrt(vuncH) )174175# Estimate correlation, coskewness and cokurtosis matrix locally using cleaned innovation series in three year estimation window176if(comoments_inception){177selectU = window(inception.R.cent, start = as.Date(from[1]) , end = as.Date(to[per]) )178selectU = selectU/window(S, start = as.Date(from[1]) , end = as.Date(to[per]) );179}else{180selectU = window(inception.R.cent, start = as.Date(from[per]) , end = as.Date(to[per]) )181selectU = selectU/window(S, start = as.Date(from[per]) , end = as.Date(to[per]) );182}183selectU = clean.boudt2(selectU , alpha = 0.05 )[[1]];184Rcor = cor(selectU)185Rcor = cor(selectU)186Rt = DCCestimation( mDevolR.centered= as.matrix(selectU) , parN = parN , uncR = Rcor )187188D = diag(S_forecast)189sigma = D%*%Rcor%*%D;190sigmalist[[per]] = sigma;191in.sample.T = nrow(selectU);192# set volatility of all U to last observation, such that cov(rescaled U)=sigma [correct this in PA]193uncS = sqrt(diag( cov(selectU) ))194selectU = selectU*matrix( rep(S_forecast/uncS,in.sample.T ) , ncol = cAssets , byrow = T )195if(!CC){196M3list[[per]] = PerformanceAnalytics:::M3.MM(selectU)197M4list[[per]] = PerformanceAnalytics:::M4.MM(selectU)198}else{199M3list[[per]] = coskewCC(selectU)200M4list[[per]] = cokurtCC(selectU)201}202}203204}205206if(nominal){207save( mulist , file="data/mulist.Rdata") ; save( sigmalist , file="data/sigmalist.Rdata") ;208if(!CC){ save( M3list , file="data/M3list.Rdata") ; save( M4list , file="data/M4list.Rdata") }else{209save( M3list , file="data/M3list_CC.Rdata") ; save( M4list , file="data/M4list_CC.Rdata")210}211}else{212save( mulist , file="data/mulist_real.Rdata") ; save( sigmalist , file="data/sigmalist_real.Rdata") ;213if(!CC){ save( M3list , file="data/M3list_real.Rdata") ; save( M4list , file="data/M4list_real.Rdata") }else{214save( M3list , file="data/M3list_real_CC.Rdata") ; save( M4list , file="data/M4list_real_CC.Rdata")215}216}217218219# sqrt(diag( sigmalist[[28]]))220# sqrt(diag( sigmalist[[29]]))221222s1 = s2 = s3 = s4 =c()223224for( k in 1:length(sigmalist) ){225S = sigmalist[[k]]226s1 = c( s1 , S[1,1] ) ; s2 = c( s2 , S[2,2] )227s3 = c( s3 , S[3,3] ) ; s4 = c( s4 , S[4,4] )228}229par( mfrow=c(2,2) ); plot( sqrt(s1) , type="l" ) ; plot( sqrt(s2) , type="l") ; plot( sqrt(s3) , type="l") ; plot( sqrt(s4) , type="l")230231232233234235