Skip to content

Time series: ARIMA, volatility, state space, local projections

The classes and functions of the row "Time series: ARIMA, volatility, state space, local projections" of Analytical tools, with what calls return (the results and their methods: forecasts, impulse responses, tests). Import them from pymetrix (from pymetrix import ...) unless a heading names another module. Parameters and return types are in each signature; the text says what each does.

Help topics: Volatility models (GARCH), Local projections, ARDL models and the bounds test, Cointegration and VECMs, Maximum likelihood, Counts and durations over time, The forecast workflow, Vector autoregressions, Bootstrap bands and intervals, Spectra and long memory, Unit roots and stationarity, Markov-switching models, Seasonal adjustment and calendar effects, Smooth-transition autoregressions, State space and the Kalman filter, Interventions and transfer functions, Trend-cycle filters, Specification and diagnostic tests, Distribution functions and moments, Business-cycle dating.

Classes

ADF dataclass

ADF(variable: str, lags: Annotated[str | int, advanced(help='lagged differences absorbing serial correlation: a number, or aic / bic / t-stat to choose')] = 'aic', trend: Annotated[Literal['c', 'ct', 'ctt', 'n'], Widget('', help='terms under the alternative: c constant, ct adds a trend (trending series), ctt a quadratic, n none')] = 'c', max_lags: Annotated[str | int, advanced(help='largest lag aic / bic / t-stat try; empty = 12*(n/100)^(1/4), capped in short samples to keep 4 residual degrees of freedom; unused with a fixed lag')] = '', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments')] = dict(), critical_values: Annotated[Literal['mackinnon', 'simulated'], Widget('', help=_CRITICAL_HELP)] = 'mackinnon', draws: Annotated[int, advanced(help=_DRAWS_HELP)] = 2000, seed: Annotated[int, advanced(help=_SEED_HELP)] = 0)

Bases: Test

Augmented Dickey-Fuller test.

The null is a unit root; the alternative is stationarity around the deterministic terms chosen in Trend. The statistic is the t-ratio on the lagged level in a regression of the first difference on it, the deterministic terms and lagged differences; it rejects when large and negative, against MacKinnon's p-values and critical values, which depend on the trend. Match the terms to the alternative: ct for a trending series (with a constant alone a trend-stationary series looks like a unit root), c for one that moves around a level, n only for a series with a known zero mean. Too few lags leave serial correlation that distorts the size; too many cost power, which is low anyway against roots near one in short samples. Not rejecting is weak evidence for a unit root: cross-check with KPSS (whose null is stationarity) or the GLS-based Ng-Perron and ERS tests, and remember that an unmodelled break in level or trend also makes ADF fail to reject (see the Perron test).

MacKinnon's values are asymptotic and the lag search distorts them further in short samples. With critical_values="simulated" they are simulated for this sample instead: draws Gaussian random walks of the series' length (seeded by seed), each tested exactly as the data are (the same trend terms, lag rule and lag search); the critical values are the 1, 5 and 10% quantiles of the draws' statistics and the p-value is the share at or below the statistic, with its Monte Carlo standard error.

APARCH dataclass

APARCH(arch: Annotated[int, _ARCH] = 1, asym: Annotated[int, _ASYM] = 1, garch: Annotated[int, _GARCH] = 1, delta: Annotated[float | None, Widget('text', advanced=True, help='fixed power; empty = estimate')] = None, dist: Dist = 'normal', backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchVariance

Asymmetric power ARCH (Ding, Granger and Engle); the power delta is estimated unless given.

ARDL dataclass

ARDL(formula: str, lags: int = 1, order: int | Mapping[str, int] = 1, trend: Literal['n', 'c', 'ct'] = 'c', select: Literal['aic', 'bic', 'hqic'] | None = None, max_lags: int = 4, max_order: int = 4, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict())

formula: the dependent variable on the distributed-lag regressors (lc ~ ly + lw; expressions allowed).

ARMA dataclass

ARMA(ar: Annotated[int | Sequence[int], Widget('text', help='AR order, or a list of lags such as [1, 4]')] = 0, ma: Annotated[int | Sequence[int], Widget('text', help='MA order, or a list of lags')] = 0)

ARMA errors: ar and ma are orders, or lists of lags such as [1, 4].

DFGLS dataclass

DFGLS(variable: str, trend: Literal['c', 'ct'] = 'c', lags: Annotated[str | int, advanced(help='fixed lags; empty = choose by method')] = '', method: Annotated[Literal['aic', 'bic', 't-stat'], advanced(help='how lags are chosen: information criterion or significance of the last lag')] = 'aic', max_lags: Annotated[str | int, advanced(help='largest lag searched; empty = default')] = '', backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchTest

Elliott-Rothenberg-Stock DF-GLS unit-root test (arch): ADF on GLS-detrended data, more powerful.

EGARCH dataclass

EGARCH(arch: Annotated[int, _ARCH] = 1, asym: Annotated[int, _ASYM] = 1, garch: Annotated[int, _GARCH] = 1, dist: Dist = 'normal', backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchVariance

Exponential GARCH (Nelson): the log variance responds to the size and sign of shocks.

ERSPointOptimal dataclass

ERSPointOptimal(variable: str, trend: Annotated[Literal['c', 'ct'], Widget('', help='terms under the alternative: c a constant, ct a constant and linear trend (trending series)')] = 'c', lags: Annotated[str | int, advanced(help='lags of the AR regression for the long-run variance, or maic (modified AIC, recommended)')] = 'maic', max_lags: Annotated[str | int, advanced(help='largest lag the modified AIC tries; empty = 12*(T/100)^(1/4)')] = '')

Bases: Test

Elliott-Rothenberg-Stock point-optimal unit-root test (PT): the likelihood ratio of a unit root against the local alternative a = 1 + cbar / T, scaled by the long-run variance.

The null is a unit root; the alternative is stationarity around a level (c) or a linear trend (ct). The test is designed to have nearly the best possible power against roots close to one, where ADF has little. PT rejects when small. There is no p-value: compare PT with ERS's asymptotic critical values, which are only approximate in short samples. The long-run variance comes from an autoregression whose lag is chosen by the modified AIC unless given; as for the Ng-Perron tests, too short a lag can distort the size.

ExponentialSmoothing dataclass

ExponentialSmoothing(series: Annotated[str, Widget('text', help='the series to forecast, unbroken in the sample; quarterly or monthly for seasonal models')], trend: Annotated[Literal['none', 'add', 'mul'], Widget('choice', help='none (simple smoothing), additive (Holt) or multiplicative')] = 'none', damped: Annotated[bool, Widget('checkbox', help='damp the trend towards flat (needs a trend)')] = False, seasonal: Annotated[Literal['none', 'add', 'mul'], Widget('choice', help='seasonal factors: none, additive or multiplicative (Holt-Winters)')] = 'none', error: Annotated[Literal['add', 'mul'], Widget('choice', advanced=True, help='additive or multiplicative errors (positive series)')] = 'add', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict())

Exponential smoothing (ETS), estimated by maximum likelihood (statsmodels' ETSModel).

A level, optionally a trend (damped or not) and seasonal factors, each updated by a share of the latest forecast error.

The smoothing parameters say how fast each component adapts: near 1 it follows the latest data, near 0 it is nearly fixed. Choose the components to match the series: a trend only if it grows (damped trends are the safer choice beyond a few periods, since undamped ones extend the latest slope for ever), additive seasonality when the swings are of constant size and multiplicative when they grow with the level. The error type matters mainly for the intervals, which widen with the level under multiplicative errors. Compare candidate models by information criteria (on the same sample) or by out-of-sample forecast errors; ETS has no regressors.

fit

fit(data: Dataset, span: Any = None) -> FittedExponentialSmoothing

Estimate the smoothing parameters and initial states by maximum likelihood on the periods of span (first, last), which must hold an unbroken run of the series.

FIGARCH dataclass

FIGARCH(arch: Annotated[int, Widget('number', min=0, max=1, help='ARCH term: 0 or 1')] = 1, garch: Annotated[int, Widget('number', min=0, max=1, help='GARCH term: 0 or 1')] = 1, power: Annotated[float, Widget('number', min=0.5, max=4, step=0.5, help='power of the shocks (2 = variance, 1 = standard deviation)')] = 2.0, truncation: Annotated[int, Widget('number', min=10, max=100000, advanced=True, help='lags kept in the fractional filter')] = 1000, dist: Dist = 'normal', backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchVariance

Fractionally integrated GARCH (long memory in volatility). arch and garch are 0 or 1.

GARCH dataclass

GARCH(arch: Annotated[int, Widget('number', min=0, max=10, help='lags of the squared shocks (ARCH terms)')] = 1, garch: Annotated[int, Widget('number', min=0, max=10, help='lags of the conditional variance (GARCH terms)')] = 1, asym: Annotated[int, Widget('number', min=0, max=10, help='GJR terms: extra response to negative shocks')] = 0, dist: Dist = 'normal', backend: Annotated[Literal['native', 'arch'], Widget('choice', advanced=True, help='our implementation or the arch package')] = 'native')

Conditional variance: arch lags of squared errors, garch lags of the variance, asym GJR terms (extra weight on negative errors).

Errors are normal, t, Hansen's (1994) skewed t (eta, lambda) or the generalised error distribution (nu), each of variance 1, estimated natively (cross-checked against the arch package); backend="arch" uses arch.

libraries property

libraries: tuple[str, ...]

Libraries this configuration needs (the arch backend needs arch).

KPSS dataclass

KPSS(variable: str, trend: Annotated[Literal['c', 'ct'], Widget('', help='the null: c stationary around a level, ct around a linear trend')] = 'c', lags: Annotated[str | int, advanced(help='Bartlett lags for the long-run variance: a number, auto (from the data) or legacy, 12(n/100)^(1/4)')] = 'auto', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments')] = dict())

Bases: Test

KPSS test: the null is stationarity (the reverse of ADF).

The null is that the series is stationary around a level (c) or a linear trend (ct); the alternative is a unit root. The statistic is the sum of squared partial sums of the residuals from the deterministic terms, scaled by a Newey-West (Bartlett) long-run variance, and it rejects when large. The p-value is interpolated in KPSS's table, so it lies between 0.01 and 0.10; a note says when it is at an edge. The lag of the long-run variance matters: too few with persistent but stationary data make the test reject too often, too many reduce its power. Read it with ADF: ADF not rejecting while KPSS rejects points to a unit root; both rejecting suggests that neither describes the data well, for instance because of a break.

LocalProjection dataclass

LocalProjection(response: Annotated[str, Widget('text', help='the response variable, e.g. 100*log(gdp) or infl')], shock: Annotated[str, Widget('text', help='the shock, e.g. an identified monetary surprise or the policy rate')], horizons: Annotated[int, Widget('number', min=0, max=60, help='last horizon, in periods: one regression for each of 0 to this; long horizons are noisier, with fewer observations')] = 12, lags: Annotated[int, Widget('number', min=0, max=24, help='lags of the response, the shock and the controls')] = 4, controls: Annotated[Sequence[str], Widget('text', help='other variables whose lags are controlled for')] = (), contemporaneous: Annotated[Sequence[str], Widget('text', help='controls dated at the time of the shock (ordered before it)')] = (), long_difference: Annotated[bool, Widget('checkbox', help='response y[t+h] - y[t-1], for variables in log levels')] = False, cov: Annotated[Literal['hac', 'white'], Widget('choice', help='hac: Newey-West with h+1 lags; white: lag-augmented robust')] = 'hac', state: Annotated[str | None, Widget('text', advanced=True, help='state indicator (0 to 1) for state-dependent responses; dated t-1')] = None, scale: Annotated[float, Widget('number', min=1e-06, max=1000000.0, advanced=True, help='size of the shock the responses are scaled to')] = 1.0, instruments: Annotated[Sequence[str], Widget('text', advanced=True, help='external instruments for the shock (LP-IV), e.g. a high-frequency surprise')] = ())

Impulse responses by local projection: one regression of the response at each horizon on the shock.

Give the response and the shock (series or expressions such as 100*log(gdp)), the number of horizons, the lags of the response, the shock and the controls, and any controls dated at the time of the shock (variables ordered before the shock). Standard errors allow for the overlapping errors of multi-horizon regressions. A state indicator gives separate responses in each state.

The response at horizon h is the shock's coefficient in that regression, and it is causal only if the shock is as good as random given the controls: an identified surprise, a recursive ordering through the contemporaneous controls (as in a Cholesky VAR), or external instruments. Unlike a VAR, local projections do not extrapolate a short-run model to long horizons, so they are more robust to misspecified dynamics, but their responses are noisier and often jagged, increasingly so at long horizons, where each regression also loses observations at the end of the sample. Read the bands rather than single horizons. With instruments, check each horizon's first-stage F in the table (below about 10: weak instruments).

formula

formula(h: int, panel_entity: str | None = None) -> str

The regression at horizon h (for reading, and to run it yourself).

fit_smooth

fit_smooth(data: Dataset, span: Any = None, penalty: float | None = None, order: int = 2, folds: int = 5, coverage: float = 0.9) -> Any

A smooth local projection (Barnichon and Brownlees 2019): the response a penalised cubic spline in the horizon, all horizons estimated together; penalty by cross-validation unless given (0: the ordinary local projection on the periods where every horizon is observed). See pymetrix.smooth_lp.

fit

fit(data: Dataset, span: Any = None, coverage: float = 0.9, bootstrap: Any = None) -> FittedLocalProjection

Estimate the regression at every horizon. coverage sets the wide bands (68% bands are always given).

bootstrap (a Bootstrap(...) or a kind's name: wild, block, pairs or residual) makes the bands from bootstrap draws of all the horizons' regressions together, each held at its data, in place of the analytic (HAC or robust) bands; the analytic standard error stays in se, the draws' in bootstrap se, and .bootstrap reports what was done. None (the default): the analytic bands, as before.

MarkovSwitching dataclass

MarkovSwitching(formula: str, regimes: int = 2, ar: int = 0, switching_variance: bool = False, switching_exog: bool = True, search: int = 20, seed: int = 0, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict())

formula: the dependent variable on regressors (growth ~ 1 for a switching mean).

NgPerron dataclass

NgPerron(variable: str, trend: Annotated[Literal['c', 'ct'], Widget('', help='terms under the alternative: c a constant, ct a constant and linear trend (trending series)')] = 'c', lags: Annotated[str | int, advanced(help='lags of the AR regression for the long-run variance, or maic (modified AIC, recommended)')] = 'maic', max_lags: Annotated[str | int, advanced(help='largest lag the modified AIC tries; empty = 12*(T/100)^(1/4)')] = '')

Bases: Test

Ng-Perron M unit-root tests (MZa, MZt, MSB, MPT) on GLS-detrended data, with good size and power even when the errors have a large negative moving-average root.

The null is a unit root; the alternative is stationarity around a level (c) or a linear trend (ct). Detrending by GLS gives more power than ADF against roots near one, and the modified statistics keep their size where Phillips-Perron tests reject far too often. All four reject when small. The statistic shown is MZa; MZt, MSB and MPT and their critical values are in the details. There is no p-value: compare each statistic with Ng and Perron's asymptotic critical values. The lag of the autoregression for the long-run variance is chosen by the modified AIC unless given; Ng and Perron recommend it because a short lag chosen by AIC or BIC can distort the size badly.

PerronBreak dataclass

PerronBreak(variable: str, date: Annotated[str, Widget('period', help='the first period of the new regime, known from outside the data')] = '', model: Annotated[Literal['A', 'B', 'C'], Widget('choice', help='A: a level shift; B: a change of slope; C: both')] = 'C', lags: Annotated[int, advanced(help='lagged differences absorbing serial correlation; too few distort the size')] = 0, draws: Annotated[int, advanced(help='replications for the simulated p-value; more, less simulation error')] = 2000, seed: Annotated[int, advanced(help='random seed for the simulated p-value')] = 0)

Bases: Test

Perron's (1989) unit-root test with a structural break at a known date: a level shift (A), a change of slope (B) or both (C) under the alternative of trend stationarity.

The null is a unit root with the break; the alternative is stationarity around a broken trend. An unmodelled break makes ADF fail to reject, which this test corrects. The date must be known from outside the data (an oil shock, a policy change): picking it by looking at the series makes the test reject too often, and for an unknown date a test that searches over dates, such as Zivot-Andrews, is the right one. The statistic is the t-ratio on the lagged level and rejects when large and negative; the p-value and critical values are simulated for this sample size, break date, model and lag. The lag is fixed: too few leave serial correlation that distorts the size.

PhillipsPerron dataclass

PhillipsPerron(variable: str, trend: Literal['c', 'ct', 'n'] = 'c', test_type: Annotated[Literal['tau', 'rho'], advanced(help='t-statistic (tau) or normalised bias (rho)')] = 'tau', lags: Annotated[str | int, advanced(help='Newey-West lags; empty = 12*(n/100)^(1/4)')] = '', backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchTest

Phillips-Perron unit-root test (arch): ADF regression with a long-run variance correction.

pymetrix.statespace.KalmanRun dataclass

KalmanRun(a_pred: ndarray, P_pred: ndarray, a_filt: ndarray, P_filt: ndarray, a_smooth: ndarray | None, P_smooth: ndarray | None, v: ndarray, F: ndarray, loglike: float, diffuse: int, engine: str, eta_smooth: ndarray | None = None, loglike_diffuse: float = 0.0)

Filtered, predicted and smoothed states with their variances (periods first), innovations, the log likelihood and the number of diffuse periods.

loglike_as

loglike_as(diffuse_terms: str = 'include') -> float

The log likelihood with the diffuse periods' terms included (loglike) or left out.

SARIMA dataclass

SARIMA(series: Annotated[str, Widget('text', help='the series, unbroken in the sample; let d difference it, so forecasts are in its levels')], order: Annotated[tuple[int, int, int], Widget('text', help='(p, d, q): AR order, differences, MA order')] = (1, 0, 0), seasonal_order: Annotated[tuple[int, int, int], Widget('text', help='(P, D, Q): seasonal AR order, seasonal differences, seasonal MA order')] = (0, 0, 0), period: Annotated[int, Widget('spin', help='the season length s; 0 = from the frequency (4 or 12)')] = 0, exog: Annotated[tuple[str, ...], Widget('text', help='regressors (their future values are needed to forecast)')] = (), trend: Annotated[Literal['auto', 'n', 'c', 't', 'ct'], Widget('choice', help='auto: a constant without differencing, none with it; c constant, t trend, ct both')] = 'auto', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict(), interventions: Annotated[tuple[str, ...], Widget('text', help='intervention regressors from dates, e.g. step("2008Q3"), pulse("2020Q2"), temporary("2024Q1", decay=0.7); carried into forecasts')] = ())

Seasonal ARIMA(p, d, q)(P, D, Q)s with optional regressors, by exact maximum likelihood (statsmodels' SARIMAX).

The series is differenced d times and seasonally D times; AR and MA terms model what is left, at lags 1 to p and q and at multiples of the season length s.

Difference only as much as needed to make the series stationary (d = 1 for a random walk, D = 1 for a seasonal unit root); differencing a stationary series adds a non-invertible MA root and wider intervals. Choose p and q from the autocorrelations of the differenced series or by information criteria, keep the model small, and check that the residuals are white noise. With trend="auto" a differenced model has no constant, so its forecasts have no drift: set the trend for a series that grows. With regressors the model is a regression with SARIMA errors, and forecasts need the regressors' future values. Forecast intervals widen with the horizon, without bound once the series is differenced; they assume the model and its parameters.

fit

fit(data: Dataset, span: Any = None) -> FittedSARIMA

Estimate by exact maximum likelihood on the periods of span (first, last), which must hold an unbroken run of the series and its regressors.

SmoothTransitionAR dataclass

SmoothTransitionAR(series: Annotated[str, Widget('text', help='the series, e.g. GDP growth')], lags: Annotated[int, Widget('number', min=1, max=12, help='the autoregressive order in each regime')] = 1, delay: Annotated[int, Widget('number', min=0, max=12, help='the lag of the series that drives the transition; 0 = choose (1 to lags)')] = 1, transition: Annotated[Literal['logistic', 'exponential'], Widget('choice', help='logistic (LSTAR) or exponential (ESTAR)')] = 'logistic')

A two-regime smooth-transition autoregression (LSTAR or ESTAR), by nonlinear least squares.

fit

fit(data: Dataset, span: Any = None) -> FittedSmoothTransitionAR

Estimate by least squares concentrated on (gamma, c), over a grid and then by Nelder-Mead (and over the delays, when the delay is 0).

StateSpace dataclass

StateSpace(states: Sequence[str], transition: Sequence[str], measurement: Sequence[str], shocks: Mapping[str, str | float], params: Sequence[str | Param] = (), stationary: Sequence[str] = (), initial: Literal['auto', 'diffuse', 'stationary'] = 'auto')

A linear state-space model, written as transition and measurement equations (see the module).

system

system(values: Mapping[str, float]) -> SystemMatrices

The system matrices at parameter values.

filter

filter(data: Dataset, values: Mapping[str, float], span: Any = None, diffuse_terms: str = 'include') -> FittedStateSpace

Filter and smooth at given (calibrated) parameter values, without estimating. diffuse_terms as in fit.

loglike

loglike(data: Dataset, values: Mapping[str, float], span: Any = None, diffuse_terms: str = 'include') -> float

The log likelihood at these values; diffuse_terms as in fit.

fit

fit(data: Dataset, span: Any = None, start: Mapping[str, float] | None = None, fixed: Mapping[str, float] | None = None, cov: Literal['classic', 'none'] = 'classic', max_iter: int = 2000, diffuse_terms: Literal['include', 'exclude'] = 'include') -> FittedStateSpace

Estimate the free parameters by maximum likelihood, or by posterior mode when parameters have priors. fixed sets parameters (e.g. {"sd_slope": 0}); start gives starting values.

diffuse_terms, with diffuse states: "include" (default) maximises the exact diffuse log likelihood of Durbin and Koopman (2012, section 7.2.2), with the diffuse periods' terms; "exclude" leaves those terms out (Harvey's likelihood of the later observations given the first d, what statsmodels' UnobservedComponents reports by default). The log likelihood, AIC and BIC follow; where the diffuse part of the system has no parameters (unobserved-components models) the two differ by a constant, d/2 log 2 pi + 1/2 sum log F_inf for one series, and the estimates and standard errors are the same. criteria gives either from a fit.

STLForecast dataclass

STLForecast(series: Annotated[str, Widget('text', help='the series to forecast, unbroken in the sample; log it if its seasonality is proportional')], model: Annotated[Literal['arima', 'ets'], Widget('choice', help='the model of the seasonally adjusted series')] = 'arima', order: Annotated[tuple[int, int, int], Widget('text', help="the ARIMA's (p, d, q) for the adjusted series; with d > 0 it has no constant, so no drift")] = (1, 1, 0), trend: Annotated[Literal['none', 'add'], Widget('choice', help='ETS: an additive trend in the adjusted series, or none (a level only, flat forecasts)')] = 'add', damped: Annotated[bool, Widget('checkbox', help='ETS: damp the trend, so long-horizon forecasts level off instead of extending the latest slope')] = True, period: Annotated[int, Widget('spin', help='the season length; 0 = from the frequency (4 or 12)')] = 0, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict())

STL, then a model of the seasonally adjusted series: its forecasts plus the last year's seasonal component (statsmodels' STLForecast).

STL estimates the seasonal pattern by local regression, letting it change slowly over the years; the model then has to capture the trend and dynamics of the adjusted series, so choose it as for a non-seasonal series. The forecasts repeat the last seasonal cycle unchanged, and their intervals come from the model of the adjusted series alone, treating the seasonal component as known. The decomposition is additive: take logs first when the seasonal swings grow with the level of the series.

fit

fit(data: Dataset, span: Any = None) -> FittedSTLForecast

Decompose by STL and estimate the model of the adjusted series on the periods of span.

TARCH dataclass

TARCH(arch: Annotated[int, _ARCH] = 1, asym: Annotated[int, _ASYM] = 1, garch: Annotated[int, _GARCH] = 1, dist: Dist = 'normal', backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchVariance

Threshold GARCH (Zakoian): the conditional standard deviation responds to absolute shocks.

Theta dataclass

Theta(series: Annotated[str, Widget('text', help='the series to forecast, unbroken in the sample; positive for multiplicative adjustment')], deseasonalize: Annotated[Literal['auto', 'yes', 'no'], Widget('choice', help='auto: adjust when a test finds seasonality')] = 'auto', period: Annotated[int, Widget('spin', help='the season length; 0 = from the frequency')] = 0, method: Annotated[Literal['auto', 'additive', 'multiplicative'], Widget('choice', advanced=True, help='the seasonal adjustment: multiplicative for positive series')] = 'auto', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict())

The theta method: simple exponential smoothing plus half the slope of a linear trend (statsmodels' ThetaModel), after a multiplicative seasonal adjustment when the series is seasonal.

A simple, hard-to-beat benchmark for univariate forecasts: the level adapts through exponential smoothing while the drift is the fitted linear trend, damped to half its slope. It has no regressors and assumes the sample's average trend carries on, so it suits short horizons and steady series better than ones with breaks. Alpha near 1 means the level follows the latest observations (close to a random walk); near 0 a long average. The intervals come from the exponential smoothing's variance, ignoring the uncertainty in the trend.

fit

fit(data: Dataset, span: Any = None) -> FittedTheta

Estimate the smoothing parameter and the trend on the periods of span.

ThresholdAR dataclass

ThresholdAR(series: Annotated[str, Widget('text', help='the series, stationary (e.g. GDP growth, not its level); its own lag switches the regime')], lags: Annotated[int, Widget('number', min=1, max=12, help='the autoregressive order in each regime')] = 1, delay: Annotated[int, Widget('number', min=0, max=12, help='the lag of the series that switches regimes; 0 = choose (1 to lags)')] = 0, trim: Annotated[float, Widget('number', min=0.05, max=0.4, step=0.05, advanced=True, help='the least share of observations in each regime')] = 0.15)

A two-regime self-exciting threshold autoregression (SETAR), by conditional least squares over the threshold and the delay.

The model lets the dynamics differ between two regimes, e.g. recessions and expansions, split by whether an earlier value of the series is above an estimated threshold. Before reading the regimes, test linearity with linearity_test(): under the null of one regime the threshold is not identified, so ordinary F distributions do not apply and the p-value is bootstrapped. The coefficients' standard errors treat the threshold and delay as known. Trim sets the smallest regime: lower values let the search find a rare regime but estimate it from few observations. Multi-step forecasts are simulated, since a nonlinear model's forecast is not its one-step rule iterated.

fit

fit(data: Dataset, span: Any = None) -> FittedThresholdAR

Estimate on the periods of span (first, last): least squares in each regime at every candidate threshold (and delay, when it is 0), keeping the one with the smallest sum of squared residuals.

Transfer dataclass

Transfer(input: str, num: int = 0, den: int = 0, delay: int = 0)

One input of a transfer function: omega(L) / delta(L) L^delay applied to input, an intervention (step("2024Q1")) or a series of the data; num is the order of omega(L) (0: one coefficient), den the order of delta(L) (0: no decay; 1: a geometric decay at rate delta).

kind property

kind: str

permanent for a step or ramp, temporary for a pulse, temporary or seasonal pulse, series for a series input.

TransferFunction dataclass

TransferFunction(series: Annotated[str, Widget('text', help='the series, unbroken in the sample')], inputs: Annotated[tuple[Any, ...], Widget('text', help='interventions or input series, e.g. step("2011Q1"); Transfer(..., den=1) for a decay')] = (), order: Annotated[tuple[int, int, int], Widget('text', help='(p, d, q) of the disturbance')] = (1, 0, 0), seasonal_order: Annotated[tuple[int, int, int], Widget('text', help='(P, D, Q) of the disturbance')] = (0, 0, 0), period: Annotated[int, Widget('spin', help='the season length s; 0 = from the frequency (4 or 12)')] = 0, trend: Annotated[Literal['auto', 'n', 'c', 't', 'ct'], Widget('choice', help='auto: a constant without differencing, none with it')] = 'auto')

Rational transfer functions omega(L) / delta(L) of interventions or input series, with ARIMA disturbances, by exact maximum likelihood (statsmodels' SARIMAX for the disturbance; the decay parameters jointly).

inputs are Transfer(input, num, den, delay), or an intervention or a series as text (no decay, one coefficient). order, seasonal_order, period and trend are SARIMA's: the disturbance's ARIMA. effects() gives each intervention's effect path (permanent and temporary parts, cumulative), forecast() carries the dynamics into the forecast periods, plot() shows the series, its counterfactual and the effect.

fit

fit(data: Dataset, span: Any = None, presample: int = 200) -> FittedTransferFunction

Estimate by exact maximum likelihood on the periods of span. presample periods before the sample are used to start the filters of interventions dated before it.

UnobservedComponents dataclass

UnobservedComponents(series: Annotated[str, Widget('text', help='the series to decompose, e.g. log real GDP')], trend: Annotated[Literal['local level', 'random walk with drift', 'local linear trend', 'smooth trend'], Widget('choice', help='local level: random walk; with drift: plus a constant growth; local linear: with a random-walk slope; smooth: slope shocks only')] = 'local linear trend', cycle: Annotated[int, Widget('number', min=0, max=4, help='order of the autoregressive cycle; 0 = no cycle')] = 2, irregular: Annotated[bool, Widget('checkbox', help='include a white-noise irregular component')] = True)

A series as trend + cycle + irregular, estimated by maximum likelihood with the Kalman filter.

Choose the trend (local level, random walk with drift, local linear trend, or smooth trend, whose trend has no shock of its own and gives an HP-like trend), the order of an autoregressive cycle (0 for none) and whether to include an irregular (white-noise) component. The smoothed trend and cycle are two-sided estimates; the filtered ones use only past data (real-time).

The split into trend and cycle is identified only by the model's assumptions: different trend specifications fit the data about equally well yet give quite different cycles, so treat the cycle as model-dependent and compare specifications. A trend with its own shocks absorbs much of the low-frequency movement and leaves a small, noisy cycle; the smooth trend forces more of the movement into the cycle. A variance estimated at zero makes that component deterministic. Smoothed estimates near the end of the sample are revised as new data arrive, which matters when the latest gap is used for policy; the filtered ones are what was known then.

VarianceRatio dataclass

VarianceRatio(variable: str, lags: int = 2, trend: Literal['c', 'n'] = 'c', debiased: Annotated[bool, advanced()] = True, robust: Annotated[bool, advanced(help='heteroskedasticity-robust statistic')] = True, overlap: Annotated[bool, advanced(help='use overlapping blocks')] = True, backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchTest

Lo-MacKinlay variance-ratio test of a random walk (arch).

ZivotAndrews dataclass

ZivotAndrews(variable: str, trend: Literal['c', 't', 'ct'] = 'c', trim: Annotated[float, advanced(help='share of the sample excluded at each end when searching for the break', min=0.05, max=0.3, step=0.05)] = 0.15, lags: Annotated[str | int, advanced(help='fixed lags; empty = choose by method')] = '', method: Annotated[Literal['aic', 'bic', 't-stat'], advanced(help='how lags are chosen: information criterion or significance of the last lag')] = 'aic', max_lags: Annotated[str | int, advanced(help='largest lag searched; empty = default')] = '', backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())

Bases: _ArchTest

Zivot-Andrews unit-root test allowing one structural break at an unknown date (arch).

Functions

acd

acd(data: Dataset, variable: str, distribution: Literal['exponential', 'weibull'] = 'exponential', span: Any = None) -> SeriesModel

The ACD(1, 1) of Engle and Russell (1998): x_t = psi_t e_t, psi_t = omega + a x_{t-1} + b psi_{t-1}, with exponential (quasi-maximum likelihood) or Weibull errors of unit mean.

ach

ach(data: Dataset, variable: str, span: Any = None) -> SeriesModel

The autoregressive conditional hazard ACH(1, 1) of the 0/1 event series variable by maximum likelihood.

arfima

arfima(data: Dataset, variable: str, p: int = 0, q: int = 0, span: Any = None) -> FittedARFIMA

ARFIMA(p, d, q) of variable by conditional sum of squares, the mean removed first.

bilinear

bilinear(data: Dataset, variable: str, span: Any = None) -> Any

The bilinear model y_t = mu + phi y_{t-1} + b y_{t-1} e_{t-1} + e_t by conditional least squares (Gaussian likelihood conditional on e_1 = 0); standard errors from the Gauss-Newton information.

cointegrating_regression

cointegrating_regression(data: Dataset, outcome: str, regressors: Sequence[str], method: Literal['fmols', 'ccr', 'dols'] = 'fmols', trend: Literal['n', 'c', 'ct', 'ctt'] = 'c', bandwidth: float | None = None, leads: int | None = None, lags: int | None = None, span: Any = None, where: str | None = None, bandwidth_rule: Literal['newey-west'] = 'newey-west') -> CointegratingRegression

The cointegrating regression of outcome on regressors (and trend) by FMOLS, CCR or DOLS, over the rows of span (first, last) and where (a condition on the rows, e.g. "year >= 1990"). bandwidth_rule is "newey-west" (Newey and West 1994, as arch 9.0 and R's sandwich), the only rule; "legacy" (pymetrix 0.1.0a18's) was removed after 0.1.0a20 and raises a SpecificationError that says so. See long_run_covariance.

concordance

concordance(first: Any, second: Any, lags: int | None = None) -> TestResult

Harding and Pagan's (2002) concordance index of two cycles, the share of periods both are in the same phase, with Harding and Pagan's (2006) test that they are unrelated.

first and second are datings (date_cycles) or 0/1 phase series, compared on the periods both have. The index I = (1/T) sum [S1 S2 + (1 - S1)(1 - S2)] is 1 when the phases always coincide, and about 0.5 for unrelated cycles only if both spend half the time in each phase, so it is judged by the test: the t-statistic of the slope in the least-squares regression of S2 on a constant and S1 (equivalently of their correlation rho_S), with Newey-West (HAC) standard errors, since phases are persistent; lags for the HAC (None: floor(4 (T / 100)^(2/9))). The statistic is compared with the standard normal.

cross_spectrum

cross_spectrum(data: Dataset, y: str, x: str, bandwidth: int = 5, span: Any = None) -> CrossSpectrum

The cross-spectrum of y and x on their common sample, Daniell-smoothed.

date_cycles

date_cycles(data: Any, series: str | None = None, method: Literal['auto', 'bbq', 'bry_boschan'] = 'auto', detrend: Any = None, k: int | None = None, min_phase: int | None = None, min_cycle: int | None = None, ends: int | None = None, outliers: float | None = 3.5, short_window: int | None = None) -> CycleDating

Date the business cycle of series: its peaks and troughs, the phases between them and their statistics.

method: "bbq", Harding and Pagan's (2002) quarterly Bry-Boschan (local extremes of the series within k periods, then censoring); "bry_boschan", Bry and Boschan's (1971) monthly procedure (extreme values replaced, turning points found in a 12-month moving average and traced back through a Spencer curve and a short moving average to the series); "auto", Bry-Boschan for monthly data and BBQ otherwise. The rules default to the published ones: quarterly BBQ k = 2, phases of at least 2 and cycles of at least 5 quarters, no turning point within 2 quarters of the ends; monthly (either method) k = 5, phases of at least 5 and cycles of at least 15 months, none within 6 months of the ends; annual BBQ k = 1, phases of at least 1 and cycles of at least 2 years, none within a year of the ends. outliers: Bry-Boschan's replacement of values more than this many standard deviations from the Spencer curve (None: none replaced); short_window: the span of its short moving average (None: the months for cyclical dominance, 3 to 6).

detrend: date a growth cycle, the deviation from a trend, with a trend-cycle filter (HP(), Hamilton()...; or "hp", "hamilton", "baxter_king", "christiano_fitzgerald"); or give the filtered gap itself as series. data is a dataset (a panel is dated entity by entity) or a dated Series.

diffusion

diffusion(data: Dataset, variable: str, model: Literal['vasicek', 'cir', 'gbm'] = 'vasicek', dt: float = 1.0, span: Any = None) -> SeriesModel

A diffusion of variable observed every dt (in the time units of the parameters: 1/12 for monthly observations of annual rates) by exact maximum likelihood.

garch_in_mean

garch_in_mean(data: Dataset, variable: str, form: Literal['variance', 'sd', 'log'] | None = 'variance', span: Any = None) -> SeriesModel

A GARCH(1, 1)-in-mean model of variable by maximum likelihood with normal errors (form=None: an ordinary constant-mean GARCH).

gph

gph(data: Dataset, variable: str, power: float = 0.5, span: Any = None) -> Any

Geweke and Porter-Hudak's log-periodogram estimate of d, from the first T^power Fourier frequencies.

gregory_hansen

gregory_hansen(data: Dataset, outcome: str, regressors: Sequence[str], model: Literal['level', 'trend', 'regime'] = 'level', lags: int = 1, trim: float = 0.15, draws: int = 500, seed: int = 0, span: Any = None, where: str | None = None) -> Any

Gregory and Hansen's test of no cointegration against cointegration with one break at an unknown date: a level shift, a level shift with a trend, or a regime shift (level and slopes).

inar

inar(data: Dataset, variable: str, span: Any = None) -> SeriesModel

INAR(1) with Poisson innovations by maximum likelihood, from conditional least squares.

intervention

intervention(kind: Literal['pulse', 'step', 'ramp', 'temporary', 'seasonal_pulse'], date: Any, index: Any, decay: float | None = None, end: Any = None) -> Series

An intervention regressor on the periods index (a PeriodIndex, or a Dataset's dates): pulse (1 at date), step (1 from date on), ramp (1, 2, 3... from date; to 1 at end if given), temporary (decay^k k periods after date) or seasonal_pulse. The same as the formula functions pulse("2024Q1") and the rest.

local_whittle

local_whittle(data: Dataset, variable: str, power: float = 0.65, span: Any = None) -> Any

Robinson's local Whittle estimate of d, from the first T^power Fourier frequencies.

nonparametric_autoregression

nonparametric_autoregression(data: Dataset, variable: str, lags: int = 1, kind: Literal['ll', 'lc'] = 'll', bandwidth: Any = 'cv', span: Any = None) -> KernelRegression

E[y_t | y_{t-1}, ..., y_{t-lags}] by kernel regression: a nonlinear autoregression with no functional form.

periodogram

periodogram(data: Dataset, variable: str, span: Any = None) -> Spectrum

The periodogram of variable at the Fourier frequencies.

poisson_autoregression

poisson_autoregression(data: Dataset, variable: str, feedback: bool = True, span: Any = None) -> SeriesModel

The Poisson autoregression y_t | past ~ Poisson(lambda_t), lambda_t = omega + a y_{t-1} + b lambda_{t-1} (feedback=False: b = 0), by maximum likelihood; a + b < 1 for stationarity.

pymetrix.statespace.kalman_filter

kalman_filter(y: ndarray, m: SystemMatrices, a0: ndarray, P0: ndarray, burn: int = 0) -> KalmanOutput

The Kalman filter. Rows of y are periods; NaN entries are unobserved (handled exactly).

Once the predicted state variance stops changing (to _RICCATI_TOL, relative) in a period with every series observed, the gain and innovation variance are constant: later fully observed periods update only the mean, as Dynare does with riccati_tol. A period with a missing observation goes back to the full recursion.

pymetrix.statespace.kalman_smoother

kalman_smoother(kf: KalmanOutput, m: SystemMatrices) -> tuple[ndarray, ndarray]

Fixed-interval (Rauch-Tung-Striebel) smoother: states and variances given all the data.

semiparametric_garch

semiparametric_garch(data: Dataset, variable: str, bandwidth: Any = 'silverman', rounds: int = 2, draws: int = 0, seed: int = 0, span: Any = None) -> SemiparametricGARCH

GARCH(1, 1) for variable (a constant mean) by Gaussian QML, then re-estimated rounds times by maximising the likelihood with the standardised shocks' kernel density in place of the normal (Engle and Gonzalez-Rivera 1991). Standard errors need draws: a bootstrap simulating the fitted GARCH with resampled standardised shocks (the Hessian with the density held fixed understates them badly).

spectrum

spectrum(data: Dataset, variable: str, bandwidth: int = 5, span: Any = None) -> Spectrum

The spectral density of variable: the periodogram smoothed by a Daniell window of 2 bandwidth + 1 ordinates.

terasvirta

terasvirta(data: Dataset, series: str, lags: int = 1, delay: int = 1, span: Any = None) -> Any

Teräsvirta's (1994) LM test of linearity against a smooth-transition AR: regress the AR(lags) residuals on the lags, and the lags times y_(t-d), y_(t-d)^2 and y_(t-d)^3 (a third-order expansion of the transition); F test of the added terms.

Results

CointegratingRegression dataclass

CointegratingRegression(method: str, y_name: str, names: tuple[str, ...], params: ndarray, cov: ndarray, resid: Series, long_run_variance: float = 0.0, bandwidth: float = 0.0, leads: int | None = None, lags: int | None = None, r2: float = 0.0, bandwidth_rule: str = 'newey-west', provenance: Any = None)

A cointegrating regression estimated by FMOLS, CCR or DOLS.

CrossSpectrum dataclass

CrossSpectrum(x: str, y: str, frequency: ndarray, fxx: ndarray, fyy: ndarray, fxy: ndarray, bandwidth: int, provenance: Any = None)

The cross-spectrum of two series: coherence, phase and gain by frequency.

CycleDating dataclass

CycleDating(values: Series, turns: DataFrame, phases: Series, method: str, settings: Mapping[str, Any], label: str = '', detrend: str = '', panel: bool = False, phase_frame: DataFrame = DataFrame(), provenance: Any = None)

Business-cycle turning points: turns (one row per peak or trough: its period, type and value, and the entity in a panel), the values dated (the series, or its deviation from trend for a growth cycle), phases (1 in recession, from the period after a peak through the trough), the method and its settings, and Harding and Pagan's statistics of each complete phase (phase_frame) and on average (statistics).

peaks property

peaks: Index

The peaks' periods (in a panel, (entity, period) pairs).

troughs property

troughs: Index

The troughs' periods (in a panel, (entity, period) pairs).

spans

spans(entity: Any = None) -> tuple[tuple[str, str, str], ...]

The recessions as (first period, last period, label), the form figures shade: from the period after each peak through the trough (or the end of the data).

statistics

statistics() -> DataFrame

Harding and Pagan's averages over the complete phases: the number of phases, their mean duration, amplitude, cumulative movement, excess and steepness, for expansions and recessions.

table

table() -> Table

The turning points, with the periods since the one before.

concordance

concordance(other: Any = None, lags: int | None = None) -> Any

Harding and Pagan's concordance with another dating (or 0/1 phase series), with their test; in a panel without other, the concordance index of each pair of entities.

plot

plot(entity: Any = None) -> Figure

The series dated, its recessions shaded and its peaks and troughs marked (in a panel, one entity's: the first by default).

FittedARDL dataclass

FittedARDL(spec: ARDL, params: Any, inference: DataFrame, resid: Series, fitted: Series, stats: Mapping[str, float], long_run_coefficients: DataFrame | None, ecm_params: Any, ecm_inference: DataFrame | None, order: tuple[int, dict[str, int]], dependent: str, bounds: Any = None, ecm_problem: str = '', freq: str = '', provenance: Any = None, backend_result: Any = None, backend_model: Any = None)

Bases: BackendResult

An estimated ARDL: its own fields hold every number it reports, read from statsmodels when it is made.

Parameter names are pymetrix expressions: c[-1] (statsmodels' c.L1), y (y.L0) and, in the error-correction form, d(y)[-1] (D.y.L1); the old names still work in params[...], with a warning.

from_statsmodels classmethod

from_statsmodels(spec: ARDL, model: Any, result: Any, freq: str) -> FittedARDL

Read everything the result reports from statsmodels' ARDL model and results, once.

long_run

long_run() -> Table

Long-run multipliers: the level relationship y = sum of coefficients x regressors (and constant).

ecm

ecm() -> Table

The error-correction form: differences on lagged levels (the speed of adjustment) and lagged differences.

bounds_test

bounds_test(case: int | None = None) -> TestResult

Pesaran-Shin-Smith bounds F test of no level relationship. Case 3 (unrestricted constant) with a constant, case 5 with a trend, case 1 with neither; or give case (1 to 5).

FittedARFIMA dataclass

FittedARFIMA(variable: str, p: int, q: int, params: ndarray, cov: ndarray, mean: float = 0.0, sigma2: float = 0.0, nobs: int = 0, resid: Series = None, provenance: Any = None)

FittedExponentialSmoothing dataclass

FittedExponentialSmoothing(spec: ExponentialSmoothing, result: Any, data: Series, provenance: Any = None)

Bases: BackendResult

An estimated exponential smoothing model: its parameters, states, fit and forecasts.

backend_result property

backend_result: Any

The library's own result object (result).

fitted property

fitted: Series

One-step-ahead fitted values.

resid property

resid: Series

The series less its one-step-ahead fitted values.

states property

states: DataFrame

The level, trend and seasonal states at the end of each period.

stats property

stats: dict[str, float]

Fit statistics, in pymetrix's definitions (estimation.criteria): the information criteria count the estimated parameters; statsmodels' own, which also count the error variance, are kept as *_backend.

forecast

forecast(data: Any = None, span: tuple[Any, Any] | None = None, coverage: float = 0.95, dynamic: bool = True, horizon: int | None = None) -> Any

Forecasts after the end of the sample, for the periods of span (or the next horizon periods), with standard errors and a (coverage) interval. Columns: forecast, se, lower, upper, and actual where data has the series.

plot

plot() -> Any

The series, its one-step-ahead fit and the level.

FittedLocalProjection dataclass

FittedLocalProjection(spec: LocalProjection, fits: Results, irf: DataFrame, alpha: float, bootstrap: Any = None)

Local-projection impulse responses: irf (by horizon) and the regressions behind them (fits).

provenance property

provenance: Any

The provenance of the first horizon's regression (all use the same data), as a local projection.

plot

plot() -> Any

The responses with 68% and wide bands (one panel per state when state-dependent).

FittedMarkovSwitching dataclass

FittedMarkovSwitching(spec: MarkovSwitching, params: Any, inference: DataFrame, smoothed: DataFrame, filtered: DataFrame, transition: DataFrame, durations: Series, endog: Series, stats: Mapping[str, float], freq: str = '', regressors: tuple[str, ...] = (), provenance: Any = None, backend_result: Any = None, backend_model: Any = None)

Bases: BackendResult

An estimated Markov-switching model: its own fields hold every number it reports, read from statsmodels when it is made. Parameter names keep statsmodels' regime suffix (const[0]) with pymetrix's terms: the regressors' own names for x1, x2, ... and g[-1] for ar.L1.

names property

names: list[str]

Parameter names, with statsmodels' x1, x2, ... replaced by the regressors' own names.

probabilities

probabilities(kind: str = 'smoothed') -> DataFrame

The probability of each regime in each period: smoothed (all data) or filtered (data to then).

plot

plot() -> Any

The series, and the smoothed probability of each regime.

FittedSARIMA dataclass

FittedSARIMA(spec: SARIMA, result: Any, data: Series, season: int = 0, provenance: Any = None)

Bases: BackendResult

An estimated seasonal ARIMA: its parameters, fit and forecasts.

fitted property

fitted: Series

One-step-ahead predictions (the first periods, before the differences are known, are rough).

resid property

resid: Series

One-step-ahead forecast errors.

forecast

forecast(data: Any = None, span: tuple[Any, Any] | None = None, coverage: float = 0.95, dynamic: bool = True, horizon: int | None = None) -> Any

Forecasts after the end of the sample, for the periods of span (or the next horizon periods), with standard errors and a (coverage) interval. With regressors, their values for the forecast periods come from data.

plot

plot() -> Any

The series and its one-step-ahead fit.

FittedSmoothLocalProjection dataclass

FittedSmoothLocalProjection(spec: Any, irf: DataFrame, penalty: float, order: int, nobs: int, cv: Series | None = None, provenance: Any = None)

A smooth local projection: the response by horizon with standard errors, and the penalty.

FittedSmoothTransitionAR dataclass

FittedSmoothTransitionAR(spec: SmoothTransitionAR, data: Series, delay: int = 1, gamma: float = 1.0, c: float = 0.0, scale: float = 1.0, phi1: ndarray = (lambda: zeros(0))(), phi2: ndarray = (lambda: zeros(0))(), cov: ndarray = (lambda: zeros((0, 0)))(), sigma2: float = 0.0, ssr: float = 0.0, ssr_linear: float = 0.0, index: Any = None, switch: ndarray = (lambda: zeros(0))(), span: Any = None, converged: bool = True, provenance: Any = None)

An estimated smooth-transition autoregression.

params property

params: Any

The estimates as a PointEstimate: both regimes' coefficients ("G = 0: constant", "G = 1: y[-1]", ...), gamma and c, with their Gauss-Newton covariance.

transition_path

transition_path() -> Series

G(s_t) over the sample: the weight on the second regime in each period.

predictive_draws

predictive_draws(data: Dataset, span: tuple[Any, Any], draws: int | None = None, seed: int = 0) -> tuple[PeriodIndex, ndarray]

Simulated forecast paths (draws, periods, 1): each draw moves through the transition with its own shocks.

forecast

forecast(data: Dataset, span: tuple[Any, Any], coverage: float = 0.95, dynamic: bool = True, draws: int = 2000, seed: int = 0) -> Any

Forecasts by simulation: mean, sd and the coverage interval from the simulated quantiles.

girf

girf(shock: Any = None, size: Any = 1.0, history: Any = 'regimes', periods: int = 20, draws: int = 500, seed: int = 0, regime: str = 'evolve', bands: int = 0, coverage: float = 0.68) -> Any

Generalised impulse responses (Koop, Pesaran and Potter 1996), by simulation: E[y_(t+h) | shock, history] - E[y_(t+h) | history], averaged over each group of histories (history: "regimes", the default, for each regime's histories; "all"; a regime; a period such as "2008Q4"; or a list), for shocks of each size in standard deviations (e.g. (1, -1, 2), to see the asymmetry). regime="evolve" lets the regime move after the shock (through the simulated transition variable); "fixed" holds the regime it arrives in. draws paths from each history, bands draws of the parameters for coverage bands. See pymetrix.girf.

FittedStateSpace dataclass

FittedStateSpace(model: StateSpace, params: Any, values: dict[str, float], matrices: SystemMatrices, kalman: KalmanRun, filtered: Any, smoothed: Any, predicted: Any, y: ndarray, index: Index, stats: dict[str, float] = dict(), provenance: Provenance | None = None, axes: Any = None)

A filtered (and possibly estimated) state-space model.

smoothed and filtered are datasets of the states with standard errors (trend, trend_se, ...); predicted holds one-step-ahead predictions.

innovations

innovations() -> DataFrame

Standardised one-step-ahead prediction errors of the observed series (should look like white noise).

criteria

criteria(diffuse_terms: str | None = None) -> dict[str, float]

The log likelihood and the information criteria (AIC, BIC, Hannan-Quinn) at these parameter values, with the diffuse periods' terms included ("include", the exact diffuse likelihood of Durbin and Koopman) or left out ("exclude", statsmodels' default convention); None: as the fit was made. AIC and BIC equal stats' for the fit's own convention. Compare criteria across models only in one convention, and only between models with the same diffuse periods (see pymetrix.statespace).

forecast

forecast(data: Dataset, span: tuple[Any, Any], coverage: float = 0.95, dynamic: bool = True) -> Dataset

Forecasts of the observed series (and states) for the periods in span, with intervals.

The filter runs on the data up to the start of the span and on beyond it with the observations treated as missing, so forecasts condition on the data before the span.

plot

plot(which: Literal['smoothed', 'filtered'] = 'smoothed') -> Any

The estimated states with 95% bands: smoothed (two-sided) or filtered (real-time).

FittedSTLForecast dataclass

FittedSTLForecast(spec: STLForecast, result: Any, data: Series, season: int = 0, provenance: Any = None)

Bases: BackendResult

STL forecasting, estimated: the decomposition, the model of the adjusted series and forecasts.

components property

components: DataFrame

The STL decomposition: trend, seasonal and remainder, and the seasonally adjusted series.

forecast

forecast(data: Any = None, span: tuple[Any, Any] | None = None, coverage: float = 0.95, dynamic: bool = True, horizon: int | None = None) -> Any

Forecasts after the end of the sample; the interval is the adjusted series' model's (the seasonal part is taken as known).

FittedTheta dataclass

FittedTheta(spec: Theta, result: Any, data: Series, provenance: Any = None)

Bases: BackendResult

An estimated theta method: the trend slope (b0), the smoothing parameter (alpha) and forecasts.

forecast

forecast(data: Any = None, span: tuple[Any, Any] | None = None, coverage: float = 0.95, dynamic: bool = True, horizon: int | None = None) -> Any

Forecasts after the end of the sample, with intervals from the exponential smoothing's variance.

FittedThresholdAR dataclass

FittedThresholdAR(spec: ThresholdAR, data: Series, delay: int = 1, threshold: float = 0.0, low: ndarray = (lambda: zeros(0))(), high: ndarray = (lambda: zeros(0))(), cov_low: ndarray = (lambda: zeros((0, 0)))(), cov_high: ndarray = (lambda: zeros((0, 0)))(), sigma2: float = 0.0, ssr: float = 0.0, ssr_linear: float = 0.0, n_low: int = 0, n_high: int = 0, provenance: Any = None, span: Any = None)

An estimated two-regime threshold autoregression.

params property

params: Any

The coefficients of both regimes as a PointEstimate ("low: constant", "high: y[-1]", ...), with their covariance (the regimes' blocks; the threshold and delay are treated as known, as in summary()).

summary

summary() -> Table

The coefficients and standard errors in each regime, with the threshold, the delay and the fit.

linearity_test

linearity_test(draws: int = 500, seed: int = 0) -> Any

Hansen's (1996, 1997) test of the linear AR against the threshold model: sup-F over the thresholds (and delays, when chosen), F = n (SSR_linear - SSR_threshold) / SSR_threshold, with a fixed-regressor bootstrap p-value (the threshold is not identified under the null, so the usual F distribution does not apply).

predictive_draws

predictive_draws(data: Dataset, span: tuple[Any, Any], draws: int | None = None, seed: int = 0) -> tuple[PeriodIndex, ndarray]

Simulated forecast paths (draws, periods, 1) from the end of data before span: each draw follows the regimes with its own normal shocks, so multi-step forecasts reflect the nonlinearity.

forecast

forecast(data: Dataset, span: tuple[Any, Any], coverage: float = 0.95, dynamic: bool = True, draws: int = 2000, seed: int = 0) -> Any

Forecasts by simulation (draws paths): mean, sd and the coverage interval from the simulated quantiles. The one-step forecast is the regime's prediction, exactly.

girf

girf(shock: Any = None, size: Any = 1.0, history: Any = 'regimes', periods: int = 20, draws: int = 500, seed: int = 0, regime: str = 'evolve', bands: int = 0, coverage: float = 0.68) -> Any

Generalised impulse responses (Koop, Pesaran and Potter 1996), by simulation: E[y_(t+h) | shock, history] - E[y_(t+h) | history], averaged over each group of histories (history: "regimes", the default, for each regime's histories; "all"; a regime; a period such as "2008Q4"; or a list), for shocks of each size in standard deviations (e.g. (1, -1, 2), to see the asymmetry). regime="evolve" lets the regime move after the shock (through the simulated switching variable); "fixed" holds the regime it arrives in. draws paths from each history, bands draws of the parameters for coverage bands. See pymetrix.girf.

plot

plot() -> Any

The series, with the threshold.

FittedTransferFunction dataclass

FittedTransferFunction(spec: TransferFunction, result: Any, data: Series, season: int = 0, theta: ndarray = (lambda: zeros(0))(), cov: ndarray | None = None, raw: list[ndarray] = list(), presample: int = 0, periods: PeriodIndex | None = None, provenance: Any = None)

Bases: BackendResult

An estimated transfer-function model: its parameters (the omegas, deltas, ARIMA terms and variance), the effect of each input, the counterfactual, and forecasts.

gains

gains() -> Table

Each input's impact, decay, long-run gain omega(1) / delta(1) (the level a step of one settles at; for a pulse, its total effect over all periods), the half-life of a first-order decay, and the effect the input leaves for good (the gain for a step, none for a pulse or temporary).

effects

effects(horizon: int = 8, data: Any = None) -> DataFrame

The effect path over the sample and horizon forecast periods: each input's effect, the total, its permanent part (the long-run gain times a step or ramp input), its temporary part (the rest, which dies away) and the cumulative effect. From the first period with an effect.

counterfactual

counterfactual() -> Series

The series without the inputs' effects (its path had the interventions not happened).

forecast

forecast(data: Any = None, span: tuple[Any, Any] | None = None, coverage: float = 0.95, horizon: int | None = None) -> Any

Forecasts after the sample with standard errors and a (coverage) interval; the interventions' effects carry on as they unwind (effect column), and counterfactual is the forecast without them.

plot

plot(horizon: int = 8) -> Any

The series, its counterfactual without the interventions and the forecast (top); the effect, its permanent and temporary parts (bottom), into the forecast periods.

pymetrix.statespace.KalmanOutput dataclass

KalmanOutput(a_pred: ndarray, P_pred: ndarray, a_filt: ndarray, P_filt: ndarray, v: ndarray, F: ndarray, loglike_t: ndarray, burn: int)

Filter output by period: predicted (a[t] | y[..t-1]) and filtered (a[t] | y[..t]) states, innovations v and their variances F (NaN where unobserved), and log-likelihood terms.

pymetrix.statespace.SystemMatrices dataclass

SystemMatrices(states: tuple[str, ...], observables: tuple[str, ...], shocks: tuple[str, ...], T: ndarray, c: ndarray, R: ndarray, Q: ndarray, Z: ndarray, d: ndarray, H: ndarray, stationary: tuple[bool, ...] = ())

y[t] = d + Z a[t] + eps[t], a[t+1] = c + T a[t] + R eta[t]; eps ~ N(0, H), eta ~ N(0, Q).

start

start(mode: str = 'auto') -> tuple[ndarray, ndarray, ndarray]

The initial state: mean, variance of its known part, and which states are diffuse (unknown).

auto: declared-stationary states start from their stationary distribution and the others are diffuse; with none declared, all states are stationary if every root of T is inside the unit circle, and all are diffuse otherwise. stationary and diffuse force one or the other; scaled starts every state at zero with variance SCALED_VARIANCE (Dynare's lik_init=2).

initial

initial(mode: str = 'auto', scale: float = 1.0) -> tuple[ndarray, ndarray, int]

Initial mean and variance with diffuse states approximated by a large variance, and how many observations to leave out of the likelihood (the approximate start of the native filter).

Diffuse states start at zero with variance KAPPA * scale**2; scale is the size of the data (its largest absolute value), so the start is equally uninformative for any units.

SeriesModel dataclass

SeriesModel(model: str, variable: str, names: tuple[str, ...], values: ndarray, cov: ndarray, loglike: float = 0.0, nobs: int = 0, fitted: Series = None, notes: tuple[str, ...] = (), provenance: Any = None)

A count or duration time-series model estimated by maximum likelihood.

plot

plot() -> Any

The series and its conditional mean.

Spectrum dataclass

Spectrum(variable: str, frequency: ndarray, density: ndarray, bandwidth: int, nobs: int, provenance: Any = None)

A periodogram or smoothed spectral density by frequency.

StateSpaceSystem dataclass

StateSpaceSystem(states: tuple[str, ...], observables: tuple[str, ...], shocks: tuple[str, ...], T: ndarray, c: ndarray, R: ndarray, Q: ndarray, Z: ndarray, d: ndarray, H: ndarray, stationary: tuple[bool, ...] = (), measurement: Any = None, shock_sd: Mapping[str, float] = dict(), shock_corr: Mapping[tuple[str, str], float] = dict(), levels: Mapping[str, float] = dict(), variables: tuple[str, ...] = (), trend: ndarray | None = None, trend_lags: ndarray | None = None)

Bases: SystemMatrices

A solved model in state-space form, as a result: its matrices with names, the measurement equations linking it to data, and the shock sizes. filter estimates the model's variables from data (the Kalman smoother), in levels; loglike is the likelihood of the data, the basis of estimation.

Made by LinearSolution.system(measurement, shock_sd). States are the model's variables in deviations from the steady state, with lagged copies where the measurement equations use lags (y[-1]).

observations

observations(data: Dataset, span: Any = None) -> tuple[ndarray, Index]

The observed series as a matrix, in the order of the measurement equations.

filter

filter(data: Dataset, span: Any = None, tunes: Mapping[str, Any] | None = None, tune_sd: Mapping[str, Any] | None = None, shocks: bool = False) -> Dataset

The model's variables estimated from the data by the Kalman smoother, in levels, with each observed series as the model fits it (<series>_fitted).

tunes imposes judgement on model variables, observed or not: {"y_gap": {"2024Q4": -1.0}} (or a Series), each value treated as an exact observation of that variable in that period, so the filter moves everything else to be consistent with it (as IRIS's filter tunes do). A tune can be soft: give it a standard deviation, {"y_gap": {"2024Q4": (-1.0, 0.25)}} (or a list [-1.0, 0.25]) or tune_sd={"y_gap": {"2024Q4": 0.25}} (or one number for all of a variable's tunes); it is then an observation with that error, in its own period only. A standard deviation of None or 0 is exact, as before.

shocks=True adds the smoothed shocks e(t) of x(t) = P x(t-1) + Q e(t) as columns named after the shocks, in their own units, as a solution's paths carry them. They come from the smoothed state disturbances, so the shocks need not be states; e(0) is E[e(0) | y] through the states that start from their stationary distribution.

contributions

contributions(data: Dataset, span: Any = None, tunes: Mapping[str, Any] | None = None, horizon: int = 0, tune_sd: Mapping[str, Any] | None = None) -> Any

The Kalman-smoothed estimate of each model variable (deviation from its steady state) split into what each observed series contributed, each tune if any, and the starting point ("start"); with horizon, the forecast from the end of the data too. A Decomposition titled "Data contributions".

Given which values are missing, the smoother is linear in the data: a series' contribution is the smoother run with that series as observed and every other one at the value the model expects with no news (its steady state, on the growth path), less the smoother with all of them there. The parts add up to the smoothed path exactly, period by period; forecasts carry each part forward by the transition matrix.

loglike

loglike(data: Dataset, span: Any = None, diffuse_terms: str = 'include') -> float

The log likelihood of the observed series under the model (the Kalman filter). With diffuse states, diffuse_terms includes the diffuse periods' terms (the exact diffuse likelihood, the default) or leaves them out ("exclude", statsmodels' default convention): see pymetrix.statespace.

loglike_observed

loglike_observed(y: ndarray, index: Any, start: str = 'auto', presample: int = 0, diffuse_terms: str = 'include') -> float

The log likelihood of observations already taken from the data (observations): estimation takes them once and evaluates this many times. start is the filter's start (see SystemMatrices.start); presample periods are filtered but left out of the likelihood (Dynare's presample); diffuse_terms as in loglike.

needed

needed(start: str = 'auto') -> SystemMatrices

The system on the states the likelihood needs: those observed and those they depend on, as Dynare's kalman_algo restricts the state to the predetermined and observed variables. Exact for a stationary system (the others never reach an observation, and the stationary distribution of the rest is their own); a system with diffuse states is returned whole, since how many states start diffuse changes the likelihood.