Create a Rolling forecast for a VAR model.

I´m trying to do a loop for forecasting a VAR model based on two times series where I want to do a rolling forecast for the last 30 observations for my data. I only want to save my forecast for my "main" variable. My data for all the variables is "mjolk_ts" and "djurfoder_ts" and the data minus the last 30 observations is "mjolk_ts_train" and "djurfoder_ts_train", the train have I created. I have tried with this code below but I get error. can someone helt me?

rf_var2 <- function(
data = (cbind(mjolk_ts_train, djurfoder_ts_train)),
first_pred = 2021 + 5/12,
last_pred = 2023 + 10/12,
n.ahead = 1
) {

end <- first_pred - 1/12
preds <- list()
i <- 1

while (end < (last_pred - 0.01)) {
train <- window(data, end = end)
model <- VAR(cbind(mjolk_ts_train, djurfoder_ts_train), lag.max = 5, ic = "AIC", type = "both")
forecast <- predict(model, n.ahead = n.ahead)

if (length(forecast) >= n.ahead) {
  preds[[i]] <- forecast[n.ahead]
}
end <- end + 1/12
i <- i + 1

}

all_preds <- ts(
unlist(preds),
start = c(as.integer(first_pred), (first_pred * 12) %% 12),
frequency = frequency(data)
)

return(all_preds)
}

rf_var33 <- rf_var2(mjolk_ts)

plot(mjolk_ts, main = "Historiska data och Prognoser")
lines(rf_var33, col = "red", lty = 2)
legend("topleft", legend = c("Historisk data", "Prognos"), col = c("black", "red"), lty = 1:2)

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.