Skip to content

Instantly share code, notes, and snippets.

@brshallo
Last active July 21, 2019 23:25
Show Gist options
  • Select an option

  • Save brshallo/f94085d5120f8034c82b51dde03018fe to your computer and use it in GitHub Desktop.

Select an option

Save brshallo/f94085d5120f8034c82b51dde03018fe to your computer and use it in GitHub Desktop.
Inadequate method for producing simulations off of `stlm` objects

General approach to pseudo simulation:
Take bootstrap sample --> build model --> refit model to original data --> forecast refitted model though use simulate() on ets/trend component of forecast.

library(tidyverse)
library(forecast)

# Function takes bootstrapped sample --> fits model --> refits model to original `y`
boot_mod_refit <- function(ts, fun = stlm, ...){
  bld.mbb.bootstrap(ts, 2)[[2]] %>% 
    fun() %>% 
    fun(ts, model = ., ...)
}

# loads function that is hack to produce a forecast of `stlm` with a simulated trend component
devtools::source_gist("https://gist.github.com/brshallo/4b93d0cf48937da6de06ffcffaed2b57")
#> Sourcing https://gist.githubusercontent.com/brshallo/4b93d0cf48937da6de06ffcffaed2b57/raw/21d25c7257be848a546a414834972d28d92f76ab/simulate_stlm_trend.R
#> SHA-1 hash of file is 40bc84793eb7040d45e5aefadf50eda5b2386d1a

# random data (should test with more representative time series data)
set.seed(1234)
ts_test <- ts(rnorm(9, 0, 3),
              start = c(2012, 1),
              frequency = 3)



boot_mod_refit(ts_test, stlm) %>% 
  simulate_stlm(3)
#> Time Series:
#> Start = c(2015, 1) 
#> End = c(2015, 3) 
#> Frequency = 3 
#> [1] -3.575151 -3.054692 -1.084186

Created on 2019-07-21 by the reprex package (v0.3.0)

Bootstrap of mean of forecast:
I presume one approach could be to bootstrap the data and then build model(s) from these bootstrapped samples? E.g. something like...

library(tidyverse)

set.seed(1234)
forecast::bld.mbb.bootstrap(ts_test, 2) %>% 
  .[[2]] %>% 
  stlm() %>% 
  forecast(3) %>%
  .[["mean"]]
#> Time Series:
#> Start = c(2015, 1) 
#> End = c(2015, 3) 
#> Frequency = 3 
#> [1] -4.7883518  0.4184315  0.8529832

However this procedure produces a simulation of the mean forecast rather than an individual prediction (i.e. the distribution of outputs of repeating this procedure would produce something analagous to confidence intervals rather than prediction intervals.) To build prediction intervals from bootstrapped samples requires using simulate(), see fpp2).

@brshallo
Copy link
Copy Markdown
Author

brshallo commented Jul 21, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment