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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
"""Generate statsmodels reference vectors for the streaming and seasonality additions.

Writes `tests/it/steady_data.rs`, `tests/it/fourier_data.rs`, `tests/it/mstl_data.rs`
`tests/it/period_data.rs` and `tests/it/fixed_data.rs`. Run from the repository root:

    python3 -I scripts/generate_streaming_reference.py

Requires numpy and statsmodels (tested with statsmodels 0.14.0, numpy 1.24.3, scipy 1.11.1), and
coreforecast (tested with 0.0.20) for the period references.
The vectors of `generate_reference.py` stay as they are; this script only adds new ones.
"""

import pathlib
import warnings

import numpy as np
import statsmodels
import pandas as pd
from statsmodels.tsa.deterministic import Fourier
from statsmodels.tsa.seasonal import MSTL
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX

TESTS = pathlib.Path(__file__).resolve().parent.parent / "tests" / "it"
STEADY_OUTPUT = TESTS / "steady_data.rs"
FOURIER_OUTPUT = TESTS / "fourier_data.rs"
MSTL_OUTPUT = TESTS / "mstl_data.rs"
PERIOD_OUTPUT = TESTS / "period_data.rs"
FIXED_OUTPUT = TESTS / "fixed_data.rs"
STEADY_HORIZON = 5


def rust_float(value):
    """Format a float as a Rust literal that round-trips exactly."""
    value = float(value)
    return "f64::NAN" if np.isnan(value) else repr(value)


def rust_array(values):
    """Format floats as a Rust array literal that round-trips exactly."""
    if len(values) == 0:
        return "&[]"
    body = ",\n".join(f"        {rust_float(v)}" for v in values)
    return f"&[\n{body},\n    ]"


def seasonal_arma(ar, ma, sar, sma, period, sigma2, n, seed):
    """Simulate `n` values of a seasonal ARMA after a burn-in."""
    rng = np.random.default_rng(seed)
    burn = 300
    e = rng.standard_normal(n + burn) * np.sqrt(sigma2)
    seasonal_ar = np.zeros(len(sar) * period + 1)
    seasonal_ar[0] = 1
    for i, c in enumerate(sar):
        seasonal_ar[(i + 1) * period] = -c
    seasonal_ma = np.zeros(len(sma) * period + 1)
    seasonal_ma[0] = 1
    for i, c in enumerate(sma):
        seasonal_ma[(i + 1) * period] = c
    ar_poly = np.convolve(np.r_[1, -np.array(ar, float)], seasonal_ar)
    ma_poly = np.convolve(np.r_[1, np.array(ma, float)], seasonal_ma)
    y = np.zeros_like(e)
    for t in range(len(y)):
        value = sum(ma_poly[j] * e[t - j] for j in range(len(ma_poly)) if t - j >= 0)
        value -= sum(ar_poly[j] * y[t - j] for j in range(1, len(ar_poly)) if t - j >= 0)
        y[t] = value
    return y[burn:]


# (name, doc, ar, d, ma, seasonal (ar, ma, period), mean, sigma2, length, missing index, seed)
STEADY_CASES = [
    ("ARMA11", "ARMA(1, 1), 120 values.", [0.5], 0, [0.3], ([], [], 0), 0.0, 1.3, 120, None, 1),
    ("ARMA21", "ARMA(2, 1) with mean 2, 120 values.", [0.5, -0.2], 0, [0.4], ([], [], 0), 2.0, 0.8, 120, None, 2),
    ("SMA4", "ARIMA(0, 0, 1)(0, 0, 1, 4), 160 values: it converges late.", [], 0, [0.3], ([], [0.6], 4), 0.0, 1.0, 160, None, 3),
    ("MISSING", "ARMA(1, 2) with values 50 and 90 missing, both after convergence.", [0.7], 0, [0.6, 0.3], ([], [], 0), 0.0, 1.0, 140, (50, 90), 4),
    ("DRIFT", "ARIMA(1, 1, 1) with drift 0.3, 121 values: the filter differences the raw values.", [0.4], 1, [0.5], ([], [], 0), 0.3, 1.0, 121, None, 5),
]


def steady_case(name, doc, ar, d, ma, seasonal, mean, sigma2, length, missing, seed):
    """Render one `SteadyCase` from statsmodels' filter with its default tolerance."""
    sar, sma, period = seasonal
    w = seasonal_arma(ar, ma, sar, sma, period, sigma2, length - d, seed) + mean
    y = w
    for _ in range(d):
        y = np.concatenate([[10.0], 10.0 + np.cumsum(y)])
    if missing is not None:
        y = y.copy()
        y[list(missing)] = np.nan
    w = np.diff(y, n=d) - mean
    model = SARIMAX(w, order=(len(ar), 0, len(ma)), seasonal_order=(len(sar), 0, len(sma), period), trend="n")
    assert model.ssm.tolerance == 1e-19
    results = model.filter([*ar, *ma, *sar, *sma, sigma2])
    if d == 0:
        forecast = results.get_forecast(STEADY_HORIZON)
        forecast_mean, forecast_variance = forecast.predicted_mean + mean, forecast.var_pred_mean
    else:
        forecast_mean, forecast_variance = [], []
    lines = [f"/// {doc}", f"pub const {name}: SteadyCase = SteadyCase {{"]
    arrays = {
        "ar": ar,
        "ma": ma,
        "seasonal_ma": sma,
        "values": y,
        "innovation_values": results.filter_results.forecasts_error[0],
        "innovation_variances": results.filter_results.forecasts_error_cov[0, 0],
        "forecast_mean": forecast_mean,
        "forecast_variance": forecast_variance,
    }
    lines += [f"    {field}: {rust_array(values)}," for field, values in arrays.items()]
    lines += [
        f"    d: {d},",
        f"    period: {period},",
        f"    mean: {rust_float(mean)},",
        f"    sigma2: {rust_float(sigma2)},",
        f"    period_converged: {results.filter_results.period_converged},",
        "};",
    ]
    return "\n".join(lines)


def write_steady():
    """Write the steady-state reference module."""
    header = f'''//! statsmodels reference vectors for the filter's steady-state mode.
//!
//! Generated by `scripts/generate_streaming_reference.py` with statsmodels {statsmodels.__version__}.
//! Do not edit by hand; rerun the script instead.

/// A series filtered by statsmodels with its default `ssm.tolerance = 1e-19`.
///
/// Innovations come from `SARIMAX(diff(values, d) - mean, order=(p, 0, q),
/// seasonal_order=(0, 0, Q, s)).filter(params)`.
pub struct SteadyCase {{
    /// The AR coefficients.
    pub ar: &'static [f64],
    /// The MA coefficients.
    pub ma: &'static [f64],
    /// The seasonal MA coefficients.
    pub seasonal_ma: &'static [f64],
    /// The raw series. `NaN` marks a missing value.
    pub values: &'static [f64],
    /// `filter_results.forecasts_error[0]`, one per differenced value.
    pub innovation_values: &'static [f64],
    /// `filter_results.forecasts_error_cov[0, 0]`, one per differenced value.
    pub innovation_variances: &'static [f64],
    /// `get_forecast({STEADY_HORIZON}).predicted_mean + mean` after the series; empty for `d > 0`.
    pub forecast_mean: &'static [f64],
    /// `get_forecast({STEADY_HORIZON}).var_pred_mean`; empty for `d > 0`.
    pub forecast_variance: &'static [f64],
    /// The differencing order.
    pub d: usize,
    /// The season length; 0 for non-seasonal cases.
    pub period: usize,
    /// The mean of the differenced series.
    pub mean: f64,
    /// The innovation variance.
    pub sigma2: f64,
    /// `filter_results.period_converged`: the step at which statsmodels froze the covariance.
    pub period_converged: usize,
}}

/// All steady-state reference cases.
pub const ALL: &[&SteadyCase] = &[{", ".join(f"&{case[0]}" for case in STEADY_CASES)}];
'''
    body = "\n\n".join(steady_case(*case) for case in STEADY_CASES)
    STEADY_OUTPUT.write_text(header + "\n" + body + "\n")


# (name, doc, period, K, first t, rows)
FOURIER_CASES = [
    ("WEEKLY", "Period 7, K = 3, from t = 0.", 7.0, 3, 0, 30),
    ("MONTHLY", "Period 12, K = 6: statsmodels keeps the Nyquist sine, the crate drops it.", 12.0, 6, 0, 30),
    ("YEARLY", "Period 365.25, K = 4, from t = 1000.", 365.25, 4, 1000, 40),
    ("HOURLY_YEAR", "Period 8766, K = 2, from t = 123456.", 8766.0, 2, 123456, 20),
]


def fourier_case(name, doc, period, k, t0, rows):
    """Render one `FourierCase` from statsmodels' `deterministic.Fourier`."""
    generator = Fourier(period, k)
    if t0 == 0:
        terms = generator.in_sample(pd.RangeIndex(rows)).to_numpy()
    else:
        terms = generator.out_of_sample(rows, pd.RangeIndex(t0)).to_numpy()
    if 2 * k == period:
        terms = np.delete(terms, 2 * k - 2, axis=1)
    lines = [f"/// {doc}", f"pub const {name}: FourierCase = FourierCase {{"]
    lines += [
        f"    period: {rust_float(period)},",
        f"    k: {k},",
        f"    t0: {t0},",
        f"    columns: {terms.shape[1]},",
        f"    values: {rust_array(terms.ravel())},",
        "};",
    ]
    return "\n".join(lines)


def write_fourier():
    """Write the Fourier reference module."""
    header = f'''//! statsmodels `deterministic.Fourier` reference regressors.
//!
//! Generated by `scripts/generate_streaming_reference.py` with statsmodels {statsmodels.__version__}.
//! Do not edit by hand; rerun the script instead.

/// Fourier regressors from statsmodels for rows `t0, t0 + 1, ...`, row-major, with the
/// Nyquist sine removed where `2K = period`.
pub struct FourierCase {{
    /// The seasonal period.
    pub period: f64,
    /// The number of harmonics.
    pub k: usize,
    /// The time index of the first row.
    pub t0: u64,
    /// The number of columns per row.
    pub columns: usize,
    /// The regressors, row-major.
    pub values: &'static [f64],
}}

/// All Fourier reference cases.
pub const ALL: &[&FourierCase] = &[{", ".join(f"&{case[0]}" for case in FOURIER_CASES)}];
'''
    body = "\n\n".join(fourier_case(*case) for case in FOURIER_CASES)
    FOURIER_OUTPUT.write_text(header + "\n" + body + "\n")


def multi_seasonal(n, periods, seed):
    """A trend, one random pattern per period, and noise."""
    rng = np.random.default_rng(seed)
    t = np.arange(n)
    y = 5.0 + 0.02 * t + 0.3 * rng.standard_normal(n)
    for period in periods:
        pattern = rng.standard_normal(period) * 2.0
        y += pattern[t % period]
    return y


# (name, doc, length, generating periods, periods passed, iterate, seed[, Box-Cox lambda or "auto"])
MSTL_CASES = [
    ("DAILY_WEEKLY", "Hourly data with daily and weekly patterns, four weeks.", 672, (24, 168), (168, 24), 2, 41),
    ("THREE", "Periods 3, 7 and 12 on 240 values, three passes.", 240, (3, 7, 12), (12, 3, 7), 3, 42),
    ("SINGLE", "One period, 12, so one pass with seasonal window 11.", 96, (12,), (12,), 2, 43),
    ("DROPPED", "Periods 4 and 30 on 50 values: 30 is at least half the length and is dropped.", 50, (4,), (4, 30), 2, 44),
    ("BOX_COX_AUTO", "Periods 7 and 12 on a positive series, Box-Cox lambda chosen by MLE.", 168, (7, 12), (7, 12), 2, 45, "auto"),
    ("BOX_COX_HALF", "Periods 4 and 9 on a positive series, Box-Cox lambda 0.5.", 120, (4, 9), (4, 9), 2, 46, 0.5),
    ("BOX_COX_LOG", "Period 12 on a positive series, Box-Cox lambda 0 (the logarithm).", 96, (12,), (12,), 2, 47, 0.0),
]


def mstl_case(name, doc, n, generating, periods, iterate, seed, lmbda=None):
    """Render one `MstlCase` from statsmodels' `MSTL`."""
    y = multi_seasonal(n, generating, seed)
    if lmbda is not None:
        y = np.exp(0.2 * (y - y.mean()) / y.std()) * 10.0
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        # statsmodels skips the transform for lmbda=0 (`elif self.lmbda:` is false), so the
        # logarithm is applied here for that case.
        if lmbda == 0.0:
            model = MSTL(np.log(y), periods=list(periods), iterate=iterate)
        else:
            model = MSTL(y, periods=list(periods), iterate=iterate, lmbda=lmbda)
        result = model.fit()
    used = model.est_lmbda if lmbda == "auto" else lmbda
    seasonal = np.asarray(result.seasonal).reshape(n, -1)
    lines = [f"/// {doc}", f"pub const {name}: MstlCase = MstlCase {{"]
    lines += [
        f"    periods: &{list(periods)},",
        f"    iterate: {iterate},",
        f"    kept: {seasonal.shape[1]},",
        f"    lambda: {rust_float(np.nan if used is None else used)},",
        f"    auto_lambda: {str(lmbda == 'auto').lower()},",
        f"    values: {rust_array(y)},",
        f"    seasonal: {rust_array(seasonal.T.ravel())},",
        f"    trend: {rust_array(result.trend)},",
        f"    remainder: {rust_array(result.resid)},",
        "};",
    ]
    return "\n".join(lines)


def write_mstl():
    """Write the MSTL reference module."""
    header = f'''//! statsmodels `MSTL` reference decompositions.
//!
//! Generated by `scripts/generate_streaming_reference.py` with statsmodels {statsmodels.__version__}.
//! Do not edit by hand; rerun the script instead.

/// A series with `MSTL(values, periods=periods, iterate=iterate).fit()` from statsmodels.
pub struct MstlCase {{
    /// The periods as passed, unsorted.
    pub periods: &'static [usize],
    /// The number of passes.
    pub iterate: usize,
    /// How many periods statsmodels kept.
    pub kept: usize,
    /// The Box-Cox lambda the series was transformed with; `NaN` for none.
    pub lambda: f64,
    /// Whether statsmodels chose `lambda` (`lmbda="auto"`, scipy's MLE).
    pub auto_lambda: bool,
    /// The series.
    pub values: &'static [f64],
    /// The seasonal components of the kept periods, ascending, one after another, on the
    /// Box-Cox scale if `lambda` is not `NaN`.
    pub seasonal: &'static [f64],
    /// The trend component.
    pub trend: &'static [f64],
    /// The remainder.
    pub remainder: &'static [f64],
}}

/// All MSTL reference cases.
pub const ALL: &[&MstlCase] = &[{", ".join(f"&{case[0]}" for case in MSTL_CASES)}];
'''
    body = "\n\n".join(mstl_case(*case) for case in MSTL_CASES)
    MSTL_OUTPUT.write_text(header + "\n" + body + "\n")


# (name, doc, length, periods, noise sd, trend slope, max period, seed)
PERIOD_CASES = [
    ("WEEKLY", "A weekly pattern on daily data with a trend.", 200, (7,), 0.5, 0.02, 30, 51),
    ("MONTHLY", "A monthly pattern on 8 years.", 96, (12,), 0.3, 0.0, 24, 52),
    ("DAILY_HOURLY", "A daily pattern on two weeks of hourly data.", 336, (24,), 0.5, 0.01, 60, 53),
    ("QUARTERLY", "A quarterly pattern.", 60, (4,), 0.2, 0.05, 12, 54),
    ("TWO", "Periods 6 and 20 together.", 300, (6, 20), 0.3, 0.0, 40, 55),
    ("NOISE", "White noise: no period.", 200, (), 1.0, 0.0, 30, 56),
    ("WEAK", "A weak weekly pattern in strong noise.", 200, (7,), 3.0, 0.0, 30, 57),
]


def period_case(name, doc, n, periods, noise, slope, max_period, seed):
    """Render one `PeriodCase` with coreforecast's answers."""
    from coreforecast._lib import seasonal as core_seasonal
    from coreforecast.seasonal import find_season_length

    rng = np.random.default_rng(seed)
    t = np.arange(n)
    y = 1.0 + slope * t + noise * rng.standard_normal(n)
    for period in periods:
        y += (rng.standard_normal(period) * 2.0)[t % period]
    lines = [f"/// {doc}", f"pub const {name}: PeriodCase = PeriodCase {{"]
    lines += [
        f"    max_period: {max_period},",
        f"    largest_lag: {int(core_seasonal.period(y, max_period))},",
        f"    season_length: {int(find_season_length(y, max_period))},",
        f"    values: {rust_array(y)},",
        "};",
    ]
    return "\n".join(lines)


def write_period():
    """Write the period detection reference module."""
    import coreforecast

    header = f'''//! coreforecast `find_season_length` reference periods.
//!
//! Generated by `scripts/generate_streaming_reference.py` with coreforecast {coreforecast.__version__}.
//! Do not edit by hand; rerun the script instead.

/// A simulated series with coreforecast's answers.
pub struct PeriodCase {{
    /// The largest lag searched.
    pub max_period: usize,
    /// `_lib.seasonal.period(values, max_period)`: the lag of the largest autocovariance of
    /// the first differences, before the strength check.
    pub largest_lag: usize,
    /// `find_season_length(values, max_period)`: that lag if the series is strongly
    /// seasonal at it, else 0.
    pub season_length: usize,
    /// The series.
    pub values: &'static [f64],
}}

/// All period reference cases.
pub const ALL: &[&PeriodCase] = &[{", ".join(f"&{case[0]}" for case in PERIOD_CASES)}];
'''
    body = "\n\n".join(period_case(*case) for case in PERIOD_CASES)
    PERIOD_OUTPUT.write_text(header + "\n" + body + "\n")


# (name, doc, ar, ma, seasonal (ar, ma, period), mean, length, fixed parameter names, seed)
FIXED_CASES = [
    ("SEASONAL_MA", "ARIMA(0, 0, 1)(0, 0, 1, 4) with the seasonal MA fixed at -0.6.",
     [], [0.4], ([], [-0.5], 4), None, 120, {"ma.S.L4": -0.6}, 61),
    ("AR_WITH_MEAN", "ARMA(1, 1) with mean 2 and the AR coefficient fixed at 0.5.",
     [0.6], [0.3], ([], [], 0), 2.0, 150, {"ar.L1": 0.5}, 62),
    ("MEAN", "ARMA(1, 0) with the mean fixed at 1.",
     [0.4], [], ([], [], 0), 1.3, 150, {"const": 1.0}, 63),
]


def fixed_case(name, doc, ar, ma, seasonal, mean, n, fixed, seed):
    """Render one `FixedCase` from statsmodels' `fix_params`."""
    sar, sma, period = seasonal
    y = seasonal_arma(ar, ma, sar, sma, period, 1.0, n, seed) + (mean or 0.0)
    model = ARIMA(y, order=(len(ar), 0, len(ma)), seasonal_order=(len(sar), 0, len(sma), period),
                  trend="c" if mean is not None else "n")
    with model.fix_params(fixed):
        result = model.fit()
    params = dict(zip(model.param_names, result.params))
    pick = lambda prefix, count, lag=1: [params[f"{prefix}{(i + 1) * lag}"] for i in range(count)]
    lines = [f"/// {doc}", f"pub const {name}: FixedCase = FixedCase {{"]
    lines += [
        f"    values: {rust_array(y)},",
        f"    ar: {rust_array(pick('ar.L', len(ar)))},",
        f"    ma: {rust_array(pick('ma.L', len(ma)))},",
        f"    seasonal_ma: {rust_array(pick('ma.S.L', len(sma), period))},",
        f"    period: {period},",
        f"    with_mean: {str(mean is not None).lower()},",
        f"    mean: {rust_float(params.get('const', 0.0))},",
        f"    sigma2: {rust_float(params['sigma2'])},",
        f"    loglike: {rust_float(result.llf)},",
        f"    fixed_ar: {str('ar.L1' in fixed).lower()},",
        f"    fixed_seasonal_ma: {str(any(k.startswith('ma.S') for k in fixed)).lower()},",
        f"    fixed_mean: {str('const' in fixed).lower()},",
        "};",
    ]
    return "\n".join(lines)


def write_fixed():
    """Write the fixed-parameter reference module."""
    header = f'''//! statsmodels reference fits with fixed parameters (`fix_params`).
//!
//! Generated by `scripts/generate_streaming_reference.py` with statsmodels {statsmodels.__version__}.
//! Do not edit by hand; rerun the script instead.

/// A fit of `ARIMA(values, order=(p, 0, q), seasonal_order=(0, 0, Q, s))` with some
/// parameters fixed. The coefficient fields hold every coefficient, fixed ones included.
pub struct FixedCase {{
    /// The series.
    pub values: &'static [f64],
    /// The AR coefficients.
    pub ar: &'static [f64],
    /// The MA coefficients.
    pub ma: &'static [f64],
    /// The seasonal MA coefficients.
    pub seasonal_ma: &'static [f64],
    /// The season length; 0 without a seasonal part.
    pub period: usize,
    /// Whether the model has a mean (`trend="c"`).
    pub with_mean: bool,
    /// The mean; 0 without one.
    pub mean: f64,
    /// The innovation variance.
    pub sigma2: f64,
    /// `results.llf`.
    pub loglike: f64,
    /// Whether the AR part is fixed.
    pub fixed_ar: bool,
    /// Whether the seasonal MA part is fixed.
    pub fixed_seasonal_ma: bool,
    /// Whether the mean is fixed.
    pub fixed_mean: bool,
}}

/// All fixed-parameter reference cases.
pub const ALL: &[&FixedCase] = &[{", ".join(f"&{case[0]}" for case in FIXED_CASES)}];
'''
    body = "\n\n".join(fixed_case(*case) for case in FIXED_CASES)
    FIXED_OUTPUT.write_text(header + "\n" + body + "\n")


if __name__ == "__main__":
    warnings.simplefilter("ignore")
    write_steady()
    write_fourier()
    write_mstl()
    write_period()
    write_fixed()