Skip to content

Multistep

polars_ts.models.multistep

Multi-step forecasting strategies: recursive and direct.

Implements model-agnostic wrappers for multi-step-ahead forecasting from Ch 18 of "Modern Time Series Forecasting with Python" (2nd Ed.).

Estimator

Bases: Protocol

Minimal interface for a scikit-learn-compatible estimator.

RecursiveForecaster

Recursive multi-step forecaster.

Train a single 1-step-ahead model. At prediction time, feed each prediction back as input to generate the next step, up to horizon h.

Parameters

estimator A scikit-learn-compatible estimator with fit and predict. lags Lag offsets used as features (e.g. [1, 2, 7]). target_col Column with the target values. id_col Column identifying each time series. time_col Column with timestamps for ordering.

fit(df)

Fit the estimator on lag features derived from df.

All series are pooled together for a single global model.

Parameters

df Training DataFrame with at least id_col, time_col, and target_col.

Returns

RecursiveForecaster Fitted forecaster (self).

predict(df, h)

Generate h-step-ahead forecasts by recursive prediction.

Parameters

df DataFrame containing the history to predict from. h Forecast horizon (number of steps ahead).

Returns

pl.DataFrame DataFrame with columns [id_col, time_col, "y_hat"].

DirectForecaster

Direct multi-step forecaster.

Train h separate models, one per forecast horizon step.

Parameters

estimator_factory Callable that returns a fresh estimator instance. Called h times. Example: lambda: LinearRegression(). lags Lag offsets used as features. h Forecast horizon. Determines how many models are trained. target_col Column with the target values. id_col Column identifying each time series. time_col Column with timestamps for ordering.

fit(df)

Fit h models, where model k predicts the value k steps ahead.

Parameters

df Training DataFrame.

Returns

DirectForecaster Fitted forecaster (self).

predict(df)

Generate forecasts for horizons 1 through h.

Each fitted model predicts its horizon from the last available observation's lag features. No recursive feeding is needed.

Parameters

df DataFrame containing the history to predict from.

Returns

pl.DataFrame DataFrame with columns [id_col, time_col, "y_hat"].

_build_lag_matrix(values, lags)

Build feature matrix and target vector from a value sequence.

Parameters

values Ordered list of target values. lags Lag offsets (positive integers). For each row t, feature i is values[t - lags[i]].

Returns

X : np.ndarray Feature matrix of shape (n_valid_rows, len(lags)). y : np.ndarray Target vector of shape (n_valid_rows,).