My intention is to generate a forecast using a GARCH(1,1) using data from an expanding window. Everyday a new return enters the dataset and I will redo the GARCH fit and forecast. The function myFit does this but now I need to pass as argument a window of returns that is increasing everyday. Two ways two do this are apply.fromstart() and rollapplyr().
In the code below I decide to start the rolling calculation after at least 100 returns are collected since this is the minimum amount of data that is required by ugarchforecast() to perform a forecast.
The last two lines call myFit an starting with a window of 100 they apply the function on an expanding window. I was expecting both apply.fromstart() and rollapplyr() to provide the same data if set up as below. After all they apply the same function (myFit) to the same data. Unfortunately only the first value is the same then the forecast are not aligned anymore.
library(quantmod)
library(PerformanceAnalytics)
library(rugarch)
source('~/Dropbox/myFit.R')
symbolLst <- c("^GSPC","^VIX")
startDate = as.Date("2004-01-01")
endDate = as.Date("2004-06-01")
myForHorizon = 22
myLag = 10
myData <- new.env()
getSymbols(symbolLst, env = myData, src = "yahoo", from = startDate, to = endDate)
args = eapply(myData,
function(x){OHLC(x)})
my_data = do.call(cbind,
args,
envir = myData)
my_data$Return <- ClCl(myData$GSPC)
my_data$Return[is.na(my_data$Return)] <- 0
spec = ugarchspec(
variance.model=list(garchOrder=c(1,1)))
forecastVec1 <- apply.fromstart(my_data$Return, FUN=myFit, gap = 100)
forecastVec2 <- rollapplyr(my_data$Return, width = seq(100, 104, 1), FUN=myFit)
This is myFit
myFit <- function(myVector)
{
#library(rugarch)
myVec <- myVector
tryCatch(
{
fit = ugarchfit(spec=spec, data=myVec)
forecast = ugarchforecast(fit, n.ahead=myForHorizon)
myForecast = sigma(forecast)[myForHorizon,] * sqrt(252) * 100
print(myForecast)
return(myForecast)
},
warning = function(warn) FALSE,
error = function(err) FALSE
)
}
These are the elements of forecastVec1 (so the forecasts when apply.fromstart() is used):
[1] 12.35142
[1] 12.1961
[1] 12.45849
[1] 11.95578
[1] 12.08832
and these are the elements of forecastVec2 (using rollapplyr()):
[1] 12.35142
[1] 12.15684
[1] 12.10457
[1] 11.89805
[1] 11.94493
As said only the first element is the same. It is probably wrong the way I am applying the increasing window in rollapplyr()? I am passing a vector of widths so I am expecting that at each iteration the function will use a window of 100, then 101, then 102...103 and finally 104. Which should be the same logic followed by apply.fromstart() since I set gap=100 and it should increase the window by 1 each iteration.
Can you please help me finding the error? Thanks.