How to forecast a VAR model and plot variables as a fanchart in Fable package (R)

243 Views Asked by At

I'm attempting to create VAR forecasts and plot both variables as fancharts using the fable package in R.

library(tidyverse)
library(tsibble)
library(fable)

# Create dataset (tsibble format)

data <- structure(list(date = structure(c(16436, 16526, 16617, 16709, 
16801, 16892, 16983, 17075, 17167, 17257, 17348, 17440, 17532, 
17622, 17713, 17805, 17897, 17987, 18078, 18170, 18262, 18353, 
18444), fiscal_start = 1, class = c("yearquarter", "vctrs_vctr"
)), GDP_NAM = c(-1.87308398729904, 2.290631067509, 0.993462708465565, 
-1.29041209029221, 1.12545485962681, -2.636526517961, 1.64791593479841, 
-0.127800586695059, -0.649131035554795, -1.41838122120497, -0.0727559182898574, 
2.61173864035165, 0.408195006166245, 2.14851460203356, -3.43206431417578, 
-3.21097438990066, -0.633222142832857, 3.62032490350241, -1.88466472673507, 
3.1882672460176, -6.25889275693812, -5.63387155573629, -2.47686181080518
), CPI_NAM = c(-0.00946230989793406, 1.15917422619178, 1.26429447879497, 
0.986332225049047, 2.41168238340004, 1.84115722165812, 1.41639006961984, 
1.35342674612451, 2.79543996486087, 0.605266622518563, 0.554959915380682, 
1.07421168196309, 1.2403520539725, 0.862800885835391, 1.26464488451186, 
1.75852063191533, 0.546966935763926, 0.534163056633208, 0.63109068920264, 
0.935286647736344, 0.159975810472712, 0.208743967794067, 0.973862299523898
)), row.names = c(NA, -23L), key = structure(list(.rows = structure(list(
    1:23), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", 
"list"))), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame")), index = structure("date", ordered = TRUE), index2 = "date", interval = structure(list(
    year = 0, quarter = 1, month = 0, week = 0, day = 0, hour = 0, 
    minute = 0, second = 0, millisecond = 0, microsecond = 0, 
    nanosecond = 0, unit = 0), .regular = TRUE, class = c("interval", 
"vctrs_rcrd", "vctrs_vctr")), class = c("tbl_ts", "tbl_df", "tbl", 
"data.frame"))

var_model <- data %>%
  model(VAR(vars(GDP_NAM, CPI_NAM) ~ AR(2)))

# Generate forecasts
fc <- var_model %>% forecast(h="1 year") 

# Plot fan chart
autoplot(
  fc, 
  data, 
  level=seq(10,90,by=10),
  color = 'red',
  show_gap = FALSE
) +
  theme(legend.position="none")

When I try to run the autoplot command, I get the following error

Error: Join columns must be present in data.
x Problem with `.response`.

Any idea how to fix this issue? TIA

0

There are 0 best solutions below