Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/paper_analysis/R_Allocation/prepare_data_bis.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
# setwd("c:/Documents and Settings/n06054/Desktop/risk budget programs")
6
7
# Options:
8
9
# Length estimation period
10
estyears = 5
11
CC = T;
12
mean_EMA = FALSE # use exponentially weighted moving average or not
13
14
# Load programs
15
16
source("R_Allocation/Risk_budget_functions.R");
17
library(zoo); library(fGarch); library("PerformanceAnalytics");
18
19
if(CC){ source( paste( getwd(),"/R_allocation/coskewkurtosis.R" ,sep="") ) }
20
source( paste( getwd(),"/R_allocation/estimationfunctions.R" ,sep="") )
21
22
# Load the data
23
24
nominal = T;
25
newdata = T;
26
firstyear = 1976 ; firstquarter = 1; lastyear = 2010; lastquarter = 2;
27
28
if(newdata){
29
data = read.table( file= paste("data/","data.txt",sep="") ,header=T)
30
# "Bond" "SP500" "NAREIT" "SPGSCI" "TBill" "Inflation" "EAFE"
31
date = as.Date(data[,1],format="%Y-%m-%d")
32
data = zoo( data[,2:ncol(data)] , order.by = date )
33
# "Bond" "SP500" "EAFE" "SPGSCI" "TBill" "Inflation" "EAFE"
34
cAssets = ncol(data)-3; # number of risky assets
35
# The loaded data has monthly frequency
36
if(!nominal){ monthlyR = data[,(1:(cAssets))]-data[,cAssets+2] }else{ monthlyR = data[,1:cAssets] }
37
plot(monthlyR)
38
if(nominal){ save(monthlyR,file="data/monthlyR.RData") }else{ save(monthlyR,file="data/monthlyR_real.RData") }
39
}else{
40
if(nominal){ load(file="data/monthlyR.RData") }else{ load(file="data/monthlyR_real.RData") }
41
}
42
43
# Define rebalancing periods:
44
45
ep = endpoints(monthlyR,on='quarters')
46
# select those for estimation period
47
ep.start = ep[1:(length(ep)-estyears*4)]+1
48
from = time(monthlyR)[ep.start]
49
from = seq( as.Date(paste(firstyear,"-01-01",sep="")), as.Date(paste(lastyear-estyears,"-07-01",sep="")), by="3 month")
50
ep.end = ep[(1+estyears*4):length(ep)]
51
to = time(monthlyR)[ep.end]
52
cPeriods = length(from);
53
54
estimateMoments = TRUE;
55
56
matrix.sqrt = function(A){
57
# Function that computes the square root of a symmetric, positive definite matrix:
58
sva = La.svd(A);
59
if( min(sva$d)>=0 ){
60
Asqrt = sva$u%*%diag(sqrt(sva$d)) }else{
61
stop("Matrix square root is not defined")}
62
return(Asqrt)
63
}
64
65
comoments_inception = TRUE
66
N = ncol (monthlyR)
67
68
if(estimateMoments){
69
70
R = monthlyR
71
72
mulist = sigmalist = M3list = M4list = {}
73
74
for( per in c(1:cPeriods) ){
75
76
print("-----------New estimation period ends on observation------------------")
77
print( paste(to[per],"out of total number of obs equal to", max(to) ));
78
print("----------------------------------------------------------------")
79
80
# Estimate GARCH model with data from inception
81
82
inception.R = window(R, start = as.Date(from[1]) , end = as.Date(to[per]) );
83
84
# Estimate comoments of innovations with rolling estimation windows
85
if(comoments_inception){
86
in.sample.R = inception.R;
87
}else{
88
in.sample.R = window(R, start = as.Date(from[per]) , end = as.Date(to[per]) );
89
in.sample.R = checkData(in.sample.R, method="matrix");
90
}
91
92
# Estimation of mean return
93
if( mean_EMA ){
94
M = c();
95
library(TTR)
96
Tmean = 47 # monthly returns: 4 year exponentially weighted moving average
97
for( i in 1:cAssets ){
98
M = cbind( M , as.vector( EMA(x=inception.R[,i],n=Tmean) ) ) #2/(n+1)
99
M = zoo( M , order.by=time(inception.R) )
100
}
101
mulist[[per]] = matrix(tail(M,n=1),ncol=1 ) ;
102
103
# Center returns (shift by one observations since M[t,] is rolling mean t-Tmean+1,...,t; otherwise lookahead bias)
104
inception.R.cent = inception.R;
105
ZZ = matrix( rep(as.vector( apply( inception.R[1:Tmean, ] , 2 , 'mean' )),Tmean),byrow=T,nrow=Tmean);
106
inception.R.cent[1:Tmean,] = inception.R[1:Tmean, ] - ZZ;
107
if( nrow(inception.R)>(Tmean+1) ){
108
A = M[Tmean:(nrow(inception.R)-1),];
109
A = zoo( A , order.by = time(inception.R[(Tmean+1):nrow(inception.R), ])) ; #shift dates; otherwise zoo poses problem
110
inception.R.cent[(Tmean+1):nrow(inception.R), ] = inception.R[(Tmean+1):nrow(inception.R), ] - A}
111
112
}else{
113
mu = apply( inception.R , 2 , 'mean' )
114
mulist[[per]] = mu
115
ZZ = matrix( rep( mu , nrow(inception.R) ),byrow=T,nrow=nrow(inception.R));
116
inception.R.cent = inception.R - ZZ;
117
}
118
119
120
121
# Garch estimation
122
S = S_forecast = c();
123
124
125
hatsigma <- function( par , x ){
126
alpha = par[1] ; beta = par[2];
127
omega = uncH*(1-alpha-beta)
128
T = length(x)
129
s2 = rep( uncH , T )
130
# Include the FILTER here to replace the loop
131
e2 <- x^2
132
# If the index is negative, it would strip the member whose position has the same absolute value as the negative index.
133
e2t <- omega + alpha*c(mean(e2),e2[-length(x)])
134
s2 <- filter(e2t, beta, "recursive", init = mean(e2))
135
return(s2)
136
}
137
138
llhGarch11N <- function(par, x)
139
{
140
s2 = hatsigma( par = par , x = x )
141
-sum(log(dnorm(x, mean = 0, sd = sqrt(abs(s2)))))
142
}
143
144
parN = c(0.04,0.95)
145
small <- 1e-3
146
lowN <- c( small, small)
147
upN <- c( 1-small, 1-small)
148
149
vuncH = rep(NA,cAssets)
150
for( i in 1:cAssets ){
151
#k = qchisq(0.99,df=1) ;
152
#jumpIndicator = ( (inception.R.cent[,i]/mad(inception.R.cent[,i]))^2<=k )
153
#xfilt = inception.R.cent[jumpIndicator,i]
154
#uncH = mean(xfilt^2)*(0.99/pchisq(k,df=3))
155
uncH = mean(inception.R.cent[,i]^2)
156
fitN <- nlminb(start=parN, objective=llhGarch11N , x = inception.R.cent[,i], lower=lowN, upper=upN,
157
control=list(x.tol = 1e-8,trace=1))
158
par <- round(fitN$par,6)
159
x = inception.R.cent[,i]
160
# Likelihood ratio test statistic for the case of time-varying garch effects
161
162
# if less than 1% improvement wrt constant, we use the constant
163
sigmat = sqrt(hatsigma( par = par , x = inception.R.cent[,i]) )
164
e2 = as.numeric(tail(inception.R.cent[,i],1)^2)
165
S_forecast = c( S_forecast ,
166
sqrt( uncH*(1-sum(par))+ par[1]*e2+ par[2]*tail(sigmat,1)^2 ) )
167
168
S = cbind( S , sigmat)
169
#gout = garchFit(formula ~ garch(1,1), data = inception.R.cent[,i],include.mean = F, cond.dist="QMLE", trace = FALSE )
170
vuncH[i] = uncH
171
}
172
S = zoo( S , order.by=time(inception.R.cent) )
173
plot(S)
174
print( sqrt(vuncH) )
175
176
# Estimate correlation, coskewness and cokurtosis matrix locally using cleaned innovation series in three year estimation window
177
if(comoments_inception){
178
selectU = window(inception.R.cent, start = as.Date(from[1]) , end = as.Date(to[per]) )
179
selectU = selectU/window(S, start = as.Date(from[1]) , end = as.Date(to[per]) );
180
}else{
181
selectU = window(inception.R.cent, start = as.Date(from[per]) , end = as.Date(to[per]) )
182
selectU = selectU/window(S, start = as.Date(from[per]) , end = as.Date(to[per]) );
183
}
184
selectU = clean.boudt2(selectU , alpha = 0.05 )[[1]];
185
Rcor = cor(selectU)
186
Rcor = cor(selectU)
187
Rt = DCCestimation( mDevolR.centered= as.matrix(selectU) , parN = parN , uncR = Rcor )
188
189
D = diag(S_forecast)
190
sigma = D%*%Rcor%*%D;
191
sigmalist[[per]] = sigma;
192
in.sample.T = nrow(selectU);
193
# set volatility of all U to last observation, such that cov(rescaled U)=sigma [correct this in PA]
194
uncS = sqrt(diag( cov(selectU) ))
195
selectU = selectU*matrix( rep(S_forecast/uncS,in.sample.T ) , ncol = cAssets , byrow = T )
196
if(!CC){
197
M3list[[per]] = PerformanceAnalytics:::M3.MM(selectU)
198
M4list[[per]] = PerformanceAnalytics:::M4.MM(selectU)
199
}else{
200
M3list[[per]] = coskewCC(selectU)
201
M4list[[per]] = cokurtCC(selectU)
202
}
203
}
204
205
}
206
207
if(nominal){
208
save( mulist , file="data/mulist.Rdata") ; save( sigmalist , file="data/sigmalist.Rdata") ;
209
if(!CC){ save( M3list , file="data/M3list.Rdata") ; save( M4list , file="data/M4list.Rdata") }else{
210
save( M3list , file="data/M3list_CC.Rdata") ; save( M4list , file="data/M4list_CC.Rdata")
211
}
212
}else{
213
save( mulist , file="data/mulist_real.Rdata") ; save( sigmalist , file="data/sigmalist_real.Rdata") ;
214
if(!CC){ save( M3list , file="data/M3list_real.Rdata") ; save( M4list , file="data/M4list_real.Rdata") }else{
215
save( M3list , file="data/M3list_real_CC.Rdata") ; save( M4list , file="data/M4list_real_CC.Rdata")
216
}
217
}
218
219
220
# sqrt(diag( sigmalist[[28]]))
221
# sqrt(diag( sigmalist[[29]]))
222
223
s1 = s2 = s3 = s4 =c()
224
225
for( k in 1:length(sigmalist) ){
226
S = sigmalist[[k]]
227
s1 = c( s1 , S[1,1] ) ; s2 = c( s2 , S[2,2] )
228
s3 = c( s3 , S[3,3] ) ; s4 = c( s4 , S[4,4] )
229
}
230
par( mfrow=c(2,2) ); plot( sqrt(s1) , type="l" ) ; plot( sqrt(s2) , type="l") ; plot( sqrt(s3) , type="l") ; plot( sqrt(s4) , type="l")
231
232
233
234
235