Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

forecast.VAR takes sqrt of potentially negative covariance #391

Open
FinYang opened this issue Apr 12, 2023 · 0 comments
Open

forecast.VAR takes sqrt of potentially negative covariance #391

FinYang opened this issue Apr 12, 2023 · 0 comments

Comments

@FinYang
Copy link

FinYang commented Apr 12, 2023

Currently, forecast.VAR calculates sqrt of the covariance matrix:

fable/R/var.R

Line 244 in 9b926f8

sigma <- map(sigma, sqrt)

and then recovers the covariance matrix before constructing the distribution at the end:

fable/R/var.R

Line 266 in 9b926f8

unname(distributional::dist_multivariate_normal(split(fc, row(fc)), map(sigma, `^`, 2)))

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant