Let's say I have a 10 year dataset of Tesla (example) and I am taking the percentage change of lag 2:
tsla <- quantmod::getSymbols("TSLA", from = base::as.Date("2011-01-01"), to = base::as.Date("2022-01-31"), auto.assign = F)
tsla = as_tibble(tsla)
head(tsla)
d = tsla%>%
dplyr::select(TSLA.Adjusted)%>%
dplyr::mutate(Close = TSLA.Adjusted)%>%
dplyr::mutate(y = as.numeric((Close - dplyr::lag(Close, 2)) / Close))%>%
dplyr::select(Close,y)%>%
tidyr::drop_na();d
That look like this:
# A tibble: 2,786 × 2
Close y
<dbl> <dbl>
1 5.37 0.00783
2 5.58 0.0434
3 5.65 0.0499
4 5.69 0.0200
5 5.39 -0.0475
6 5.39 -0.0553
7 5.24 -0.0282
8 5.15 -0.0470
9 5.13 -0.0226
10 4.81 -0.0716
# … with 2,776 more rows
Now I want to fit the GARCH(1,1) model with normal innovations.
garnor1 = function(x){
require(fGarch)
t = length(x)
fit = garchFit(~garch(1,1),data=x,trace=F,cond.dist="norm")
m = fit@fitted
cv = [email protected]
var = m+cv*qnorm(0.01) # low tail
return(var[t])
}
What I have succeeded is that I can estimate the the lower value at risk for 2-day returns up to time $t$. This will give a number that is the VaR up until now (say today). Am I right until now?
If yes, I know that the VaR is being calculated from the predictive function for the $t+2$ quantile value. Doing so I have to predict the above function:
g11pre = function(x){
require(fGarch)
fit = garchFit(~garch(1,1),data=x,trace=F,cond.dist="norm")
df=coef(fit)["shape"]
p = predict(fit,2)
m=p$meanForecast
cv=p$standardDeviation
var=m+cv*qnorm(0.01)
return(var[2])
}
And this last predictive function I have to backtest or the previous one?
Edit
For the backtesting in the predictive function I tried something by my own.(in order to fully understand it):
db= d%>%
dplyr::mutate(back_lower = zoo::rollapplyr(y,252,FUN = g11pre,by = 21,fill=NA))%>%
tidyr::fill(back_lower)%>%
tidyr::drop_na()
I know it looks strange.Let me explain.I am using the full 10 year dataset.The period of estimation are the first 252 days and then roll by one month (21) days.I am not interested on by 2 day assess-roll the model. Plotting the backtesting result:
p = ggplot() +
geom_line(data = db, aes(x =1:length(y) , y = y), color = "black") +
geom_line(data = db, aes(x = 1:length(back_lower), y = back_lower), color = "red") +
xlab('') +
ylab('risk low')
That looks like a step graph (this what It must look like)