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 statsmodels reference vectors for the VAR conformance tests.

Writes `tests/it/var_data.rs`. Run from the repository root with the pinned tools of
`scripts/requirements.txt`:

    .venv/bin/python -I scripts/generate_var_reference.py

The series are simulated here with fixed seeds and stored in the output, so the tests do not
depend on numpy's random number generator.
"""

import numpy as np
import statsmodels
from statsmodels.tsa.api import VAR

OUT = "tests/it/var_data.rs"


def rust_float(x):
    """A float as a Rust literal that reads back as the same double."""
    x = float(x)
    if np.isnan(x):
        return "f64::NAN"
    text = repr(x)
    if "e" not in text and "." not in text and "inf" not in text:
        text += ".0"
    if text == "inf":
        return "f64::INFINITY"
    if text == "-inf":
        return "f64::NEG_INFINITY"
    return text


def rust_array(values):
    """Floats as a Rust slice literal, row-major for a matrix."""
    flat = np.asarray(values, dtype=float).ravel()
    return "&[" + ", ".join(rust_float(v) for v in flat) + "]"


def simulate(coefficients, intercept, sigma, n, seed, exog=None, beta=None):
    """`n` values of a VAR with lag matrices `coefficients`, plus `exog @ beta.T` if given."""
    rng = np.random.default_rng(seed)
    p = len(coefficients)
    k = len(intercept)
    chol = np.linalg.cholesky(sigma)
    burn = 200
    y = np.zeros((n + burn, k))
    for t in range(p, n + burn):
        value = np.array(intercept, dtype=float)
        for i, a in enumerate(coefficients):
            value += np.asarray(a) @ y[t - i - 1]
        if exog is not None and t >= burn:
            value += np.asarray(beta) @ exog[t - burn]
        y[t] = value + chol @ rng.standard_normal(k)
    return y[burn:]


CASES = [
    {
        "name": "VAR2_K2",
        "p": 2,
        "y": simulate(
            [[[0.5, 0.1], [0.2, 0.3]], [[-0.2, 0.0], [0.1, -0.1]]],
            [1.0, -0.5],
            [[1.0, 0.3], [0.3, 0.5]],
            200,
            1,
        ),
    },
    {
        "name": "VAR1_K3",
        "p": 1,
        "y": simulate(
            [[[0.6, 0.1, 0.0], [0.0, 0.4, 0.2], [0.1, 0.0, 0.5]]],
            [0.2, 0.0, -0.3],
            [[1.0, 0.2, 0.1], [0.2, 0.8, 0.0], [0.1, 0.0, 0.6]],
            150,
            2,
        ),
    },
]

# A VARX(1) with one exogenous dummy.
X = np.zeros((180, 1))
X[::17, 0] = 1.0
CASES.append(
    {
        "name": "VARX1_K2",
        "p": 1,
        "exog": X,
        "y": simulate(
            [[[0.4, 0.2], [0.1, 0.5]]],
            [0.5, 1.0],
            [[0.7, 0.1], [0.1, 0.9]],
            180,
            3,
            exog=X,
            beta=[[2.0], [-1.0]],
        ),
    }
)

HORIZON = 5
MAX_LAGS = 6

lines = [
    "//! statsmodels reference vectors for the VAR conformance tests.",
    "//!",
    f"//! Generated by `scripts/generate_var_reference.py` with statsmodels {statsmodels.__version__}"
    f" and numpy {np.__version__}.",
    "//! Do not edit by hand; rerun the script instead.",
    "",
    "/// A `VAR(values, exog).fit(p)` fit and its forecasts.",
    "pub struct VarCase {",
    "    /// The series, row-major: `nobs` rows of `k` values.",
    "    pub values: &'static [f64],",
    "    /// The number of series `k`.",
    "    pub k: usize,",
    "    /// The lag order `p`.",
    "    pub p: usize,",
    "    /// The exogenous regressors, row-major with `columns` values per row; empty for none.",
    "    pub exog: &'static [f64],",
    "    /// The number of exogenous regressors.",
    "    pub columns: usize,",
    "    /// The intercepts, one per series.",
    "    pub intercept: &'static [f64],",
    "    /// The lag matrices `A_1, ..., A_p`, each `k x k` row-major: row `i` is equation `i`.",
    "    pub lags: &'static [f64],",
    "    /// The exogenous coefficients, `k x columns` row-major.",
    "    pub beta: &'static [f64],",
    "    /// `sigma_u`, the residual covariance over `nobs - k p - 1 - columns`.",
    "    pub sigma: &'static [f64],",
    "    /// `sigma_u_mle`, the residual covariance over `nobs`.",
    "    pub sigma_mle: &'static [f64],",
    "    /// The log-likelihood.",
    "    pub loglike: f64,",
    "    /// AIC, BIC, HQIC and FPE.",
    "    pub criteria: [f64; 4],",
    "    /// The future exogenous rows the forecast uses, row-major; empty for none.",
    "    pub exog_future: &'static [f64],",
    "    /// The forecast means, `horizon` rows of `k` values.",
    "    pub mean: &'static [f64],",
    "    /// The 95% lower and upper bounds, laid out like `mean`.",
    "    pub lower: &'static [f64],",
    "    /// See `lower`.",
    "    pub upper: &'static [f64],",
    "    /// The forecast covariance matrices, `horizon` of them, each `k x k` row-major.",
    "    pub forecast_cov: &'static [f64],",
    f"    /// The orders `select_order(maxlags = {MAX_LAGS})` picks by AIC, BIC, HQIC and FPE.",
    "    pub selected: [usize; 4],",
    "}",
    "",
]

for case in CASES:
    y = case["y"]
    p = case["p"]
    k = y.shape[1]
    exog = case.get("exog")
    model = VAR(y, exog=exog)
    result = model.fit(p)
    names = result.params.index if hasattr(result.params, "index") else None
    params = np.asarray(result.params)
    columns = 0 if exog is None else exog.shape[1]
    # statsmodels stacks the constant, the exogenous columns, then the lags `L1.y1 ... Lp.yk`;
    # column `j` of `params` is equation `j`.
    intercept = params[0]
    beta = params[1 : 1 + columns].T
    lags = [params[1 + columns + i * k : 1 + columns + (i + 1) * k].T for i in range(p)]
    exog_future = np.zeros((HORIZON, columns))
    if columns:
        exog_future[2, 0] = 1.0
    mean, lower, upper = result.forecast_interval(
        y[-p:], HORIZON, alpha=0.05, exog_future=exog_future if columns else None
    )
    forecast_cov = result.forecast_cov(HORIZON)
    selection = VAR(y, exog=exog).select_order(MAX_LAGS)
    criteria = [result.aic, result.bic, result.hqic, result.fpe]
    lines += [
        f"/// `VAR(values{', exog' if columns else ''}).fit({p})` on {y.shape[0]} rows of {k} series.",
        f"pub const {case['name']}: VarCase = VarCase {{",
        f"    values: {rust_array(y)},",
        f"    k: {k},",
        f"    p: {p},",
        f"    exog: {rust_array(exog if columns else [])},",
        f"    columns: {columns},",
        f"    intercept: {rust_array(intercept)},",
        f"    lags: {rust_array(np.concatenate([np.asarray(a).ravel() for a in lags]))},",
        f"    beta: {rust_array(beta)},",
        f"    sigma: {rust_array(result.sigma_u)},",
        f"    sigma_mle: {rust_array(result.sigma_u_mle)},",
        f"    loglike: {rust_float(result.llf)},",
        f"    criteria: [{', '.join(rust_float(c) for c in criteria)}],",
        f"    exog_future: {rust_array(exog_future if columns else [])},",
        f"    mean: {rust_array(mean)},",
        f"    lower: {rust_array(lower)},",
        f"    upper: {rust_array(upper)},",
        f"    forecast_cov: {rust_array(forecast_cov)},",
        "    selected: [{}],".format(
            ", ".join(str(int(selection.selected_orders[c])) for c in ["aic", "bic", "hqic", "fpe"])
        ),
        "};",
        "",
    ]

lines.append(
    "/// All VAR reference cases.\npub const ALL: &[&VarCase] = &["
    + ", ".join("&" + c["name"] for c in CASES)
    + "];"
)

with open(OUT, "w", encoding="utf-8") as f:
    f.write("\n".join(lines) + "\n")