--- title: "Seasonal adjustment of high-frequency series" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Seasonal adjustment of high-frequency series} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} # The examples need Java and the rjd3highfreq package knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = rjd3jars::check_java_version(silent = TRUE) && requireNamespace("rjd3highfreq", quietly = TRUE) ) ``` ## Introduction Besides X-13ARIMA and TRAMO-SEATS (see `vignette("vignette", package = "fable.rjd3")`), `fable.rjd3` gives access to the decompositions of high-frequency series (daily, hourly, half-hourly...) of the [`rjd3highfreq`](https://rjdverse.github.io/rjd3highfreq/) package. These series usually have several periodicities, some of them non-integer (a year is 365.25 days on average), that the classical methods cannot handle. | Model | Method | Periodicities | Forecasts | |:------|:-------|:--------------|:----------| | `AIRLINE_DECOMPOSITION()` | Extended (fractional) airline model (`rjd3highfreq::multi_airline_decomposition()`) | one or several | yes | | `MSTL()` | Multiple STL (`rjd3highfreq::mstl()`) | one or several | no | | `ISTL()` | Iterative STL (`rjd3highfreq::istl()`) | one or several | no | | `STLPLUS()` | STL (`rjd3highfreq::stlplus()`) | one | no | | `X11PLUS()` | Extended X-11 (`rjd3highfreq::x11plus()`) | one | no | All of them can be combined with a **pre-adjustment** of the series (outliers, holidays and user-defined regressors) estimated with an extended airline model (`rjd3highfreq::fractional_airline_estimation()`): the decomposition is then done on the linearized series, and the effects removed by the pre-adjustment are put back in the components. `rjd3highfreq` must be installed (it is only suggested by `fable.rjd3`). ```{r load} library(fable.rjd3) library(dplyr) ``` ## Daily series We use the number of daily births in France (`rjd3toolkit::Births`), over the last four years. The series must be a `tsibble` without gaps. ```{r births} births <- as_tsibble(tail(rjd3toolkit::Births, 365 * 4), index = date) births ``` ### Periodicities The periodicities are deduced from the index: `c(7, 365.25)` for a daily series (weekly and annual periodicities), `k * c(1, 7)` for a series with `k` observations per day (daily and weekly periodicities: the annual periodicity, `k * 365.25`, must be added with `period()`). They can be set with the special `period()`. `STLPLUS()` and `X11PLUS()` handle only one periodicity: by default the smallest one is used. ```{r births-fit} mb <- model( births, airline = AIRLINE_DECOMPOSITION(births, log = TRUE), mstl = MSTL(births), x11 = X11PLUS(births ~ period(7)) ) mb ``` ### Decomposition `components()` returns a `dable` with one seasonal component per periodicity (`seasonal_week`, `seasonal_year`, or `seasonal` with a single periodicity). The decomposition is multiplicative with `log = TRUE` (for `AIRLINE_DECOMPOSITION()`) or `multiplicative = TRUE` (the default of the other models), additive otherwise. With `"auto"`, the choice is made with `rjd3highfreq::loglevel()`. ```{r births-components} dcmp <- components(mb) dcmp ``` ```{r births-plot, fig.width = 7, fig.height = 7} library(ggtime) dcmp |> filter(.model == "airline") |> ggplot2::autoplot() ``` ## Pre-adjustment The pre-adjustment is defined with specials of the formula: * `preadjust()`: outlier detection (`outliers = c("ao", "ls", "wo")` and `critical_value = 6` by default) and other options of `rjd3highfreq::fractional_airline_estimation()`; * `holidays(calendar)`: holidays regressors of a national calendar (`rjd3toolkit::national_calendar()`); * `xreg(..., regeffect = "Irregular")`: regressors taken from the columns of the tsibble (variables written directly in the formula are handled by `xreg()`). ```{r calendar} french_calendar <- rjd3toolkit::national_calendar(list( rjd3toolkit::special_day("NEWYEAR"), rjd3toolkit::special_day("EASTERMONDAY"), rjd3toolkit::special_day("MAYDAY"), rjd3toolkit::fixed_day(5, 8), rjd3toolkit::special_day("ASCENSION"), rjd3toolkit::special_day("WHITMONDAY"), rjd3toolkit::fixed_day(7, 14), rjd3toolkit::special_day("ASSUMPTION"), rjd3toolkit::special_day("ALLSAINTSDAY"), rjd3toolkit::special_day("ARMISTICE"), rjd3toolkit::special_day("CHRISTMAS") )) mb_pre <- model( births, airline = AIRLINE_DECOMPOSITION( births ~ preadjust(critical_value = 5) + holidays(french_calendar), log = TRUE ), mstl = MSTL(births ~ preadjust(critical_value = 5) + holidays(french_calendar)) ) ``` The effects removed by the pre-adjustment are allocated to the components following the JDemetra+ conventions: * level shifts (LS) are added to the trend; * additive outliers (AO) and switch outliers (WO) are added to the irregular; * the holidays are put in a separate `calendar` component, which is removed from the seasonally adjusted series; * user-defined regressors go to the component given by `regeffect` (`"Irregular"`, `"Trend"` or `"Calendar"`). ```{r pre-components} components(mb_pre) |> filter(.model == "airline") ``` The coefficients of the airline model and of the regressors are given by `tidy()`, and the dates of the outliers by `outliers()`. ```{r pre-tidy} tidy(mb_pre) |> filter(.model == "airline") outliers(mb_pre) report(select(mb_pre, airline)) ``` ### User-defined regressors ```{r xreg} births <- births |> mutate(lockdown = as.numeric(date >= as.Date("2021-01-01") & date <= as.Date("2021-01-31"))) mb_xreg <- model( births, airline = AIRLINE_DECOMPOSITION( births ~ holidays(french_calendar) + xreg(lockdown, regeffect = "Trend"), log = TRUE ) ) tidy(mb_xreg) ``` ## Forecasts `AIRLINE_DECOMPOSITION()` can forecast and backcast the series: the forecasts of the linearized series are combined with the regression effects (holidays, level shifts, and user-defined regressors whose future values are taken from `new_data`). `rjd3highfreq` does not provide the standard errors of the forecasts yet, so only point forecasts are returned (degenerate distributions). ```{r forecast} fc <- forecast(select(mb_pre, airline), h = 28) fc backcast(select(mb_pre, airline), h = 7) ``` ```{r forecast-xreg} future <- new_data(births, 28) |> mutate(lockdown = 0) forecast(mb_xreg, new_data = future) ``` ```{r forecast-plot, fig.width = 7, fig.height = 4} fc |> ggplot2::autoplot(tail(births, 120)) ``` The other models have no forecasting method. Their components can be forecasted separately with `fabletools::decomposition_model()`, which requires an additive decomposition (for a multiplicative one, decompose the log of the series): ```{r decomposition-model} fit <- model( births, dcmp = fabletools::decomposition_model( MSTL(log(births) ~ period(7), multiplicative = FALSE), fable::NAIVE(season_adjust) ) ) forecast(fit, h = 7) ``` Fitted values and residuals (`fitted()`, `residuals()`, `augment()`) come from the airline model: the pre-adjustment model, or the model of `AIRLINE_DECOMPOSITION()`. ## Infra-daily series `rjd3toolkit::Electricity` contains the half-hourly electricity consumption in France. Here we only use the last eight weeks. With infra-daily data, the default periodicities are the daily (48) and weekly (336) ones: the annual periodicity (17532) must be added explicitly with `period()`. It is rarely relevant on a few years of data (it is then estimated on very few cycles) and much longer to compute; an annual effect is usually better studied on the daily aggregated series. ```{r electricity} electricity <- rjd3toolkit::Electricity |> tail(48 * 7 * 8) |> transmute( time = as.POSIXct(paste(Date, Hours), tz = "UTC"), consumption = Consumtion ) |> as_tsibble(index = time) mb_elec <- model( electricity, airline = AIRLINE_DECOMPOSITION(consumption, log = TRUE), mstl = MSTL(consumption) ) components(mb_elec) ``` ```{r electricity-plot, fig.width = 7, fig.height = 6} components(mb_elec) |> filter(.model == "mstl") |> ggplot2::autoplot() ``` ## Limitations * The index must be a `Date` (daily or weekly series), a `POSIXct` (infra-daily series, with a constant interval: use a time zone without daylight saving time, such as UTC) or a `yearweek`; otherwise the periodicities must be given with `period()`. * Holidays are only available for daily and infra-daily series. * The forecasts are point forecasts, and are only available for `AIRLINE_DECOMPOSITION()`. * Backcasts are not available with user-defined regressors. * `MSTL()` and `ISTL()` use by default 15 robustness iterations (`nouterloop = 15`), whereas `forecast::mstl()` and `feasts::STL()` use none: with long series and long periodicities, `nouterloop = 1` divides the computation time by about seven (`nouterloop = 0` fails with `rjd3highfreq` 3.0.1). Even then, these functions are much slower than their `stats::stl()`-based counterparts when the annual periodicity of infra-daily data is used. * The computation time and the memory used by the Java routines grow quickly with the length of the series and of the periodicities; the Java heap size can be increased with `options(java.parameters = "-Xmx4g")` before loading the package.