Search code examples
for-looptime-seriesforecastingarimaforecast

Can I transform those seperate forcecasts into one for loop?


The data is in quarters and starts from 1955 till 2019, what I'm trying to do is obtaining the fixed horizon forecasts by increasing the sample period by one point incrementally, and repeating the estimation and forecasting process for this new sample period, and extract the year ahead (h=4) forecast. I want to forecast from the second quarter of 2017.

however I've tried using for loop but it just dosen't work, is it possible to condense this code into a for loop function

a <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2016,4), frequency = 4)
aa <- auto.arima(a)
aa
forecast(aa,h = 4)


b <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,1), frequency = 4)
bb <- auto.arima(a)
bb
forecast(bb,h = 4)


c <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,2), frequency = 4)
cc <- auto.arima(a)
cc
forecast(cc,h = 4)


d<- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,3), frequency = 4)
dd <- auto.arima(d)
dd
forecast(dd,h = 4)

e <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,4), frequency = 4)
ee <- auto.arima(e)
ee
forecast(ee,h = 4)

f <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2018,1), frequency = 4)
ff <- auto.arima(f)
ff
forecast(ff,h = 4)

g <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2018,2), frequency = 4)
gg <- auto.arima(g)
gg
forecast(gg,h = 4)

h <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2018,3), frequency = 4)
hh <- auto.arima(h)
hh
forecast(hh,h = 4)

Solution

  • library(forecast)
    ukgdp <- ts(data$UK.GDP.UA.MP, start=1955, frequency=4)
    
    fc <- matrix(NA, ncol=4, nrow=8) %>% ts(start=c(2016,4), frequency=4)
    colnames(fc) <- paste("h =",1:4)
    
    for(i in seq(8)) {
      ukgdp_train <- window(ukgdp, end = c(2016, 3+i))
      fit <- auto.arima(ukgdp_train)
      fc[i,] <- forecast(fit, h=4)$mean
    }
    

    Created on 2019-12-06 by the reprex package (v0.3.0)