Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/paper_analysis/R_interpretation/old/getRiskContrib.R
1433 views
1
2
# ! Set your working directory (folder containing the subfolders R_allocation, R_interpretation, data, weights, etc)
3
4
setwd("c:/Documents and Settings/Administrator/Desktop/risk budget programs")
5
6
# Programs:
7
8
source("R_Allocation/allocation_functions_monthly.R"); source("R_Allocation/estimators.R");
9
library(zoo); library(fGarch); library("PerformanceAnalytics");
10
memory.limit(2048)
11
12
# Choose data
13
datacase = "equitybondscommodity" # "equitybondscommodity" or "equitybondscommodity"
14
15
# Define optimization criteria
16
criteria = c( "EW" )
17
18
# Yearly or quarterly rebalancing
19
yearly = F;
20
21
# Length estimation period
22
estyears = 4
23
24
source("R_Allocation/allocation_functions_monthly.R"); source("R_Allocation/estimators.R");
25
library(zoo); library(fGarch); library("PerformanceAnalytics");
26
memory.limit(2048)
27
28
#############################################################################
29
# Load the data
30
#############################################################################
31
32
firstyear = 1976 ; firstquarter = 1; lastyear = 2009; lastquarter = 2;
33
34
data = read.table( file= paste("data/",datacase,"/data.txt",sep="") ,header=T)
35
date = as.Date(data[,1],format="%Y-%m-%d")
36
data = zoo( data[,2:ncol(data)] , order.by = date )
37
38
# "Bond" "SP500" "EAFE" "SPGSCI" "TBill" "Inflation"
39
40
cAssets = ncol(data)-2; # number of risky assets
41
42
# The loaded data has monthly frequency
43
44
# Estimation uses real returns
45
46
monthlyR = data[,(1:(cAssets+1))]-data[,cAssets+2]
47
monthlyR.cash = monthlyR[,cAssets+1]
48
R = monthlyR[,1:cAssets]
49
plot(R)
50
51
head(R);tail(R)
52
53
from=to=c();
54
55
if(yearly){
56
for( year in firstyear:(lastyear-estyears+1) ){
57
from = c( from , paste( year,"-01-01",sep="" ) );
58
to = c( to , paste( (year+estyears-1),"-12-31",sep="" ) ) }
59
nsamples = length(from);
60
names.input = paste( rep("y_",nsamples) , seq( (firstyear+estyears),lastyear+1,1) , sep="" );
61
}else{
62
for( year in firstyear:(lastyear-estyears) ){
63
from = c( from , paste( year,"-01-01",sep="" ) , paste( year,"-04-01",sep="" ) , paste( year,"-07-01",sep="" ) , paste( year,"-10-01",sep="" ) );
64
to = c( to , paste( (year+estyears-1),"-12-31",sep="" ), paste( (year+estyears),"-03-31",sep="" ), paste( (year+estyears),"-06-30",sep="" ),
65
paste( (year+estyears),"-09-30",sep="" ) ) }
66
from = c( from , paste( year+1,"-01-01",sep="" ) ); to = c( to , paste( (year+estyears),"-12-31",sep="" ) )
67
nsamples = length(from);
68
#names of quarters for which the forecast is made:
69
names.input = paste( c("Q1y_","Q2y_","Q3y_","Q4y_") , rep(seq( (firstyear+estyears),lastyear,1),each=4) , sep="" );
70
names.input = c( names.input , paste( "Q1y_" , lastyear+1, sep="" ) );
71
# this is assuming estimation window runs from firstyearQ1 to lastyearQ4
72
from = from[firstquarter:(length(from)-4+lastquarter)]; to = to[firstquarter:(length(to)-4+lastquarter)]
73
names.input = names.input[firstquarter:(length(names.input)-4+lastquarter)]
74
}
75
76
cPeriods = length(to) ; cCriteria = length(criteria) ;
77
78
percriskcontribcriterion = "mES";
79
80
RCout = matrix( rep(0,cPeriods*cAssets) , ncol= cAssets );
81
82
#wper = matrix(rep(1/cAssets, cAssets),ncol=1)
83
84
W = read.csv( file = paste("C:\\Documents and Settings\\Administrator\\Desktop\\risk budget programs\\weights\\mES\\equitybondscommodity\\quarterly\\unconstrained\\", "mES.4yr-InfInf" , ".csv" , sep="") );
85
86
87
RCout = matrix( rep(0, cCriteria*cPeriods*(cAssets)) , ncol= (cAssets) ); # add possibility of cash if risk budget constraints are infeasible.
88
89
90
# downside risk
91
alpha = 0.05;
92
93
# Estimation of the return mean vector, covariance, coskewness and cokurtosis matrix
94
95
96
for( per in c(1:cPeriods) ){
97
98
print("-----------New estimation period ends on observation------------------")
99
print( paste(to[per],"out of total number of obs equal to", max(to) ));
100
print("----------------------------------------------------------------")
101
102
matrix(as.vector(wper[1:4]),ncol=1)
103
104
# Estimate GARCH model with data from inception
105
106
inception.R = window(R, start = as.Date(from[1]) , end = as.Date(to[per]) );
107
108
# Estimate comoments of innovations with rolling estimation windows
109
in.sample.R = window(R, start = as.Date(from[per]) , end = as.Date(to[per]) );
110
in.sample.R = checkData(in.sample.R, method="matrix");
111
112
113
# Estimation of mean return
114
M = c();
115
library(TTR)
116
Tmean = 47 # monthly returns: 4 year exponentially weighted moving average
117
for( i in 1:cAssets ){
118
# M = cbind( M , as.vector( rollmean(x=inception.R[,i],k=Tmean, align="right",na.pad=T) ) ) #2/(n+1)
119
M = cbind( M , as.vector( EMA(x=inception.R[,i],n=Tmean) ) ) #2/(n+1)
120
# M = cbind( M , as.vector(cumsum())/c(1:length(inception.R[,i])) )
121
}
122
M = zoo( M , order.by=time(inception.R) )
123
124
# Center returns (shift by one observations since M[t,] is rolling mean t-Tmean+1,...,t; otherwise lookahead bias)
125
inception.R.cent = inception.R;
126
ZZ = matrix( rep(as.vector( apply( inception.R[1:Tmean, ] , 2 , 'mean' )),Tmean),byrow=T,nrow=Tmean);
127
inception.R.cent[1:Tmean,] = inception.R[1:Tmean, ] - ZZ;
128
if( nrow(inception.R)>(Tmean+1) ){
129
A = M[Tmean:(nrow(inception.R)-1),];
130
A = zoo( A , order.by = time(inception.R[(Tmean+1):nrow(inception.R), ])) ; #shift dates; otherwise zoo poses problem
131
inception.R.cent[(Tmean+1):nrow(inception.R), ] = inception.R[(Tmean+1):nrow(inception.R), ] - A}
132
133
# Garch estimation
134
S = c();
135
for( i in 1:cAssets ){
136
gout = garchFit(formula ~ garch(1,1), data = inception.R.cent[,i],include.mean = F, cond.dist="QMLE", trace = FALSE )
137
if( as.vector(gout@fit$coef["alpha1"]) < 0.01 ){
138
sigmat = rep( sd( as.vector(inception.R.cent[,i])), length(inception.R.cent[,i]) );
139
}else{
140
sigmat = gout@sigma.t
141
}
142
S = cbind( S , sigmat)
143
}
144
S = zoo( S , order.by=time(inception.R.cent) )
145
#plot(S, main="Check visually garch volatility estimates \n If estimated alpha < 0.01, the standard deviation is used. " )
146
147
148
# Estimate correlation, coskewness and cokurtosis matrix locally using cleaned innovation series in three year estimation window
149
selectU = window(inception.R.cent, start = as.Date(from[per]) , end = as.Date(to[per]) )
150
selectU = selectU/window(S, start = as.Date(from[per]) , end = as.Date(to[per]) );
151
selectU = clean.boudt2(selectU , alpha = alpha )[[1]];
152
in.sample.T = nrow(selectU);
153
Rcor = matrix(rep(0,cAssets^2),nrow=cAssets,ncol=cAssets)
154
M3 = matrix(rep(0,cAssets^3),nrow=cAssets,ncol=cAssets^2)
155
M4 = matrix(rep(0,cAssets^4),nrow=cAssets,ncol=cAssets^3)
156
157
for(t in c(1:in.sample.T)){
158
centret = as.vector(selectU[t,]);
159
Rcor = Rcor + centret%*%t(centret)
160
M3 = M3 + ( centret%*%t(centret) )%x%t(centret)
161
M4 = M4 + ( centret%*%t(centret) )%x%t(centret)%x%t(centret)
162
}
163
resSigma = Rcor = 1/in.sample.T*Rcor
164
sdzero = function(data){ return( sqrt(mean(data^2)) ) }
165
D = diag( apply(selectU,2,'sdzero')^(-1),ncol=cAssets )
166
Rcor = D%*%Rcor%*%D
167
M3 = 1/in.sample.T*M3
168
M4 = 1/in.sample.T*M4
169
170
# we only need mean and conditional covariance matrix of last observation
171
mu = matrix(tail(M,n=1),ncol=1 ) ;
172
D = diag( as.vector(as.vector(tail(S,n=1) ) ),ncol=cAssets )
173
sigma = D%*%Rcor%*%D
174
175
switch( percriskcontribcriterion ,
176
StdDev = { percriskcontrib = function(w){ cont = Portsd(w,mu=mu,sigma=sigma)[[3]] ; return( cont ) }},
177
GVaR = {percriskcontrib = function(w){ cont = PortgausVaR(w,alpha=alpha,mu=mu,sigma=sigma)[[3]] ; return( cont ) }},
178
GES = {percriskcontrib = function(w){ cont = PortgausES(w,mu=mu,alpha=alpha,sigma=sigma)[[3]] ; return( cont ) }},
179
mVaR = {percriskcontrib = function(w){ cont = resPortMVaR(w,mu=mu,alpha=alpha,sigma=sigma,resSigma=resSigma,M3=M3,M4=M4)[[3]] ; return( cont ) }},
180
mES = {percriskcontrib = function(w){ cont = resoperPortMES(w,mu=mu,alpha=alpha,sigma=sigma,resSigma=resSigma,M3=M3,M4=M4)[[3]] ; return( cont ) }}
181
)
182
RCout[ per , ] = as.vector(percriskcontrib(wper))
183
184
} # end loop periods
185
186
187
#write.table( RCout , paste("riskcont/", percriskcontribcriterion,"/",datacase,"/",frequency,"/EW.csv" , sep=""),
188
# append = FALSE, quote = TRUE, sep = ",", eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = "escape")
189
190
write.table( RCout ,file = paste("C:\\Documents and Settings\\Administrator\\Desktop\\risk budget programs\\riskcont\\mES\\equitybondscommodity\\quarterly\\unconstrained\\", "mES.4yr-InfInf" , ".csv" , sep="") );
191
append = FALSE, quote = TRUE, sep = ",", eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = "escape")
192
193
194
195
196
197
198
199