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 GARCH(1,1) conformance tests.
#
# Writes `tests/it/r_garch_data.rs`. R's packages are pinned by the Docker image in
# `scripts/r/` (tseries comes with forecast); 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_garch_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.
#
# `tseries::garch` minimises 0.5 sum_{t >= 2} (log h_t + x_t^2 / h_t) with the variance
# started at mean(x^2); its fitted values start at the long-run variance instead. Its optimiser often stops short of the minimum,
# so the script also polishes the fit with `optim` from several starts and stores both.

suppressPackageStartupMessages(library(tseries))

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

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

lines <- c(
  "//! R reference vectors for the GARCH(1,1) conformance tests.",
  "//!",
  sprintf("//! Generated by `scripts/generate_r_garch_reference.R` with %s and tseries %s.",
          R.version.string, as.character(packageVersion("tseries"))),
  "//! Do not edit by hand; rerun the script instead.",
  "",
  "/// A `tseries::garch(values, order = c(1, 1))` fit and the polished optimum of its",
  "/// likelihood.",
  "pub struct GarchCase {",
  "    /// The zero-mean series.",
  "    pub values: &'static [f64],",
  "    /// tseries' `omega`, `alpha` and `beta`.",
  "    pub tseries: [f64; 3],",
  "    /// tseries' log-likelihood, `logLik(fit)`.",
  "    pub tseries_loglike: f64,",
  "    /// tseries' conditional standard deviation of each value from the second on, started",
  "    /// at the long-run variance `omega / (1 - alpha - beta)`.",
  "    pub sigma: &'static [f64],",
  "    /// The best `omega`, `alpha` and `beta` that `optim` finds from several starts.",
  "    pub optimum: [f64; 3],",
  "    /// The log-likelihood at `optimum`.",
  "    pub optimum_loglike: f64,",
  "}",
  ""
)
emit <- function(...) lines <<- c(lines, ...)

simulate <- function(n, omega, alpha, beta, seed) {
  set.seed(seed)
  x <- numeric(n)
  h <- omega / (1 - alpha - beta)
  for (t in 1:n) {
    x[t] <- sqrt(h) * rnorm(1)
    h <- omega + alpha * x[t]^2 + beta * h
  }
  # The nearest doubles to 6 decimals; round() can land one ulp away.
  as.numeric(sprintf("%.6f", x))
}

# tseries' negative log-likelihood without the constant.
objective <- function(par, x) {
  if (any(par <= 0) || par[2] + par[3] >= 1) return(1e10)
  n <- length(x)
  h <- mean(x^2)
  total <- 0
  for (t in 2:n) {
    h <- par[1] + par[2] * x[t - 1]^2 + par[3] * h
    total <- total + log(h) + x[t]^2 / h
  }
  0.5 * total
}

polish <- function(x, starts) {
  best <- NULL
  for (start in starts) {
    fit <- optim(start, objective, x = x, control = list(reltol = 1e-15, maxit = 20000))
    fit <- optim(fit$par, objective, x = x, control = list(reltol = 1e-15, maxit = 20000))
    if (is.null(best) || fit$value < best$value) best <- fit
  }
  best
}

constant <- function(n) 0.5 * (n - 1) * log(2 * pi)

cases <- list(
  list(name = "MODERATE", values = simulate(800, 0.1, 0.12, 0.8, 71)),
  list(name = "PERSISTENT", values = simulate(1000, 0.02, 0.06, 0.92, 72)),
  list(name = "SHORT", values = simulate(300, 0.3, 0.2, 0.5, 73))
)

for (case in cases) {
  x <- case$values
  n <- length(x)
  fit <- garch(x, order = c(1, 1), trace = FALSE)
  v <- mean(x^2)
  starts <- list(as.numeric(coef(fit)), c(0.1 * v, 0.1, 0.8), c(0.05 * v, 0.05, 0.9),
                 c(0.5 * v, 0.2, 0.3))
  best <- polish(x, starts)
  emit(
    sprintf("/// `garch(values, order = c(1, 1))` on %d values.", n),
    sprintf("pub const %s: GarchCase = GarchCase {", case$name),
    sprintf("    values: %s,", rust_array(x)),
    sprintf("    tseries: [%s],", paste(vapply(coef(fit), rust_float, ""), collapse = ", ")),
    sprintf("    tseries_loglike: %s,", rust_float(as.numeric(logLik(fit)))),
    sprintf("    sigma: %s,", rust_array(fit$fitted.values[-1, 1])),
    sprintf("    optimum: [%s],", paste(vapply(best$par, rust_float, ""), collapse = ", ")),
    sprintf("    optimum_loglike: %s,", rust_float(-best$value - constant(n))),
    "};",
    ""
  )
}
emit(sprintf("/// All GARCH reference cases.\npub const ALL: &[&GarchCase] = &[%s];",
             paste0("&", vapply(cases, function(c) c$name, ""), collapse = ", ")))

writeLines(lines, out)