Skip to content

Forecasting

sequential_analysis.procedures.forecast

Forecasting: predictive distributions for the next horizon values of a series.

Every forecaster gives, after each observation, the forecast of the next 1..horizon values: a point forecast, a scale, a distribution (normal, Student t with df degrees of freedom, or negative binomial for counts) and the central interval holding coverage of it. Each observation is first scored against the one-step forecast made for it: error is y minus that forecast and log_score the log predictive density (for counts, probability) of y, so log_likelihood is the prequential log-likelihood, a fair score for comparing forecasters on the same data.

Two kinds of training:

  • Fixed: the parameters are given, usually estimated from a history with forecasting.fit_ets, fit_ar or fit_counts. The state (level, trend, season, recent values) moves with the data, the parameters do not. The forecasts are then exactly those of the fitted model.
  • Continuous: the parameters are learnt from the stream itself. AutoRegressive without coefficients is Bayesian linear regression on the lags, with optional exponential forgetting for drift. ExponentialSmoothing without sigma learns the noise level, and without coefficients the effects of its regressors. ModelAveraging weights several forecasters (a grid of smoothing parameters, say) by their predictive densities, optionally forgetting, so the weight moves to whichever currently forecasts best.

Regressors (promotions, holidays, prices, weather) are inputs named in regressors. Each is a list of horizon + 1 numbers: its value at the current step, which explains the current observation, followed by its planned values for the next 1..horizon steps, which the forecasts use. A regressor must therefore be known ahead (a calendar, a planned campaign); forecasting.forecast_records cuts these windows from aligned columns. transform="log" models log y: multiplicative effects and a season that grows with the level become additive, the intervals are those of the model mapped back exactly, and the point forecast is then the median.

ConformalForecast puts distribution-free intervals around any of them, and ForecastComparison tells, anytime-valid, whether one forecaster is better than another.

ExponentialSmoothing is the additive-error ETS model of Hyndman, Koehler, Ord and Snyder (2008), with no, additive or damped trend, an optional additive season of period m and optional regressors z with effects b:

yhat_t = l_{t-1} + phi b_{t-1} + s_{t-m} + b'z_t,     e_t = y_t - yhat_t,
l_t = l_{t-1} + phi b_{t-1} + alpha e_t,
b_t = phi b_{t-1} + beta e_t,
s_t = s_{t-m} + gamma e_t.

The forecast h steps ahead is l + (phi + ... + phi^h) b + s (the season h steps ahead) + b'z_{t+h}, with variance sigma^2 (1 + sum_{j<h} c_j^2), c_j = alpha + beta (phi + ... + phi^j) + gamma [j divisible by m]. These are the recursions and intervals of statsmodels' ETSModel, which the tests check to 1e-9. With sigma unknown, it gets the prior p(sigma^2) ~ 1/sigma^2; after k errors the predictive distribution is then Student t with k degrees of freedom and scale^2 = (sum of squared errors / k) times the same factor, exact given the smoothing parameters.

The effects of the regressors can be learnt too. The state and errors of the model are affine in the effects: with x~ the states of the run without regressors and A_j those of a run driven by regressor j alone (from zero), the states are x~ - sum_j b_j A_j and the errors e~_t - sum_j b_j u_jt, with u_jt = z_jt - (what A_j predicts). So the effects are a linear regression of e~ on u, updated exactly (normal prior with precision ridge, sigma^2 ~ 1/sigma^2, optional forgetting of the data's information): the forecasts are Student t, exact at every horizon given the smoothing parameters when nothing is forgotten.

AutoRegressive is the AR(p) model y_t = c + phi_1 y_{t-1} + ... + phi_p y_{t-p} + b'z_t + e_t. With coefficients given, forecasts are the usual recursions with variance sigma^2 sum_{j<h} psi_j^2. Without, the coefficients get the prior N(0, sigma^2 I / ridge) and sigma^2 the prior 1/sigma^2, and each observation updates the posterior exactly (Bayesian linear regression on the lags and the regressors). With forgetting lambda < 1 the data's information decays by lambda per step (the prior's does not), so the coefficients are an exponentially weighted ridge regression and follow drift. The state holds the weighted sums x x' and x y, never a covariance obtained by subtraction, so it stays valid for any data. The one-step predictive distribution is exactly Student t; for h > 1 the scale adds the parameter uncertainty of the one-step regressors to the plug-in variance, an approximation.

PoissonSmoothing forecasts counts (orders, calls, incidents) with the Poisson local level model of Harvey and Fernandes (1989). The rate mu_t has a gamma distribution given the past, Gamma(a, b); before each observation it is discounted, Gamma(omega a, omega b): same mean, less certainty, so the rate can move. Then y_t ~ Poisson(e_t mu_t), with an optional exposure e_t (opening hours, a seasonal factor, a population), and the update a + y_t, b + e_t is exact. The forecast h steps ahead is negative binomial with mean e a / b, whose spread comes from the uncertainty in the rate; the intervals are counts, holding at least coverage. omega plays the part of the smoothing parameter: 1 is a constant rate, smaller values follow changes faster.

Cost per step (PERFORMANCE.md): constant time and state. 20 µs for exponential smoothing with fixed parameters (trend, season of 12, 12 steps ahead); about 0.3 ms when sigma is learnt, most of it the Student t quantile of the interval, and 0.4 ms with two learnt regressors; 0.45 ms for a learnt AR(5); 0.25 ms for counts 7 steps ahead (the count quantiles); 6 ms and a 31 kB state for averaged_smoothing over 63 models; 2 µs for the comparison.

Predictive dataclass

The forecast of the next 1..horizon values.

Continuous (size empty): mean + scale * (standard normal, or t with df), on the log scale with transform "log". Counts: negative binomial with size, rate and exposure per horizon; mean and scale are its mean and standard deviation.

cdf(h, x)

P(Y <= x) for the forecast h + 1 steps ahead, in the data's units.

density(h, x)

The density at x in the data's units (continuous forecasts only).

Forecaster

Bases: Procedure

Common protocol: update scores and absorbs one record, predictive forecasts from a state.

update(state, x)

(new state, error, log score) after observing the record x.

present(pred)

(point forecasts, scales) in the data's units: on the log scale, the median and m * s.

ExponentialSmoothing

Bases: Forecaster

Additive-error exponential smoothing (ETS) with optional trend, season and regressors.

See the module docstring. initial_level None lets the first observation set the level (it is not scored); initial_seasonal lists the seasonal effects of the first period observations, in order (zeros by default). sigma None learns the noise level from the one-step errors. With regressors, coefficients gives their effects; None learns them (then sigma must be None), with forgetting and ridge as in AutoRegressive.

AutoRegressive

Bases: Forecaster

AR(p) forecasts, with fixed coefficients or learnt by Bayesian regression on the lags.

Give coefficients (phi_1..phi_p), intercept, sigma and, with regressors, their effects for fixed training. Leave them out to learn them: forgetting lambda in (0, 1] discounts the past by lambda per step (1 keeps everything), and ridge is the prior precision of the coefficients relative to the noise, which is not discounted. The coefficients used for each forecast are then the exponentially weighted ridge regression

(sum_t lambda^(n+1-t) x_t x_t' + ridge I)^-1 sum_t lambda^(n+1-t) x_t y_t,

x_t = (1, y_{t-1}, ..., y_{t-p}, z_t): the exact posterior mean when the data's information decays by lambda per step and the prior's does not.

parameters(state)

The coefficients and noise level the next forecast uses.

PoissonSmoothing

Bases: Forecaster

Forecasts of counts: the Poisson local level model with a discounted gamma rate; see the module docstring.

discount omega in (0, 1]; exposure names an optional input of horizon + 1 positive numbers (now, then planned), like a regressor. prior is the rate's Gamma(shape, rate) before any data; the default (0, 0) lets the data alone decide, so the first forecast comes after the first non-zero count.

ModelAveraging

Bases: Forecaster

Bayesian model averaging of forecasters, with optional forgetting (dynamic model averaging).

The weight of model k is its prior weight times its predictive density of every observation so far, normalized: the exact posterior probability of each model. With forgetting lambda < 1 the weights are flattened before each observation (raised to the power lambda, Raftery, Karny and Ettler 2010), so an old record fades and the weight can move to a model that has become better. The forecast is the mixture of the models' forecasts with these weights: mean is the weighted mean of their point forecasts, the interval holds coverage of the mixture, and scale is the normal-equivalent one (the interval's half width over the normal quantile).

Weights move only on observations that every model forecast. averaged_smoothing builds one over a grid of smoothing parameters, averaged_counts over a grid of discounts. The models must be ExponentialSmoothing and AutoRegressive forecasters (with or without the log transform), or PoissonSmoothing ones, with the same horizon and inputs.

ConformalForecast

Bases: Procedure

Distribution-free forecast intervals around any forecaster: online conformal quantile tracking.

For each horizon h it keeps a half width q_h (in units of the forecaster's scale with normalize, else in the data's units) and issues the interval mean +- q_h scale. When the value it was issued for arrives, q_h moves by step_size (miss - alpha): up after a miss, down a little after a hit (Angelopoulos, Candes and Tibshirani 2023, the quantile-tracking form of adaptive conformal inference, Gibbs and Candes 2021). Telescoping the updates gives, for every sequence of data whatsoever,

miscoverage - alpha = (q_now - q_start) / (step_size * count),

and q stays within step_size of the range of the scores, so the fraction of intervals that missed tends to alpha at rate 1/count with no assumption on the data or the forecaster -- a long-run guarantee, not a per-interval probability. An interval with q < 0 is empty (lower above upper) and counts as a miss.

ForecastComparison

Bases: Procedure

Anytime-valid comparison of two forecasters by their losses (Choe and Ramdas 2024).

Each step takes the two forecasters' losses on the same value, both within bounds (an absolute error clipped at a cap, a Brier or interval score...). With d_t = loss_a - loss_b, the target is Delta_n = (1/n) sum_t E[d_t | past]: the difference in expected loss averaged over the steps so far, which may drift -- no stationarity is assumed. The sequence is the empirical Bernstein one of Howard et al. (2021) with their polynomial stitched boundary: with probability at least 1 - alpha, Delta_n lies in [lower, upper] at every n at once, so it can be monitored after every value and stopped at will.

log_density(error, scale, df)

Log density of a normal (df None) or Student t location-scale law at error from its location.

negative_binomial_log_pmf(k, size, rate, exposure)

log P(Y = k) for Poisson(exposure mu) counts with mu ~ Gamma(size, rate).

negative_binomial_cdf(k, size, rate, exposure)

P(Y <= k) for the same law: I_q(size, k + 1) with q = rate / (rate + exposure).

count_quantile(pred, h, p)

The smallest count k with P(Y <= k) >= p.

averaged_smoothing(*, trend=None, period=None, alphas=(0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9), betas=(0.01, 0.1, 0.3), gammas=(0.01, 0.1, 0.3), phis=(0.9, 0.98), regressors=(), transform=None, forgetting=1.0, horizon=1, coverage=0.9, input='y')

Exponential smoothing that learns its smoothing parameters: model averaging over a grid.

beta is given as a fraction of alpha and gamma as a fraction of 1 - alpha (the usual admissible region beta < alpha, gamma < 1 - alpha); phis are used only with a damped trend. Each model learns its own noise level and the effects of the regressors, so the averaging is over the smoothing parameters given the data.

averaged_counts(*, discounts=(0.5, 0.7, 0.8, 0.9, 0.95, 0.98, 0.995, 1.0), exposure=None, forgetting=1.0, horizon=1, coverage=0.9, input='y')

Count forecasts that learn how fast the rate moves: model averaging over a grid of discounts.

stitched_boundary(v, c, alpha, m)

Polynomial stitched boundary of Howard, Ramdas, McAuliffe and Sekhon (2021), with s = 1.4 and eta = 2.

For a process S_t that is sub-exponential with variance process V_t and scale c, P(exists t: S_t >= boundary(max(V_t, m))) <= alpha.

sequential_analysis.forecasting

Fitting forecasters to a history: the "fixed training" half of forecasting.

fit_ets estimates an exponential smoothing model by maximum likelihood. The initial states (level, trend, seasonal effects) and the effects of the regressors enter the one-step errors linearly, e_t = e_t(0) - w' D^(t-1) x0 - sum_j b_j u_jt with D = F - g w' (Hyndman et al. 2008), so for given smoothing parameters the best initial states and effects are a least-squares regression and the likelihood is profiled over them exactly. The smoothing parameters are then found by Nelder-Mead, started from the four best points of a grid (the likelihood can have several local maxima), over the usual admissible region, as statsmodels bounds it: alpha in [1e-4, 0.9999], beta / alpha in [1e-4, 0.9999], gamma in [0, 0.9999 (1 - alpha)] (statsmodels also allows a slightly negative gamma) and phi in [0.8, 0.98]. The seasonal effects are normalized to sum to zero (level and season are otherwise confounded). sigma^2 is the mean squared one-step error.

fit_ar estimates an AR(p) with intercept and regressors by conditional least squares (the first p values are conditioned on), as statsmodels' AutoReg; sigma^2 is the residual sum of squares over n - p.

fit_var estimates a VAR(p) with intercept by least squares, equation by equation (as statsmodels' VAR), with the maximum-likelihood noise covariance (residual cross-products over the n - p fitted steps), and can choose p by AIC among 1..max_order on the common sample that the largest order leaves (as statsmodels' select_order).

fit_counts estimates the discount of PoissonSmoothing by maximizing the prequential likelihood (golden-section search on [0.01, 1]).

With transform="log" the models are fitted to log y and the reported log-likelihood is that of y itself (the Jacobian is subtracted), so it can be compared with an untransformed fit. All return the fitted forecaster, whose forecasts follow the model with the estimated parameters held fixed, and the state after the history, from which a run can continue (Run(fit.model, initial_state=fit.state)).

forecast_records builds the records these take, and the forecasters too, from a series and aligned columns of regressors (or exposures): each record holds the value and, for each regressor, its value at that step and the next horizon ones.

forecast_records(values, regressors=None, *, horizon=1, input='y')

Records for the forecasters: {input: value, name: [z_t, z_t+1, ..., z_t+horizon]} for each regressor.

Each column of regressors is aligned with values and runs horizon steps past its end (the plan for the steps to forecast).

nelder_mead(f, start, *, step=0.5, tolerance=1e-10, max_evaluations=4000)

Minimize f from start by the Nelder-Mead simplex (standard coefficients); (x, f(x), evaluations).

fit_ets(inputs, *, trend=None, period=None, regressors=(), transform=None, input='y', horizon=1, coverage=0.9, max_evaluations=4000)

Maximum likelihood exponential smoothing (additive errors); see the module docstring.

inputs are records ({input: value, regressor: window...}, see forecast_records) or, without regressors, plain numbers. trend is None, "additive" or "damped"; period the length of the season.

fit_ar(inputs, order, *, regressors=(), transform=None, input='y', horizon=1, coverage=0.9)

Conditional least squares AR(p) with intercept and regressors; see the module docstring.

fit_var(inputs, series, order=None, *, max_order=8, horizon=1, coverage=0.9)

Least-squares VAR(p) with intercept; with order None, p chosen by AIC up to max_order. See the docstring.

fit_counts(inputs, *, exposure=None, prior=(0.0, 0.0), input='y', horizon=1, coverage=0.9, tolerance=1e-06)

The PoissonSmoothing discount that maximizes the prequential likelihood of the history.