Search code examples
rtime-seriesforecasting

Remove season and trend from multivariate tsibble


I am using the stl() function to remove season and trend from a multivariate timeseries. I then want to keep to remainder term from the stl decomposition in order to perform an ARIMA() analysis on the residuals.

I am trying to code this in a tidy way as I will be expanding to a large number of time series. Here I give an example with 3 series. My problem is that I cannot apply stl to the df unless I filter to a specific univariate time-series.

library(fable)
#> Loading required package: fabletools
library(tidyverse)
library(feasts)

df <- tibble(
  X = rnorm(71), Y = rnorm(71), Z = rnorm(71),
  quarter = seq(as.Date("2001/4/1"),
    as.Date("2018/10/1"),
    by = "quarter"
  )
) %>%
  mutate(quarter = tsibble::yearquarter(quarter)) %>%
  gather(-quarter, key = "Series", value = "value") %>%
  as_tsibble(index = quarter, key = Series)

# Detrend into seasonal, trend and remainder components

# Applying stl to a univariate series using filter works fine

df_stl <- df %>%
  filter(Series == "Z") %>%
  stl(s.window = "per", t.window = 1000)

df_stl <- df_stl[["time.series"]][,'remainder'] %>%
  as_tsibble()

# Applying stl to a multivariate series fails
df %>%
  stl(s.window = "per", t.window = 1000)
#> Error in stl(., s.window = "per", t.window = 1000): only univariate series are allowed

Created on 2019-11-14 by the reprex package (v0.3.0)


Solution

  • Use the STL() function in the feasts package:

    df_stl <- df %>%
      STL(value ~ season("periodic") + trend(window=1000))