fable icon indicating copy to clipboard operation
fable copied to clipboard

`forecast.VAR` takes sqrt of potentially negative covariance

Open FinYang opened this issue 2 years ago • 0 comments

Currently, forecast.VAR calculates sqrt of the covariance matrix: https://github.com/tidyverts/fable/blob/9b926f8be993594c3ae448b912366aca09ab78d7/R/var.R#L244 and then recovers the covariance matrix before constructing the distribution at the end: https://github.com/tidyverts/fable/blob/9b926f8be993594c3ae448b912366aca09ab78d7/R/var.R#L266

This produces NaN when the covariance between variables is negative. For example:

library(tidyverse)
library(fable)
#> Loading required package: fabletools
lung_deaths <- cbind(mdeaths, fdeaths) %>%
  as_tsibble(pivot_longer = FALSE)

fit <- lung_deaths %>%
  mutate(fdeaths = -fdeaths) %>% 
  model(VAR(vars(mdeaths, fdeaths) ~ AR(3)))

fc <- forecast(fit, h=1)
#> Warning: There was 1 warning in `mutate()`.
#> ℹ In argument: `VAR(vars(mdeaths, fdeaths) ~ AR(3)) = (function (object, ...)
#>   ...`.
#> Caused by warning in `FUN()`:
#> ! NaNs produced
distributional::covariance(pull(fc, .distribution))
#> [[1]]
#>          mdeaths fdeaths
#> mdeaths 58985.95     NaN
#> fdeaths      NaN 9983.95

Created on 2023-04-12 with reprex v2.0.2

FinYang avatar Apr 12 '23 12:04 FinYang