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 conformance tests.
#
# Writes `tests/it/r_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_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_data.rs"

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

lines <- c(
  "//! R reference vectors for the conformance tests.",
  "//!",
  sprintf("//! Generated by `scripts/generate_r_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, ...)

# ARIMA fits by exact maximum likelihood, and forecasts at the fitted coefficients.
emit(
  "/// A `stats::arima(values, order, seasonal, include.mean, method = \"ML\")` fit and its",
  "/// `predict(fit, n.ahead = 5)` forecasts.",
  "pub struct ArimaCase {",
  "    /// The series.",
  "    pub values: &'static [f64],",
  "    /// `(p, d, q)`.",
  "    pub order: [usize; 3],",
  "    /// `(P, D, Q)`.",
  "    pub seasonal: [usize; 3],",
  "    /// The season length; 0 without a seasonal part.",
  "    pub period: usize,",
  "    /// `include.mean`.",
  "    pub include_mean: bool,",
  "    /// The fitted AR coefficients.",
  "    pub ar: &'static [f64],",
  "    /// The fitted MA coefficients.",
  "    pub ma: &'static [f64],",
  "    /// The fitted seasonal AR coefficients.",
  "    pub seasonal_ar: &'static [f64],",
  "    /// The fitted seasonal MA coefficients.",
  "    pub seasonal_ma: &'static [f64],",
  "    /// The fitted mean (`intercept`); 0 without one.",
  "    pub mean: f64,",
  "    /// `fit$sigma2`.",
  "    pub sigma2: f64,",
  "    /// `fit$loglik`.",
  "    pub loglike: f64,",
  "    /// `predict(fit, 5)$pred`.",
  "    pub forecast_mean: &'static [f64],",
  "    /// `predict(fit, 5)$se`.",
  "    pub forecast_se: &'static [f64],",
  "}",
  ""
)

simulate <- function(n, ar = numeric(), ma = numeric(), d = 0, seasonal = NULL, mean = 0, seed) {
  set.seed(seed)
  model <- list(ar = ar, ma = ma)
  if (!is.null(seasonal)) {
    # Expand the seasonal polynomials into the non-seasonal ones.
    s <- seasonal$period
    sar <- c(1, rep(0, s * length(seasonal$ar)))
    for (i in seq_along(seasonal$ar)) sar[i * s + 1] <- -seasonal$ar[i]
    sma <- c(1, rep(0, s * length(seasonal$ma)))
    for (i in seq_along(seasonal$ma)) sma[i * s + 1] <- seasonal$ma[i]
    full_ar <- -convolve(c(1, -ar), rev(sar), type = "open")[-1]
    full_ma <- convolve(c(1, ma), rev(sma), type = "open")[-1]
    model <- list(ar = full_ar, ma = full_ma)
  }
  x <- as.numeric(arima.sim(model, n = n, n.start = 200)) + mean
  if (d > 0) for (i in seq_len(d)) x <- cumsum(c(10, x))[seq_len(n)]
  x
}

arima_cases <- list(
  list(name = "ARMA11", doc = "ARMA(1, 1) with a mean.", order = c(1, 0, 1), mean = TRUE,
       values = simulate(150, ar = 0.6, ma = 0.3, mean = 2, seed = 101)),
  list(name = "AR2", doc = "AR(2) with a mean.", order = c(2, 0, 0), mean = TRUE,
       values = simulate(200, ar = c(0.5, -0.3), mean = -1, seed = 102)),
  list(name = "MA2", doc = "MA(2) without a mean.", order = c(0, 0, 2), mean = FALSE,
       values = simulate(150, ma = c(0.4, -0.3), seed = 103)),
  list(name = "I1", doc = "ARIMA(1, 1, 1).", order = c(1, 1, 1), mean = FALSE,
       values = simulate(150, ar = 0.5, ma = -0.3, d = 1, seed = 104)),
  list(name = "I2", doc = "ARIMA(0, 2, 1).", order = c(0, 2, 1), mean = FALSE,
       values = simulate(150, ma = -0.5, d = 2, seed = 105)),
  list(name = "AIRLINE", doc = "The airline model ARIMA(0, 1, 1)(0, 1, 1, 12).",
       order = c(0, 1, 1), seasonal = c(0, 1, 1), period = 12, mean = FALSE,
       values = {
         w <- simulate(168, ma = -0.4, seasonal = list(ma = -0.6, period = 12), seed = 106)
         x <- w
         for (t in 13:length(x)) x[t] <- x[t - 12] + w[t]
         cumsum(x)
       }),
  list(name = "SAR4", doc = "ARIMA(1, 0, 0)(1, 0, 0, 4) with a mean.",
       order = c(1, 0, 0), seasonal = c(1, 0, 0), period = 4, mean = TRUE,
       values = simulate(160, ar = 0.4, seasonal = list(ar = 0.5, period = 4), mean = 3, seed = 107))
)

coef_part <- function(fit, prefix, count) {
  if (count == 0) return(numeric())
  as.numeric(fit$coef[paste0(prefix, seq_len(count))])
}

for (case in arima_cases) {
  seasonal <- if (is.null(case$seasonal)) c(0, 0, 0) else case$seasonal
  period <- if (is.null(case$period)) 0 else case$period
  fit <- arima(case$values, order = case$order,
               seasonal = list(order = seasonal, period = if (period > 0) period else NA),
               include.mean = case$mean, method = "ML",
               optim.control = list(maxit = 1000, reltol = 1e-12))
  pred <- predict(fit, n.ahead = 5)
  emit(
    sprintf("/// %s", case$doc),
    sprintf("pub const %s: ArimaCase = ArimaCase {", case$name),
    sprintf("    values: %s,", rust_array(case$values)),
    sprintf("    order: [%s],", paste(case$order, collapse = ", ")),
    sprintf("    seasonal: [%s],", paste(seasonal, collapse = ", ")),
    sprintf("    period: %d,", period),
    sprintf("    include_mean: %s,", tolower(case$mean)),
    sprintf("    ar: %s,", rust_array(coef_part(fit, "ar", case$order[1]))),
    sprintf("    ma: %s,", rust_array(coef_part(fit, "ma", case$order[3]))),
    sprintf("    seasonal_ar: %s,", rust_array(coef_part(fit, "sar", seasonal[1]))),
    sprintf("    seasonal_ma: %s,", rust_array(coef_part(fit, "sma", seasonal[3]))),
    sprintf("    mean: %s,", rust_float(if (case$mean) fit$coef[["intercept"]] else 0)),
    sprintf("    sigma2: %s,", rust_float(fit$sigma2)),
    sprintf("    loglike: %s,", rust_float(fit$loglik)),
    sprintf("    forecast_mean: %s,", rust_array(pred$pred)),
    sprintf("    forecast_se: %s,", rust_array(pred$se)),
    "};",
    ""
  )
}
emit(sprintf("/// All ARIMA reference cases.\npub const ARIMA: &[&ArimaCase] = &[%s];\n",
             paste0("&", vapply(arima_cases, function(c) c$name, ""), collapse = ", ")))

# A fit with a fixed part: arima(fixed =) needs transform.pars = FALSE.
fixed_values <- arima_cases[[1]]$values
fixed_fit <- arima(fixed_values, order = c(1, 0, 1), include.mean = TRUE, method = "ML",
                   fixed = c(0.5, NA, NA), transform.pars = FALSE,
                   optim.control = list(maxit = 1000, reltol = 1e-12))
emit(
  "/// `arima(ARMA11.values, order = c(1, 0, 1), fixed = c(0.5, NA, NA), method = \"ML\")`:",
  "/// the AR coefficient fixed at 0.5.",
  "pub const FIXED_AR: ArimaCase = ArimaCase {",
  "    values: ARMA11.values,",
  "    order: [1, 0, 1],",
  "    seasonal: [0, 0, 0],",
  "    period: 0,",
  "    include_mean: true,",
  "    ar: &[0.5],",
  sprintf("    ma: %s,", rust_array(fixed_fit$coef[["ma1"]])),
  "    seasonal_ar: &[],",
  "    seasonal_ma: &[],",
  sprintf("    mean: %s,", rust_float(fixed_fit$coef[["intercept"]])),
  sprintf("    sigma2: %s,", rust_float(fixed_fit$sigma2)),
  sprintf("    loglike: %s,", rust_float(fixed_fit$loglik)),
  sprintf("    forecast_mean: %s,", rust_array(predict(fixed_fit, 5)$pred)),
  sprintf("    forecast_se: %s,", rust_array(predict(fixed_fit, 5)$se)),
  "};",
  sprintf("/// `fixed_fit$aic`, which counts only the estimated parameters.\npub const FIXED_AR_AIC: f64 = %s;", rust_float(fixed_fit$aic)),
  ""
)

# Diagnostics: acf, pacf and Box.test.
set.seed(201)
diagnostic <- as.numeric(arima.sim(list(ar = c(0.5, -0.2)), n = 120))
acf_values <- acf(diagnostic, lag.max = 10, plot = FALSE)$acf[-1]
pacf_values <- pacf(diagnostic, lag.max = 10, plot = FALSE)$acf
box <- Box.test(diagnostic, lag = 10, type = "Ljung-Box", fitdf = 2)
emit(
  "/// A simulated AR(2) series for `acf`, `pacf` and `Box.test`.",
  sprintf("pub const DIAGNOSTIC: &[f64] = %s;", rust_array(diagnostic)),
  "/// `acf(DIAGNOSTIC, lag.max = 10)$acf`, lags 1 to 10.",
  sprintf("pub const ACF: &[f64] = %s;", rust_array(acf_values)),
  "/// `pacf(DIAGNOSTIC, lag.max = 10)$acf`, lags 1 to 10.",
  sprintf("pub const PACF: &[f64] = %s;", rust_array(pacf_values)),
  "/// `Box.test(DIAGNOSTIC, lag = 10, type = \"Ljung-Box\", fitdf = 2)`: statistic and p-value.",
  sprintf("pub const LJUNG_BOX: [f64; 2] = [%s, %s];", rust_float(box$statistic), rust_float(box$p.value)),
  ""
)

# Fourier regressors, in-sample from t = 1 and for the horizon after the series.
fourier_series <- msts(seq_len(40), seasonal.periods = c(7, 30.5))
in_sample <- fourier(fourier_series, K = c(2, 3))
horizon <- fourier(fourier_series, K = c(2, 3), h = 5)
monthly <- fourier(ts(seq_len(24), frequency = 12), K = 6)
emit(
  "/// `fourier(msts(1:40, seasonal.periods = c(7, 30.5)), K = c(2, 3))`, row-major, rows",
  "/// for t = 1 to 40.",
  sprintf("pub const FOURIER_IN_SAMPLE: &[f64] = %s;", rust_array(t(in_sample))),
  "/// The same with `h = 5`: rows for t = 41 to 45.",
  sprintf("pub const FOURIER_HORIZON: &[f64] = %s;", rust_array(t(horizon))),
  "/// `fourier(ts(1:24, frequency = 12), K = 6)`, row-major: the Nyquist sine is dropped.",
  sprintf("pub const FOURIER_MONTHLY: &[f64] = %s;", rust_array(t(monthly))),
  ""
)

# Differencing tests and the automatic search.
auto_cases <- list(
  list(name = "AUTO_AR1", doc = "An AR(1) with a mean.", period = 1,
       values = simulate(200, ar = 0.7, mean = 5, seed = 301)),
  list(name = "AUTO_RANDOM_WALK", doc = "A random walk with drift.", period = 1,
       values = cumsum(simulate(200, mean = 0.3, seed = 302))),
  list(name = "AUTO_I1_MA", doc = "An ARIMA(0, 1, 1).", period = 1,
       values = simulate(200, ma = -0.5, d = 1, seed = 303)),
  list(name = "AUTO_AIRLINE", doc = "The airline series above.", period = 12,
       values = arima_cases[[6]]$values),
  list(name = "AUTO_SEASONAL_AR", doc = "The seasonal AR series above.", period = 4,
       values = arima_cases[[7]]$values)
)
emit(
  "/// A series with R's differencing tests and `auto.arima` choice.",
  "pub struct AutoCase {",
  "    /// The series.",
  "    pub values: &'static [f64],",
  "    /// The season length; 1 for none.",
  "    pub period: usize,",
  "    /// `ndiffs(values)`: KPSS at the 5% level.",
  "    pub ndiffs: usize,",
  "    /// `nsdiffs(ts(values, frequency = period))`: seasonal strength; 0 without a season.",
  "    pub nsdiffs: usize,",
  "    /// `auto.arima(..., approximation = FALSE)`'s `(p, d, q, P, D, Q)`.",
  "    pub orders: [usize; 6],",
  "    /// Whether it kept a mean or drift.",
  "    pub constant: bool,",
  "}",
  ""
)
for (case in auto_cases) {
  x <- ts(case$values, frequency = case$period)
  nsd <- if (case$period > 1) nsdiffs(x) else 0
  fit <- auto.arima(x, approximation = FALSE, stepwise = TRUE)
  arma <- fit$arma  # p, q, P, Q, period, d, D
  constant <- any(c("intercept", "drift") %in% names(fit$coef))
  emit(
    sprintf("/// %s", case$doc),
    sprintf("pub const %s: AutoCase = AutoCase {", case$name),
    sprintf("    values: %s,", rust_array(case$values)),
    sprintf("    period: %d,", case$period),
    sprintf("    ndiffs: %d,", ndiffs(case$values)),
    sprintf("    nsdiffs: %d,", nsd),
    sprintf("    orders: [%s],", paste(arma[c(1, 6, 2, 3, 7, 4)], collapse = ", ")),
    sprintf("    constant: %s,", tolower(constant)),
    "};",
    ""
  )
}
emit(sprintf("/// All automatic-search reference cases.\npub const AUTO: &[&AutoCase] = &[%s];",
             paste0("&", vapply(auto_cases, function(c) c$name, ""), collapse = ", ")))


# R's ndiffs on the pmdarima series of `tests/it/auto_data.rs`, where R and pmdarima differ.
auto_text <- paste(readLines("tests/it/auto_data.rs"), collapse = "\n")
blocks <- regmatches(auto_text, gregexpr("pub const [A-Z0-9_]+: AutoCase = AutoCase \\{\\s*values: &\\[[^]]*\\]", auto_text))[[1]]
pmdarima_names <- sub("pub const ([A-Z0-9_]+):.*", "\\1", blocks)
pmdarima_ndiffs <- vapply(blocks, function(block) {
  body <- sub(".*values: &\\[", "", block)
  body <- sub("\\]$", "", body)
  ndiffs(as.numeric(strsplit(gsub("\\s", "", body), ",")[[1]]))
}, 0)
emit(
  "",
  "/// `ndiffs(values)` for each pmdarima series of `crate::auto_data` (in its order):",
  sprintf("/// %s.", paste(pmdarima_names, collapse = ", ")),
  sprintf("pub const PMDARIMA_SERIES_NDIFFS: &[usize] = %s;", rust_usize_array(pmdarima_ndiffs))
)

writeLines(lines, out)