backshift 0.3.0

Time-series forecasting checked against R and statsmodels: ARIMA, ETS, Theta, VAR, Croston/TSB, GARCH and changepoint detection, with streaming filters that run without a heap
Documentation
# Generate R reference vectors for the exponential smoothing (ETS) conformance tests.
#
# Writes `tests/it/r_ets_data.rs`. R's packages are pinned by the Docker image in `scripts/r/`;
# run from the repository root:
#
#     docker build -t backshift-r-reference scripts/r
#     docker run --rm -v "$PWD":/work backshift-r-reference Rscript scripts/generate_r_ets_reference.R
#
# The series are simulated here with fixed seeds and stored in the output, so the tests do
# not depend on R's random number generator.

suppressPackageStartupMessages(library(forecast))

out <- "tests/it/r_ets_data.rs"

source("scripts/r/rust_literals.R")

lines <- c(
  "//! R reference vectors for the ETS conformance tests.",
  "//!",
  sprintf("//! Generated by `scripts/generate_r_ets_reference.R` with %s and forecast %s.",
          R.version.string, as.character(packageVersion("forecast"))),
  "//! Do not edit by hand; rerun the script instead.",
  ""
)
emit <- function(...) lines <<- c(lines, ...)

emit(
  "/// An `ets(values, model, damped)` fit and its `forecast(fit, h, level = c(80, 95))`.",
  "pub struct EtsCase {",
  "    /// The series.",
  "    pub values: &'static [f64],",
  "    /// The season length; 1 for a non-seasonal series.",
  "    pub period: usize,",
  "    /// R's model string, for example `\"AAdA\"`: error, trend, `d` if damped, season.",
  "    pub model: &'static str,",
  "    /// The fitted `alpha`, `beta`, `gamma`, `phi` (`NaN` where the model has none).",
  "    pub parameters: [f64; 4],",
  "    /// The fitted initial states: level, slope (if any), then all `m` seasonal states.",
  "    pub initial_states: &'static [f64],",
  "    /// The states after the last value, in the same layout.",
  "    pub final_states: &'static [f64],",
  "    /// The one-step residuals: `y - forecast` for additive errors, `(y - forecast) / forecast`",
  "    /// for multiplicative ones.",
  "    pub residuals: &'static [f64],",
  "    /// R's log-likelihood, `-0.5 * lik`, with its constants dropped.",
  "    pub loglik: f64,",
  "    /// R's AIC, AICc and BIC.",
  "    pub criteria: [f64; 3],",
  "    /// R's innovation variance, the residual sum of squares over `n - np`.",
  "    pub sigma2: f64,",
  "    /// The forecast means.",
  "    pub mean: &'static [f64],",
  "    /// The 80% and 95% interval bounds: lower 80, upper 80, lower 95, upper 95, per horizon.",
  "    pub intervals: &'static [[f64; 4]],",
  "}",
  ""
)

# A series of `n` values: a level, a slope, a seasonal pattern and noise, all optional.
simulate <- function(n, m, seed, slope = 0, amplitude = 0, noise = 1, walk = 0.3) {
  set.seed(seed)
  t <- 1:n
  level <- 50 + cumsum(rnorm(n, sd = walk))
  pattern <- if (m > 1) amplitude * sin(2 * pi * ((t - 1) %% m) / m + 0.7) else 0
  level + slope * t + pattern + rnorm(n, sd = noise)
}

# A positive series whose noise and season scale with its level, for multiplicative models.
simulate_multiplicative <- function(n, m, seed, slope = 0, amplitude = 0, noise = 0.03) {
  set.seed(seed)
  t <- 1:n
  level <- 100 * exp(cumsum(rnorm(n, sd = 0.01))) + slope * t
  pattern <- if (m > 1) 1 + amplitude * sin(2 * pi * ((t - 1) %% m) / m + 0.4) else 1
  level * pattern * exp(rnorm(n, sd = noise))
}

cases <- list(
  list(name = "ANN", m = 1, model = "ANN", damped = FALSE, values = simulate(80, 1, 11)),
  list(name = "AAN", m = 1, model = "AAN", damped = FALSE, values = simulate(90, 1, 12, slope = 0.4)),
  list(name = "AADN", m = 1, model = "AAN", damped = TRUE, values = simulate(90, 1, 13, slope = 0.3)),
  list(name = "ANA", m = 4, model = "ANA", damped = FALSE, values = simulate(64, 4, 14, amplitude = 4)),
  list(name = "AAA", m = 12, model = "AAA", damped = FALSE,
       values = simulate(120, 12, 15, slope = 0.2, amplitude = 6)),
  list(name = "AADA", m = 12, model = "AAA", damped = TRUE,
       values = simulate(120, 12, 16, slope = 0.2, amplitude = 6)),
  list(name = "MNN", m = 1, model = "MNN", damped = FALSE, values = simulate_multiplicative(80, 1, 21)),
  list(name = "MAN", m = 1, model = "MAN", damped = FALSE,
       values = simulate_multiplicative(90, 1, 22, slope = 0.5)),
  list(name = "MADN", m = 1, model = "MAN", damped = TRUE,
       values = simulate_multiplicative(90, 1, 23, slope = 0.4)),
  list(name = "MNA", m = 4, model = "MNA", damped = FALSE,
       values = simulate_multiplicative(64, 4, 24, amplitude = 0.1)),
  list(name = "MAA", m = 12, model = "MAA", damped = FALSE,
       values = simulate_multiplicative(120, 12, 25, slope = 0.3, amplitude = 0.1)),
  list(name = "MADA", m = 12, model = "MAA", damped = TRUE,
       values = simulate_multiplicative(120, 12, 26, slope = 0.3, amplitude = 0.1)),
  list(name = "MNM", m = 4, model = "MNM", damped = FALSE,
       values = simulate_multiplicative(64, 4, 27, amplitude = 0.15)),
  list(name = "MAM", m = 12, model = "MAM", damped = FALSE,
       values = simulate_multiplicative(120, 12, 28, slope = 0.3, amplitude = 0.15)),
  list(name = "MADM", m = 12, model = "MAM", damped = TRUE,
       values = simulate_multiplicative(120, 12, 29, slope = 0.3, amplitude = 0.15))
)

for (case in cases) {
  y <- ts(case$values, frequency = case$m)
  trend <- substr(case$model, 2, 2)
  season <- substr(case$model, 3, 3)
  fit <- ets(y, model = case$model, damped = case$damped)
  h <- if (case$m > 1) 2 * case$m else 10
  fc <- forecast(fit, h = h, level = c(80, 95))
  par <- fit$par
  parameters <- c(
    if ("alpha" %in% names(par)) par[["alpha"]] else NA,
    if ("beta" %in% names(par)) par[["beta"]] else NA,
    if ("gamma" %in% names(par)) par[["gamma"]] else NA,
    if ("phi" %in% names(par)) par[["phi"]] else NA
  )
  states <- fit$states
  intervals <- vapply(1:h, function(i) {
    sprintf("[%s, %s, %s, %s]", rust_float(fc$lower[i, 1]), rust_float(fc$upper[i, 1]),
            rust_float(fc$lower[i, 2]), rust_float(fc$upper[i, 2]))
  }, "")
  emit(
    sprintf("/// `ets(values, model = \"%s\", damped = %s)` on %d values with period %d.",
            case$model, case$damped, length(case$values), case$m),
    sprintf("pub const %s: EtsCase = EtsCase {", case$name),
    sprintf("    values: %s,", rust_array(case$values)),
    sprintf("    period: %d,", case$m),
    sprintf("    model: \"%s\",", sub("\\(|\\)|,", "", gsub("ETS\\(|\\)|,", "", fit$method))),
    sprintf("    parameters: [%s],", paste(vapply(parameters, rust_float, ""), collapse = ", ")),
    sprintf("    initial_states: %s,", rust_array(states[1, ])),
    sprintf("    final_states: %s,", rust_array(states[nrow(states), ])),
    sprintf("    residuals: %s,", rust_array(fit$residuals)),
    sprintf("    loglik: %s,", rust_float(fit$loglik)),
    sprintf("    criteria: [%s, %s, %s],", rust_float(fit$aic), rust_float(fit$aicc), rust_float(fit$bic)),
    sprintf("    sigma2: %s,", rust_float(fit$sigma2)),
    sprintf("    mean: %s,", rust_array(fc$mean)),
    sprintf("    intervals: &[%s],", paste(intervals, collapse = ", ")),
    "};",
    ""
  )
}
emit(sprintf("/// All ETS reference cases.\npub const ALL: &[&EtsCase] = &[%s];",
             paste0("&", vapply(cases, function(c) c$name, ""), collapse = ", ")))

# The automatic search over the additive models, as `ets(values, additive.only = TRUE)`.
emit(
  "",
  "/// The model `ets(values, additive.only = TRUE)` selects by AICc for each case of [`ALL`],",
  "/// as R prints it, for example `\"AAdA\"`.",
  sprintf("pub const AUTO_ADDITIVE: &[&str] = &[%s];", paste(vapply(cases, function(case) {
    fit <- ets(ts(case$values, frequency = case$m), additive.only = TRUE)
    sprintf("\"%s\"", gsub("ETS\\(|\\)|,", "", fit$method))
  }, ""), collapse = ", "))
)

# The automatic search over R's default model set, as `ets(values)`, for each case.
emit(
  "",
  "/// The model `ets(values)` selects by AICc for each case of [`ALL`] (R's default set:",
  "/// additive and multiplicative errors and seasons, no multiplicative trend).",
  sprintf("pub const AUTO_DEFAULT: &[&str] = &[%s];", paste(vapply(cases, function(case) {
    fit <- ets(ts(case$values, frequency = case$m))
    sprintf("\"%s\"", gsub("ETS\\(|\\)|,", "", fit$method))
  }, ""), collapse = ", "))
)

writeLines(lines, out)