Rolling window forecast

Hello all,

I am trying to make a rolling window forecast, but I am having troubles doing so. My goal is to compute one-step ahead forecast by using fixed number of observations (1444 in my case).

That means, that to compute Forecast for observation 1445 I will use AR(1) model with data from observations 1-1444. To compute forecast for observation 1446 I will use AR(1) model with data from observations 2-1445 and so on.

However, I can't get it to work in R, so any help would be greatly appreciated. Cheers

Below is the code that I tried:

data.xts$AR1EX_Forecast<-NA

for (s in data.xts$t) {
  if(s>=1444 && s<nrow(data.xts)){
    model.1=Arima(data.xts$RealizedVariance, order = c(1,0,0), seasonal = FALSE)
    forecast=forecast(model.1,h=1)
    data.xts$AR1EX_Forecast<- forecast$fitted
  }
}

Hi, and welcome!

Please see the FAQ: What's a reproducible example (`reprex`) and how do I do one? Using a reprex, complete with representative data will attract quicker and more answers. In particular, it's hard to reproduce an issue without representative data.

Forecasting Principles and Practice has a brief discussion of moving average forecasts (not the same a moving average smoothing).

The h argument to forecast can take a range ahead based on the fit of the data. It would seem, therefore, in order to generate n period-ahead forecasts, it would be necessary first to generate n fits.

I'd prefer to do this by mapping, rather than looping, using purrr:map I'd first write a function to generate the fits by successively subsetting data.xts, taking as its argument seq(1445:nrow(data.xts) and then another function to do the fit, taking as its argument the successive fits.

The resulting object from the first function, say fits would be fed to the second function, say aheads with

purrr:map(fit,heads)

The tsCV() function in the forecast package is designed to do exactly this. See the examples in the help file. It returns the errors, rather than the forecasts, but you can easily compute the forecasts by substracting the errors from the data.

Something like this should do what you want:

library(forecast)
#> Registered S3 method overwritten by 'quantmod':
#>   method            from
#>   as.zoo.data.frame zoo
data.xts <- data.frame(
  t = seq(2000),
  RealizedVariance = ts(rnorm(2000))
)

far1 <- function(x, h){forecast(Arima(x, order=c(1,0,0), seasonal=FALSE), h=h)}
e <- tsCV(data.xts$RealizedVariance, far1, h=1)
fc <- c(NA, data.xts$RealizedVariance[2:2000] - e[1:1999])

Created on 2020-03-26 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.