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 setauto=Trueto search for one and refit the winning order with the direct least-squares backend.Restriction:
dmay be0or1(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_squaresminimizes 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
autodifferencing test and inside everyautocandidate fit, by OLS as the warm start, jointly with the ARIMA terms in the one-step fit, and, whenforecast_horizon > 1, again by the free-run refinement. Only the last of these is kept. It is the beta incoefficientsand in the spec’sexog.<column>parameters, and the one the spec’s historyeta = y - X @ betais computed with.Stability: AR coefficients are bounded to
[-max_ar_persistence, max_ar_persistence](default 0.85) during the fit itself, andfit()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 whenautoisFalse. Must satisfyd in (0, 1).include_mean – Whether to include the model’s deterministic term. This is a level intercept for
d=0and constant drift ford=1. DefaultTrue.auto – If
True, search for the order, then refit it at the configuredforecast_horizon.dcomes from KPSS (null: stationary) and ADF (null: unit root) tests at 5% on the disturbancey - X @ beta: 1 when only KPSS rejects, 0 when only ADF rejects, and an error when both or neither do, which passingdinauto_kwargsavoids. Every(p, q)within the limits is then fitted by one-step least squares and the lowest-AIC stationary, invertible candidate wins. Useauto_kwargsto restrict it.max_ar_persistence – Bounds every AR coefficient to
[-max_ar_persistence, max_ar_persistence]during the fit itself (via bounded least squares). Default0.85. Set toNoneto 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)) thatfit()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_pandmax_q(default 5),max_order(largestp + q, default 5),max_d(0 or 1, default 1),d(fix the differencing order instead of testing for it), andstationary(Trueforcesd=0).
- Raises:
FlexConfigError – If neither
ordernorauto=Trueis given; ifd > 1; ifauto_kwargsis given withoutauto=True, or holds an unknown or out-of-range option; ifmax_ar_persistenceis not a number in(0, 1]orNone; or ifforecast_horizonis 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
ArimaSurrogatebuilt fromto_surrogate_spec():intercept(d=0) ordrift(d=1) when the model has a deterministic term,ar.L{j},ma.L{j}, thenexog.<column>for each exogenous input.- Returns:
The parameter map, or
Nonebeforefit()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
ywith optional exogenous regressorsX.Uses
scipy.optimize.least_squaresto minimize the mean-equation residual directly, so the fitted parameters exactly match the Pyomo surrogate. Whenauto=True, the order is searched for first (see theautoargument), then refitted. Of the severalbetaestimates made along the way, only the last is kept (see the class docstring).Xandymust be clean: no null values, and a sharedDatetimeIndexthat 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
DataFramefor a pure ARIMA fit.y – A one-column
DataFrameholding the output.input_units – Units of every fitted exogenous column, keyed by its column name. Defaults to
{}. Recorded forto_surrogate_spec().output_units – Units of the fitted output column. Defaults to
"". Recorded forto_surrogate_spec().
- Returns:
self, fitted.- Raises:
FlexConfigError – If
automust test fordand statsmodels (the[parameterize]extra) is not installed; ifinput_unitsis missing an entry for one ofX’s columns; ifautofinds no stationary, invertible candidate; if the fitted AR block is not stationary; or if aforecast_horizon > 1fit’s MA block is not invertible.FlexDataError – If
Xoryis not aDataFrame; ifydoes not hold exactly one column; ifXandylack aDatetimeIndex, hold a null value, or are not evenly spaced in time; if there are no rows; or if there are fewer thanmax(p, q) + d + k + 1rows (wherekis the number of fitted parameters), which would leave the fit rank-deficient. Withauto=True, candidate orders needing more rows are skipped, and the error is raised only if none fits. Also ifautomust choosedand 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_sampleshere is the number of observations the mean equation defines, which ismax(p, q) + dfewer than the regressor’sn_samples.ma_max_rootis 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 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 arefit_diagnostics()["forecast_horizon"].1is the one-step (equation-error) fit.
- to_fit_result() FitResult¶
Return this fit as the shared
FitResultshape.The coefficient map is
coefficients, holding the lastbetaestimated (see the class docstring).- Returns:
A
FitResultcarrying 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
arimaSurrogateSpec.Uses the
input_units/output_unitsrecorded byfit(). The spec is built bymake_spec(), so it matchesArimaSurrogate’s contract. Itsconfigholds:order: the fitted(p, d, q).deterministic:"intercept"(d=0) or"drift"(d=1) when the fit has a deterministic term, elseNone.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 lasthistory_lengthof the training data plus themax(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
parametersarecoefficients, all fixed, named asarima_parameter_names()names them: the deterministic term (if any),ar.L1toar.Lp,ma.L1toma.Lq, and oneexog.<column>per exogenous column. Theexogvalues are the lastbetathe 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)),0to keep only the terminal state for forecast-only use, orNonefor the full training series. Rounded up to whole steps and capped at the training length.- Returns:
A
SurrogateSpecof typeSurrogateType.ARIMA.- Raises:
FlexDataError – If
fit()has not been called.FlexConfigError – If
input_unitsis missing an entry for a fitted exogenous column, orhistory_lengthis invalid.