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 Theta method conformance tests.
#
# Writes `tests/it/r_theta_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_theta_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_theta_data.rs"

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

lines <- c(
  "//! R reference vectors for the Theta method conformance tests.",
  "//!",
  sprintf("//! Generated by `scripts/generate_r_theta_reference.R` with %s and forecast %s.",
          R.version.string, as.character(packageVersion("forecast"))),
  "//! Do not edit by hand; rerun the script instead.",
  "",
  "/// A `thetaf(values, h, level = c(80, 95))` forecast.",
  "pub struct ThetaCase {",
  "    /// The series.",
  "    pub values: &'static [f64],",
  "    /// The season length; 1 for a non-seasonal series.",
  "    pub period: usize,",
  "    /// Whether R's seasonality test passed and the series was deseasonalised.",
  "    pub seasonal: bool,",
  "    /// The smoothing parameter of the simple exponential smoothing.",
  "    pub alpha: f64,",
  "    /// The drift, half the least-squares slope of the (deseasonalised) series.",
  "    pub drift: f64,",
  "    /// The innovation variance of the simple exponential smoothing.",
  "    pub sigma2: f64,",
  "    /// The level of the simple exponential smoothing after the last value.",
  "    pub level: f64,",
  "    /// The seasonal indices of the next `period` values, next first; empty unless seasonal.",
  "    pub factors: &'static [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]],",
  "}",
  ""
)
emit <- function(...) lines <<- c(lines, ...)

simulate <- function(n, m, seed, slope, amplitude) {
  set.seed(seed)
  t <- 1:n
  level <- 100 + cumsum(rnorm(n, sd = 0.8)) + slope * t
  pattern <- if (m > 1) 1 + amplitude * sin(2 * pi * ((t - 1) %% m) / m + 0.3) else 1
  level * pattern + rnorm(n, sd = 1)
}

cases <- list(
  list(name = "NONSEASONAL", m = 1, values = simulate(80, 1, 41, 0.3, 0)),
  list(name = "MONTHLY", m = 12, values = simulate(120, 12, 42, 0.2, 0.15)),
  list(name = "QUARTERLY_WEAK", m = 4, values = simulate(40, 4, 43, 0.1, 0.002))
)

for (case in cases) {
  y <- ts(case$values, frequency = case$m)
  h <- if (case$m > 1) 2 * case$m else 10
  fc <- thetaf(y, h = h, level = c(80, 95))
  # thetaf's seasonality test, repeated to report its outcome.
  n <- length(y)
  r <- if (case$m > 1) as.numeric(acf(y, lag.max = case$m, plot = FALSE)$acf)[-1] else 0
  seasonal <- case$m > 1 && !is.constant(y) && n > 2 * case$m &&
    abs(r[case$m]) / sqrt((1 + 2 * sum(r[-case$m]^2)) / n) > qnorm(0.95)
  # thetaf's own steps, to export the level and indices it forecasts from.
  x <- y
  factors <- numeric(0)
  if (seasonal) {
    decomp <- decompose(y, type = "multiplicative")
    x <- seasadj(decomp)
    factors <- tail(decomp$seasonal, case$m)
  }
  level <- tail(ses(x, h = h)$model$states[, "l"], 1)
  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("/// `thetaf(values, h = %d)` on %d values with period %d.", h, n, case$m),
    sprintf("pub const %s: ThetaCase = ThetaCase {", case$name),
    sprintf("    values: %s,", rust_array(case$values)),
    sprintf("    period: %d,", case$m),
    sprintf("    seasonal: %s,", tolower(seasonal)),
    sprintf("    alpha: %s,", rust_float(fc$model$alpha)),
    sprintf("    drift: %s,", rust_float(fc$model$drift)),
    sprintf("    sigma2: %s,", rust_float(fc$model$sigma)),
    sprintf("    level: %s,", rust_float(level)),
    sprintf("    factors: %s,", rust_array(factors)),
    sprintf("    mean: %s,", rust_array(fc$mean)),
    sprintf("    intervals: &[%s],", paste(intervals, collapse = ", ")),
    "};",
    ""
  )
}
emit(sprintf("/// All Theta reference cases.\npub const ALL: &[&ThetaCase] = &[%s];",
             paste0("&", vapply(cases, function(c) c$name, ""), collapse = ", ")))

writeLines(lines, out)