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):
value = float(value)
return "f64::NAN" if np.isnan(value) else repr(value)
def rust_array(values):
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):
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:]
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):
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():
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")
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):
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():
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):
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
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):
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")
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():
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")
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):
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():
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")
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):
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():
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()