ArimaRegressor

class flexparameterize.regression.arima.ArimaRegressor(order: tuple[int, int, int] | None = None, include_mean: bool = True, auto: bool = False, max_ar_persistence: float | None = 0.85, forecast_horizon: int | str | timedelta = 1, **auto_kwargs: object)

Fit regression with ARIMA errors and expose the shared fit protocol.

Either supply an explicit order, or set auto=True to search for one and refit the winning order with the direct least-squares backend.

Restriction: d may be 0 or 1 (the Pyomo surrogate’s mean ARIMA equation supports at most a single order of differencing), and the model is non-seasonal.

Fitting backend: scipy.optimize.least_squares minimizes the mean-equation residual directly. This is the exact objective the Pyomo surrogate implements, so fitted parameters reproduce the surrogate one-to-one.

Which beta is kept: the exogenous coefficients are estimated several times: by OLS for the auto differencing test and inside every auto candidate fit, by OLS as the warm start, jointly with the ARIMA terms in the one-step fit, and, when forecast_horizon > 1, again by the free-run refinement. Only the last of these is kept. It is the beta in coefficients and in the spec’s exog.<column> parameters, and the one the spec’s history eta = y - X @ beta is computed with.

Stability: AR coefficients are bounded to [-max_ar_persistence, max_ar_persistence] (default 0.85) during the fit itself, and fit() rejects a fitted AR block that is not stationary, which a per-coefficient bound alone does not prevent. The surrogate implements the mean equation as a difference equation, so a non-stationary AR block makes every forecast and optimization diverge.

Parameters:
  • order – (p, d, q) ARIMA order; required when auto is False. Must satisfy d in (0, 1).

  • include_mean – Whether to include the model’s deterministic term. This is a level intercept for d=0 and constant drift for d=1. Default True.

  • auto – If True, search for the order, then refit it at the configured forecast_horizon. d comes from KPSS (null: stationary) and ADF (null: unit root) tests at 5% on the disturbance y - X @ beta: 1 when only KPSS rejects, 0 when only ADF rejects, and an error when both or neither do, which passing d in auto_kwargs avoids. Every (p, q) within the limits is then fitted by one-step least squares and the lowest-AIC stationary, invertible candidate wins. Use auto_kwargs to restrict it.

  • max_ar_persistence – Bounds every AR coefficient to [-max_ar_persistence, max_ar_persistence] during the fit itself (via bounded least squares). Default 0.85. Set to None to leave the coefficients unbounded; the stationarity check still applies.

  • forecast_horizon – Length of the free-run windows whose error the fit minimizes: each window is seeded from actual data, then simulated forward with innovations at zero, as the surrogate forecasts. Either an int number of steps, or a duration ("2D", "48h", pd.Timedelta(days=2)) that fit() rounds up to whole steps of the training index. 1 (default) is the one-step (equation-error) fit using actual lagged values, as is any duration of one step or less. A longer horizon refines that fit against multi-step error, bounds the MA coefficients to [-0.99, 0.99], and rejects a non-invertible MA block. Set it to the horizon you will forecast over; very long windows make the objective flat and slow to solve.

  • **auto_kwargs – Order-search limits, only with auto=True: max_p and max_q (default 5), max_order (largest p + q, default 5), max_d (0 or 1, default 1), d (fix the differencing order instead of testing for it), and stationary (True forces d=0).

Raises:

FlexConfigError – If neither order nor auto=True is given; if d > 1; if auto_kwargs is given without auto=True, or holds an unknown or out-of-range option; if max_ar_persistence is not a number in (0, 1] or None; or if forecast_horizon is neither a positive int nor a positive duration.

property coefficients: dict[str, float] | None

The fitted parameters as a name -> value mapping.

Names match the coefficient registry of the ArimaSurrogate built from to_surrogate_spec(): intercept (d=0) or drift (d=1) when the model has a deterministic term, ar.L{j}, ma.L{j}, then exog.<column> for each exogenous input.

Returns:

The parameter map, or None before fit() is called.

fit(X: DataFrame, y: DataFrame, *, input_units: dict[str, str] | None = None, output_units: str | None = None) → ArimaRegressor

Fit an ARIMA model to y with optional exogenous regressors X.

Uses scipy.optimize.least_squares to minimize the mean-equation residual directly, so the fitted parameters exactly match the Pyomo surrogate. When auto=True, the order is searched for first (see the auto argument), then refitted. Of the several beta estimates made along the way, only the last is kept (see the class docstring).

X and y must be clean: no null values, and a shared DatetimeIndex that strictly increases at one constant step. The fitted lags and the surrogate’s dated history both assume that grid, so gaps must be imputed (or the data split) before fitting.

Parameters:
  • X – Zero or more exogenous-input columns. Pass an empty DataFrame for a pure ARIMA fit.

  • y – A one-column DataFrame holding the output.

  • input_units – Units of every fitted exogenous column, keyed by its column name. Defaults to {}. Recorded for to_surrogate_spec().

  • output_units – Units of the fitted output column. Defaults to "". Recorded for to_surrogate_spec().

Returns:

self, fitted.

Raises:
  • FlexConfigError – If auto must test for d and statsmodels (the [parameterize] extra) is not installed; if input_units is missing an entry for one of X’s columns; if auto finds no stationary, invertible candidate; if the fitted AR block is not stationary; or if a forecast_horizon > 1 fit’s MA block is not invertible.

  • FlexDataError – If X or y is not a DataFrame; if y does not hold exactly one column; if X and y lack a DatetimeIndex, hold a null value, or are not evenly spaced in time; if there are no rows; or if there are fewer than max(p, q) + d + k + 1 rows (where k is the number of fitted parameters), which would leave the fit rank-deficient. With auto=True, candidate orders needing more rows are skipped, and the error is raised only if none fits. Also if auto must choose d and the KPSS and ADF tests both reject or both fail to reject, or the series is too short to run ADF.

fit_diagnostics() → dict[str, float]

Return extended fit statistics.

All of them exclude the zero-padded leading lags, so n_samples here is the number of observations the mean equation defines, which is max(p, q) + d fewer than the regressor’s n_samples. ma_max_root is the largest MA root magnitude: below 1.0 the fitted MA block is invertible.

Returns:

Mapping of diagnostic name to value.

Raises:

FlexDataError – If fit() has not been called.

property fitted: bool

True once fit() has succeeded.

property forecast_horizon: int | Timedelta

The requested free-run window, as an int number of steps or a pd.Timedelta.

A duration is converted to steps on each fit(), from that fit’s time step; the steps used are fit_diagnostics()["forecast_horizon"]. 1 is the one-step (equation-error) fit.

property order: tuple[int, int, int] | None

The fitted (p, d, q) order, or None before fit().

to_fit_result() → FitResult

Return this fit as the shared FitResult shape.

The coefficient map is coefficients, holding the last beta estimated (see the class docstring).

Returns:

A FitResult carrying the model’s coefficients, metrics, sample count, and data window.

Raises:

FlexDataError – If fit() has not been called.

to_surrogate_spec(history_length='7D') → SurrogateSpec

Return the fit as a persistable arima SurrogateSpec.

Uses the input_units/output_units recorded by fit(). The spec is built by make_spec(), so it matches ArimaSurrogate’s contract. Its config holds:

  • order: the fitted (p, d, q).

  • deterministic: "intercept" (d=0) or "drift" (d=1) when the fit has a deterministic term, else None.

  • input_variables: all fitted exogenous variable names and units.

  • output_variables: the output variable name and its units.

  • history: start_date, time_step_seconds, and the disturbance/innovation series the surrogate replays to seed its pre-horizon lags, covering the last history_length of the training data plus the max(p + d, q) lags ahead of it. When the window reaches the start of the series, where no true pre-sample data exists, those lags repeat the start of the series.

Its parameters are coefficients, all fixed, named as arima_parameter_names() names them: the deterministic term (if any), ar.L1 to ar.Lp, ma.L1 to ma.Lq, and one exog.<column> per exogenous column. The exog values are the last beta the fit estimated (see the class docstring).

A surrogate built from the spec can start its horizon anywhere from the first kept point onward; a start after the training data is forecast from the terminal state with zero innovations.

Parameters:

history_length – How much of the training history to keep: a duration ("7D", pd.Timedelta(days=7)), 0 to keep only the terminal state for forecast-only use, or None for the full training series. Rounded up to whole steps and capped at the training length.

Returns:

A SurrogateSpec of type SurrogateType.ARIMA.

Raises:
  • FlexDataError – If fit() has not been called.

  • FlexConfigError – If input_units is missing an entry for a fitted exogenous column, or history_length is invalid.