Skip to content

API Reference

scripts/generate_api_docs.py builds this page from the package's __all__ declarations. Zensical renders each public object from the current source.

Core API

forecast_realtime.RealTimeModel

A class for producing real-time forecasts.

__init__(data, models: ForecastModel | list[ForecastModel] = None)

Initialise RealTimeModel with a ForecastData object.

Parameters:

Name Type Description Default
data

ForecastData An instance of the ForecastData class

required
models

ForecastModel or list[ForecastModel] A single forecasting model or a list of models. Labels come from each model's label attribute, or from its class name when no label is set. Labels become the source in forecasts.

required

forecast(y_variables: list[str], step_frequency: str | None = None, data_transformation: dict[str, str] | None = None, label: str | None = None, steps: int = 1, first_forecast_horizon: dict[str, int] | int | None = None, X_variables: list[str] | None = None, y_steps_ahead: dict[str, int | None] | None = None, y_sources: dict[str, str] | None = None, X_steps_ahead: dict[str, int | None] | None = None, X_sources: dict[str, str] | None = None, y_lags: int = 0, X_lags: int | dict = 0, dummies: list | dict | None = None, first_vintage: str | None = None, last_vintage: str | None = None, reconstruct_levels: bool = True, parallel: bool = False, batch_size: int | None = None, max_workers: int | None = None, decomp: bool = False, X_imputation: str | None = None, drop_transformation_nans: bool = True, *, quantiles: bool | list[float] = False, **kwargs)

Produce forecasts in real-time.

Parameters:

Name Type Description Default
y_variables

List[str] The labels of the variable(s) to include in y. Must be a subset of the variables in the ForecastData object.

required
step_frequency

str | None, optional The frequency used for forecast steps (e.g. "M" for monthly, "Q" for quarterly). When omitted, it is inferred from the selected y variables. It must be provided when those variables have mixed or ambiguous frequencies.

required
data_transformation

dict[str, str] | None, optional A dictionary mapping each variable to the type of data transformation to apply before forecasting. The values must be one of "levels", "pop", "yoy", "logs", "log diff" or "diff". Used only as a fallback for models that have no model-owned data_transformation; may be omitted (default None) when every model's own pipeline covers all requested y/X variables. Any model without a pipeline that covers its own variables raises a clear error naming that model.

required
label

str | None, optional Extra label to name the forecast on top of each model's label attribute.

required
steps

int >= 1, optional The number of steps ahead to forecast. If None, no conditioning is applied.

required
first_forecast_horizon

dict[str, int] | int | None, optional The first target period to return, measured from the vintage period. At the selected frequency, the horizon is target period - vintage period: 0 is the vintage period, -1 is one period before it, and 1 is one period after it.

If None, the model is fitted through the latest period for which all selected y variables have observations in that vintage, and forecasting starts in the next period. If several y variables are selected, the one with the shortest available history therefore sets this default starting point.

If an int, the same horizon is used for every y variable. If a dict, it maps each y variable to its own first returned horizon. The model still uses one fitting cutoff for all y variables, set by the smallest value in the dict; returned rows are then filtered using each variable's own value.

required
X_variables

List[str] | None, optional The labels of the variable(s) to include in X. Must be a subset of the variables in the ForecastData object.

required
y_steps_ahead

dict[str, int | None] | None, optional A dictionary mapping y variable names to the number of forecast steps ahead to use as conditioning paths. Values are zero-based horizons in 0..steps-1 or None. Keys must be a subset of y_variables.

required
y_sources

dict[str, str] | None, optional Source of the forecasts to use for conditioning. Keys must match y_steps_ahead keys.

required
X_steps_ahead

dict[str, int | None] | None, optional A dictionary mapping X variable names to the number of forecast steps ahead to use as regressor forecasts. Values are zero-based horizons in 0..steps-1 or None. Keys must be a subset of X_variables.

required
X_sources

dict[str, str] | None, optional Source of the forecasts to use for X regressors. Keys must match X_steps_ahead keys.

required
first_vintage

str, optional The first vintage to use for forecasting. Defaults to None, which means the earliest vintage in the data will be used.

required
last_vintage

str, optional The last vintage to use for forecasting. Defaults to None, which means the latest vintage in the data will be used.

required
y_lags

int, optional Number of autoregressive lags of y to append to X before fitting. When provided, overrides any y_lags set on the model itself. Default 0 (no lags).

required
X_lags

int or dict[str, int], optional Lags of X to append before fitting. An int applies the same lag count to every X column; a dict maps each column name to its lag count. When provided, overrides any X_lags set on the model itself. Default 0 (no lags).

required
dummies

list or dict, optional Outlier (point) dummies appended to the design matrix at fit and forecast time. Either a list of dates (each becomes a 0/1 column that is 1 only on that date) or a dict mapping a chosen column name to a date. Being deterministic functions of the date index, they need no imputation over the forecast horizon. Default None.

required
reconstruct_levels

bool, optional If True (default), reconstruct levels from logs / log diff / diff forecasts when the underlying levels series is available in the outturns. Set to False to skip the reconstruction step; native "diff"/"log diff"/"logs" forecast rows, which ForecastData cannot store directly, are then preserved on self.native_forecasts instead of being dropped.

required
parallel

bool, optional Parallelisation strategy: - False (default): sequential execution over models - True: parallelise with ProcessPoolExecutor across (model, vintage_batch) combinations for full 2D scaling.

required
batch_size

int | None, optional Number of vintages per worker task. If None (default), computed as ceil(len(vintages) / num_workers) for optimal load balancing. Tune manually for specific hardware/data.

required
max_workers

int | None, optional Max worker processes for ProcessPoolExecutor (None = all CPUs).

required
decomp

bool, optional If True, collect decomposition rows from models and augment with metadata. Stored in self.decompositions. Default False.

required
X_imputation

str or None, optional Strategy used to fill missing future regressor values when the provided X has fewer rows ahead than steps. This is applied only for models whose _needs_ragged_edge_imputation attribute is True. Models that set it to False handle their own ragged edge, so this option is not applied to them. - None (default): no imputation (X is passed through as-is) - "zero" : fill with 0 - "last" : repeat the last observed value (random-walk) - "mean" : fill with the in-sample column mean - "ar1_t" : simulate from an AR(1) fit with Student-t errors

required
drop_transformation_nans

bool, optional If True (default), drop the undefined prefix produced by calendar-dependent transformations such as pop, yoy, diff and log diff. Interior missing observations are preserved. Set to False to keep the undefined prefix.

required
quantiles

bool | list[float], optional False returns point forecasts. True selects (0.16, 0.5, 0.84); a sequence selects distinct probabilities between zero and one. Store only native-metric quantiles in self.quantiles and disable level reconstruction. Decomposition is unavailable. Quantile runs leave earlier point forecasts in self.data unchanged; point runs accumulate forecasts there.

required
**kwargs

dict Additional keyword arguments to pass.

required

forecast_realtime.ForecastModel

Bases: ABC

Abstract base class for forecast models.

Subclasses implement _fit and _forecast; the public fit and forecast handle validation, lag/dummy construction and output shaping.

Forecast date contract ~~~~~~~~~~~~~~~~~~~~~~ _forecast may return an (steps, n_vars) array-like, which :meth:_wrap_forecast labels with the next steps periods after the effective fitting origin. Models anchored elsewhere must return a DataFrame with their own DatetimeIndex whose dates are strictly after that origin. RealTimeModel derives horizons from these dates, so wrong dates give wrong horizons.

Data transformation configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ data_transformation is an optional, model-owned mapping (constructor argument or assignable property). RealTimeModel.forecast() resolves one transformation per model, preferring this setting when set and falling back to the call-level mapping otherwise.

Ragged-edge regressor handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _needs_ragged_edge_imputation defaults to True. When it is True, the X_imputation option supplied to fit() or forecast() can be applied to missing future regressor values. Models that handle their own ragged edge should set it to False; the framework then leaves X unchanged and does not apply X_imputation.

data_transformation: dict[str, str] | None property writable

Optional model-owned variable-to-metric transformation mapping.

Resolved per-model by RealTimeModel.forecast(), which prefers this setting when set and falls back to its call-level mapping.

conditioning property

Immutable conditioning policy; direct forecasts use supplied frames instead.

fitted_values: pd.Series | pd.DataFrame property

In-sample fitted values produced during fit().

Returns

pd.Series | pd.DataFrame The in-sample fitted values stored on self.fitted_values_ by the subclass's _fit() implementation.

Raises

AttributeError If the model has not been fitted yet (or the subclass does not populate fitted_values_).

__init__(label: str | None = None, formula: str | None = None, data_transformation: dict[str, str] | None = None, align_start_dates: bool = False, conditioning: dict | None = None)

Configure input selection, transformation and conditioning.

Parameters

label : str | None Forecast label. Defaults to the class name. formula : str | None Variable selection, e.g. "cpisa ~ gdpkp + unemp". None uses all supplied y and X variables. data_transformation : dict[str, str] | None Model-owned variable-to-metric mapping, preferred over the run fallback. align_start_dates : bool Align input series to their latest common starting date. conditioning : dict | None Sources and positive durations by role and variable. None inherits the run fallback; an empty mapping disables it. Direct forecasts use supplied frames independently of this policy.

resolve_target_variables(y_variables: list[str]) -> list[str]

Return the requested variables this model treats as targets.

input_requirements(y_variables, X_variables=None, data_transformation=None) -> tuple[ModelInputRequirements, ...]

Report every formula-selected input, including implicit levels requests.

resolve_input_data_transformation(data_transformation: dict[str, str] | None = None, *, y_variables: list[str] | None = None, X_variables: list[str] | None = None) -> DataTransformationPipeline | None

Resolve the model input pipeline, preserving None to represent the identity transformation.

A model-owned pipeline takes precedence over the call-level fallback. When neither is configured, raw levels are the identity input. If variables are supplied, the resolved mapping is validated against the model input roles using the same coverage rules as the pipeline.

native_metric_mapping(target_variables: list[str] | None = None) -> dict[str, str]

Return the metric space used by the fitted target outputs.

fit(y: pd.DataFrame, X: pd.DataFrame | None = None, y_lags: int = 0, X_lags: int | dict = 0, dummies: list | dict | None = None, data_transformation: dict[str, str] | None = None, frequency: str | None = None, X_imputation: str | None = None, input_frequencies: dict[str, str] | None = None, y_input_metrics: dict[str, str] | None = None, X_input_metrics: dict[str, str] | None = None, drop_transformation_nans: bool = True, **kwargs)

Fit the model and return self after successful estimation.

forecast(steps: int = 1, X: pd.DataFrame | None = None, y: pd.DataFrame | None = None, decomp: bool = False, data_transformation: dict[str, str] | None = None, frequency: str | None = None, X_imputation: str | None = None, context: ForecastContext | None = None, *, quantiles: bool | list[float] = False, **kwargs) -> ForecastResult

Return long point forecasts, or native-metric quantiles when requested.

Extend models through _forecast(), not by replacing this orchestration. Point hooks remain arrays or wide tables; ForecastResult validates output.

forecast_realtime.ForecastContext dataclass

Raw fitted history and future paths for one prediction request.

y_conditioning: pd.DataFrame | None = None class-attribute instance-attribute

Raw explicit target constraints, never merged with published observations.

y_published: pd.DataFrame | None = None class-attribute instance-attribute

Published target observations after the fitted history.

y_published_input_metrics: dict[str, str] | None = None class-attribute instance-attribute

Input units of published targets, independent of explicit constraint units.

forecast_realtime.ForecastResult

Bases: DataFrame

Long forecast table with origin and decomposition metadata.

Point results contain date, variable and value. Quantile results also contain quantile before value. Rows use a RangeIndex and follow date, fitted target and ascending probability order; steps count dates.

Construction validates and orders the forecast against explicit expectations. Slices and copies are ordinary DataFrames without result metadata. Validation does not protect against later mutation of the result.

forecast: pd.DataFrame property

Return the forecast values without result metadata.

forecast_realtime.ForecastTree

Bases: ForecastModel

Forecast model that produces the root output of a TreeNode tree.

Every leaf is fitted on the shared raw y/X (**kwargs forwarded to each leaf's fit()), and each node's output is produced bottom-up by its transform. Intermediate forecasts are kept on the instance for inspection: leaf_forecasts_ (by leaf label) and node_forecasts_ (by node name).

Parameters

spec : TreeNode The (possibly nested) tree describing which models to fit and how each node's output is produced. A callable node's target (see TreeNode) selects the column it reduces its children to. label : str | None Label for this model instance; passed through to ForecastModel. data_transformation : dict[str, str] | None Optional tree-owned transformation configuration, accepting the same values as ForecastModel. Used as the fallback data_transformation for every leaf/nested tree that has no model-owned data_transformation of its own; a leaf's/nested tree's own pipeline still takes precedence, and a nested tree resolves this same fallback rule recursively for its own leaves/children. The call-level data_transformation passed to fit()/forecast() is used only where neither this tree nor any nearer ancestor tree owns a pipeline. conditioning : dict | None Conditioning policy for raw X inputs and root-only target constraints.

forecast(steps: int = 1, X: pd.DataFrame | None = None, y: pd.DataFrame | None = None, decomp: bool = False, context: ForecastContext | None = None, **kwargs) -> ForecastResult

Retain the tree's positional context on the shared forecast path.

native_metric_mapping(target_variables: list[str] | None = None) -> dict[str, str]

Return the metric space used by the fitted root output.

resolve_target_variables(y_variables: list[str]) -> list[str]

Return the targets selected by the root transform.

resolve_input_data_transformation(data_transformation: dict[str, str] | None = None, *, y_variables: list[str] | None = None, X_variables: list[str] | None = None) -> DataTransformationPipeline | None

Resolve a fallback pipeline without validating the shared panel.

input_requirements(y_variables: list[str], X_variables: list[str] | None = None, data_transformation=None)

Compose consumer requests without merging roles or losing unmapped inputs.

input_metric_requirements(y_variables, X_variables=None, data_transformation=None)

Project consumer requests for callers of the established inspection API.

forecast_realtime.TreeNode dataclass

A single node in a nested forecast tree.

Parameters

transform : Callable or ForecastModel Either a function dict[str, pd.DataFrame] -> pd.DataFrame that produces this node's output from its children (each reduced to the node's target column), or a ForecastModel that stacks: it is fitted on its children's raw components (one column per leaf/node name) and its own forecast() produces this node's output. Validated and stored here; invoked/fitted by ForecastTree. children : list of ForecastModel or TreeNode The direct children of this node. Must be a non-empty list. name : str, optional Identifier for this node. Defaults to "node" when None. target : str, optional The y column a callable transform reduces its children to (and the tree forecasts, when this is the root). Auto-resolved when y has one column. Must not be set when transform is a ForecastModel (which picks its own target via its formula).

Notes

The same object may be referenced through multiple branches (DAG-style reuse); all_leaves() and nodes() deduplicate by object identity. Rejected: two distinct objects sharing a name anywhere in the tree, or duplicate names among the direct children of a single node.

Raises

TypeError If transform is neither callable nor a ForecastModel, or any child is neither a ForecastModel nor a TreeNode. ValueError If children is not a non-empty list; if target is set on a ForecastModel transform; if direct children of any node do not have unique names; if two distinct objects share a name; or if the tree contains a cycle.

child_names: list[str] property

Names of the direct children, in order (leaf label / node name).

all_leaves() -> list[ForecastModel]

All unique leaf ForecastModel instances, in first-occurrence order.

nodes() -> list[TreeNode]

All TreeNode nodes in dependency order (children before parents).

forecast_realtime.ExternalModel

Bases: ForecastModel

Abstract base for models implemented in an external language.

Handles temporary-directory lifecycle, Parquet I/O, parameter serialisation and subprocess execution. Subclasses implement _fit_command and _forecast_command to specify the shell command for each stage.

Parameters

script : str Path to the external script (e.g. my_model.R). Resolved against the current working directory, so build it from __file__ (see Examples) to keep it independent of where Python is launched from. debug : str | None If "fit" or "forecast", drop into an interactive debug REPL for that stage instead of running the script. Default None. label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressor variables. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. subprocess_timeout : float | None Maximum number of seconds allowed for an external process. None disables the timeout. conditioning : dict | None Optional model-owned conditioning configuration.

Examples

from pathlib import Path script = str(Path(file).parent / "my_model.R") model = RModel(script, p=4, horizon=8) model.fit(y) forecasts = model.forecast(steps=4)

params_path: str property

Path to params.parquet in the current cache directory.

__getstate__() -> dict

Return copy state without transferring cache-directory ownership.

forecast_realtime.Formula

Parse and apply R-style formulas for selective variable usage.

Supports: - Basic: "y ~ x1 + x2" (select y and specific X columns) - Wildcard: "y ~ ." (y with all X columns) - Future: interactions, polynomial terms, transformations

__init__(formula_str: str)

Parse R-style formula string.

Parameters:

Name Type Description Default
formula_str

str Formula like "y ~ x1 + x2" or "y ~ ."

required

Raises:

Type Description
ValueError

If formula is malformed

extract_y(y: pd.DataFrame) -> pd.DataFrame

Select y column(s) from DataFrame.

Parameters:

Name Type Description Default
y

pd.DataFrame Input data containing y_col

required

Returns:

Type Description
DataFrame

pd.DataFrame Columns listed on the left side of the formula

Raises:

Type Description
ValueError

If y_col not in y.columns

input_columns(X_columns=None)

Select raw input names in formula order, deferring generated design terms.

extract_available_inputs(y: pd.DataFrame, X: pd.DataFrame | None) -> tuple[pd.DataFrame, pd.DataFrame | None]

Select formula inputs available before design construction.

Formula terms produced later, such as lags and dummies, are deliberately left for :meth:extract_X to validate once the full design exists.

extract_X(X: pd.DataFrame | None) -> pd.DataFrame | None

Select X column(s) from DataFrame, expanding wildcards if needed.

Parameters:

Name Type Description Default
X

pd.DataFrame or None Input data containing X columns

required

Returns:

Type Description
DataFrame | None

pd.DataFrame or None Selected X columns, or None if X is None

Raises:

Type Description
ValueError

If specified X columns not in X or X is None when required

forecast_realtime.RModel

Bases: ExternalModel

Wrapper for a model implemented in an R script.

The script is sourced and executed by R, so it must be trusted code.

The user script only needs to define two functions::

fit(y, X, params)                     # returns a model object (saved by runner)
forecast(model, steps, X, y, params)  # returns a data.frame (saved by runner)

X is a data.frame of regressors (NULL when there are none). At forecast time it may contain the fitting history followed by future regressor values; the script selects the forecast horizon. The argument order mirrors ForecastModel._fit / _forecast.

CLI dispatch, parameter reading, data loading, model serialisation, and forecast output are all handled by the bundled runner.r.

Parameters

script : str Path to the .R file containing fit() and forecast(). **params Written to params.parquet.

debug_repl(action: str = 'fit', steps: int = 1) -> None

Launch an interactive R session with cache_dir and params pre-set.

Sources the runner's read_params helper and the user script, then calls fit() or forecast() automatically. Add browser() calls to the user script to set breakpoints.

forecast_realtime.MATLABModel

Bases: ExternalModel

Wrapper for a model implemented in a MATLAB function.

The function file is executed by MATLAB, so it must be trusted code.

The user function only needs to handle two actions::

function result = my_model(action, y, X, params)
    % action is 'fit' — return a model struct
    % y is a table loaded from y.parquet; X is a table of
    % regressors (empty [] when there are none); params is a
    % struct from keyword arguments

function result = my_model(action, model, steps, X, y, params)
    % action is 'forecast' — return a table; X holds the future
    % regressor values (one row per step)

CLI dispatch, parameter reading, data loading, model serialisation, and forecast output are all handled by the bundled runner.m.

Parameters

script : str Path to the .m file. debug : str | None Optional debugging stage, either "fit" or "forecast". label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressor variables. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. subprocess_timeout : float | None Maximum number of seconds allowed for the MATLAB process. conditioning : dict | None Optional model-owned conditioning configuration.

debug_repl(action: str = 'fit', steps: int = 1) -> None

Launch an interactive MATLAB session with variables pre-set.

Opens MATLAB desktop with cache_dir, params, and the script directory already on the path. The fit or forecast function is called automatically — add breakpoints in the MATLAB editor.

forecast_realtime.JuliaModel

Bases: ExternalModel

Wrapper for a model implemented in a Julia script.

The script is included and executed by Julia, so it must be trusted code.

The user script only needs to define two functions::

function fit(y, X, params)
# returns a model object (serialised by runner)
function forecast(model, steps, X, y, params)
# returns a DataFrame (saved by runner)

X is a DataFrame of regressors (nothing when there are none); at forecast time it holds the future regressor values (one row per step).

CLI dispatch, parameter reading, data loading, model serialisation, and forecast output are all handled by the bundled runner.jl.

Parameters

script : str Path to the .jl file containing fit() and forecast(). **params Written to params.parquet.

debug_repl(action: str = 'fit', steps: int = 1) -> None

Launch an interactive Julia session with variables pre-set.

Opens a Julia REPL that includes the user script and sets cache_dir and params. The fit or forecast function is called automatically; add @bp or @infiltrate to set breakpoints.

forecast_realtime.generate_synthetic_data(N: int = N, mode: str = 'dense', seed: int = SEED, first_period=FIRST_PERIOD, endpoint=ENDPOINT, publication_lags: bool = True, year: int = YEAR) -> pd.DataFrame

Create the composed synthetic mixed-frequency real-time data set.

forecast_realtime.__version__ = version('forecast_realtime') module-attribute

Built-in models

forecast_realtime.models.ridge.ForecastRidge

Bases: LinearRegression

Ridge regression with optional cross-validated alpha: y = Xβ + ε.

Fits a single-equation Ridge regression of y (one variable) on X (regressors) using sklearn.linear_model.Ridge or sklearn.linear_model.RidgeCV. Set cv to select the regularisation parameter by cross-validation.

Parameters

fit_intercept : bool Whether to include an intercept term. Default is True. forecast_strategy : str Forecasting strategy to use ("recursive" or "direct"). Default is "recursive". steps : int | None For direct forecasting, the horizon to fit. Required when forecast_strategy="direct". scale : bool Whether to scale X and y before fitting. Default is False. alpha : float | None Regularisation strength, expressed on the scale set by alpha_scaling. If None and cv is also None, defaults to 0.1. Ignored when cv is set. cv : int | BaseCrossValidator | None Cross-validation splitter or number of splits. Default is None. label : str | None Name used to identify the model's forecasts. Defaults to the class name. alphas : np.ndarray | list | None Alpha values to try when cv is set. Defaults to 100 logarithmically spaced values from 1e-4 to 1e2, in alpha_scaling units. alpha_scaling : str Loss normalisation used for alpha. Default is "mean". formula : str | None Optional formula selecting the target and regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. drop_nans : bool Whether to remove rows containing missing values before fitting. align_start_dates : bool Whether to align the starts of the target and regressor series. conditioning : dict | None Optional model-owned conditioning configuration. penalise_ar : bool Whether to penalise target lags generated by y_lags. Default is False. Dummies are always exempt. Supports CV; designs with no penalised terms use least squares.

Attributes

alpha_ : float or None Penalty actually applied, reported on the alpha_scaling scale.

forecast_realtime.models.lasso.ForecastLasso

Bases: LinearRegression

Lasso regression with optional CV-selected alpha: y = Xβ + ε.

Fits a single-equation Lasso regression of y (one variable) on X (regressors) using sklearn.linear_model.Lasso or LassoCV. The regularisation parameter (alpha) can be fixed or automatically selected via cross-validation.

Parameters

fit_intercept : bool Whether to include an intercept term. Default is True. forecast_strategy : str Forecasting strategy to use ("recursive" or "direct"). Default is "recursive". steps : int | None For direct forecasting, the horizon to fit. Required when forecast_strategy="direct". scale : bool Whether to scale X and y before fitting. Default is False. alpha : float | None Regularisation strength. If None and cv is also None, defaults to 0.1. Ignored when cv is set. cv : int | BaseCrossValidator | None Cross-validation splitter or number of splits. Default is None. label : str | None Name used to identify the model's forecasts. Defaults to the class name. alphas : np.ndarray | list | None Candidate penalties for CV. None uses a data-dependent logarithmic grid. With exempt terms, CV selects a relative grid position using training-fold grids, then computes the final alpha on all fit data. formula : str | None Optional formula selecting the target and regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. drop_nans : bool Whether to remove rows containing missing values before fitting. align_start_dates : bool Whether to align the starts of the target and regressor series. conditioning : dict | None Optional model-owned conditioning configuration. penalise_ar : bool Whether to penalise target lags generated by y_lags. Default is False. Dummies are always exempt. Supports CV; designs with no penalised terms use least squares.

forecast_realtime.models.elastic_net.ForecastElasticNet

Bases: LinearRegression

ElasticNet regression: y = Xβ + ε with L1+L2 regularisation.

Fits a single-equation ElasticNet regression of y (one variable) on X (regressors) using sklearn.linear_model.ElasticNet or ElasticNetCV. The regularisation parameter (alpha) can be fixed or automatically selected via cross-validation.

Parameters

fit_intercept : bool Whether to include an intercept term. Default is True. forecast_strategy : str Forecasting strategy to use ("recursive" or "direct"). Default is "recursive". steps : int | None For direct forecasting, the horizon to fit. Required when forecast_strategy="direct". scale : bool Whether to scale X and y before fitting. Default is False. alpha : float | None Regularisation strength. If None and cv is also None, defaults to 0.1. Ignored when cv is set. l1_ratio : float ElasticNet mixing parameter (0 = Ridge, 1 = Lasso). Default 0.5. CV also accepts a sequence. Supply alphas when using 0 with CV. cv : int | BaseCrossValidator | None Cross-validation splitter or number of splits. Default is None. label : str | None Name used to identify the model's forecasts. Defaults to the class name. alphas : np.ndarray | list | None Candidate penalties for CV. None uses a data-dependent logarithmic grid. With exempt terms, CV selects a relative grid position using training-fold grids, then computes the final alpha on all fit data. formula : str | None Optional formula selecting the target and regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. drop_nans : bool Whether to remove rows containing missing values before fitting. align_start_dates : bool Whether to align the starts of the target and regressor series. conditioning : dict | None Optional model-owned conditioning configuration. penalise_ar : bool Whether to penalise target lags generated by y_lags. Default is False. Dummies are always exempt. Supports CV; designs with no penalised terms use least squares.

forecast_realtime.models.forecast_bvar.ForecastBVAR

Bases: ForecastModel

Bayesian VAR model wrapper for unconditional and conditional forecasting.

Wraps the bvar package's BVAR class, exposing a simplified interface compatible with ForecastModel.

Parameters

stationary : bool If True, treat all variables as stationary. Default is True. forecasts_type : Literal["mean", "median"] How to summarise the posterior forecast distribution. Default is "mean". n_lags : int Number of lags in the VAR model. Default is 1. model : str Prior model type. Default is "natural_conjugate". minnesota : bool Use Minnesota prior. Default is True. soc : bool Use sum-of-coefficients prior. Default is True. sur : bool Use single-unit-root prior. Default is True. covid : bool Include COVID dummy variables. Default is False. covid_dates : list Dates for COVID dummies. Default is None (uses package defaults). optimisation_method : str Method for hyperparameter optimisation. Default is "ml". cv_options : dict | None Options for cross-validation (if optimisation_method="cross_validation"). nb_restart : int Number of random restarts for the hyperparameter optimiser. Default is 5. n_samples : int Number of posterior draws to retain. Default is 1000. progressbar : bool Show progress bar during sampling. Default is True. mode_only : bool If True, only compute the posterior mode (fast). Default is False. label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target variables. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. method : str Algorithm for conditional forecasting. Default is "andersson_et_al". N_draws : int Number of draws for forecast uncertainty simulation. Default is 5000. N_burn : int | None Burn-in draws to discard. None lets the backend use half the effective forecast draw count, capped by the retained posterior count. base_value : np.ndarray | None Base value for converting differenced forecasts back to levels. optim_random_state : int | None Random seed passed to BVAR.optimise_hyperparameters(). Default is 42. sampling_random_state : int | None Random seed passed to BVAR.sample(). Default is 42. forecast_random_state : int | None Random seed passed to BVAR.forecast(). Default is 42. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.random_forest.RandomForest

Bases: TreeRegression

Random Forest forecaster with optional y and X lags appended to X.

Parameters

n_estimators : int Number of trees. Default 100. max_depth : int | None Maximum tree depth. Default None. min_samples_leaf : int Minimum samples required at a leaf node. Default 1. max_features : str | int | float | None Number of features to consider at each split. Default 1.0 (all). random_state : int Random seed. Default 42. standardise : bool Standardise features and target before fitting. Default False. forecast_strategy : str Forecasting strategy ("recursive" or "direct"). Default "recursive". steps : int | None For direct forecasting, the horizon to fit. label : str | None Name used to identify the model's forecasts. formula : str | None Optional patsy-style formula selecting the regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.xg_boost.XGBoost

Bases: TreeRegression

XGBoost forecaster with optional y and X lags appended to X.

Parameters

n_estimators : int Number of boosting rounds. Default 100. max_depth : int Maximum tree depth. Default 6. learning_rate : float Step size shrinkage. Default 0.1. subsample : float Row subsampling ratio per boosting round. Default 1.0. colsample_bytree : float Column subsampling ratio per tree. Default 1.0. random_state : int Random seed. Default 42. standardise : bool Standardise features and target before fitting. Default False. forecast_strategy : str Forecasting strategy ("recursive" or "direct"). Default "recursive". steps : int | None For direct forecasting, the horizon to fit. label : str | None Name used to identify the model's forecasts. formula : str | None Optional patsy-style formula selecting the regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.r_lm.ForecastRlm

Bases: RModel

AR regression model fitted in R via lm().

Parameters

lags : int Number of autoregressive lags to include. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.fable.RFableModel

Bases: RModel

Run a univariate fable model through the external R-model bridge.

spec is an R expression such as ARIMA(value ~ 1 + pdq(1, 0, 0)). It is evaluated as trusted R code in the external process; it is not treated as an inert data string or sandboxed expression. The response is named value inside R; regressor names retain their Python column names. The generic class is useful for fable models that do not need a dedicated Python convenience wrapper.

Parameters

spec : str R model specification evaluated by fable. index : str Date-index conversion used by the R model. Default "auto". allow_xreg : bool Whether the model may use exogenous regressors. Default is True. label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.fable.RFableETS

Bases: RFableModel

Fable exponential-smoothing model for a univariate series.

Parameters

error : str | None Error type passed to the Fable model. trend : str | None Trend type passed to the Fable model. season : str | None Seasonal type passed to the Fable model. Default "N". period : int | str | None Seasonal period. Requires a seasonal term. index : str Date-index conversion used by the R model. Default "auto". label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressors. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.fable.RFableARIMA

Bases: RFableModel

Fable ARIMA model for a univariate series.

Parameters

p : int | None Non-seasonal ARIMA orders. d : int | None Non-seasonal differencing order. q : int | None Non-seasonal moving-average order. seasonal : bool Whether to include seasonal ARIMA terms. Default False. P : int | None Seasonal autoregressive order. Requires seasonal=True. D : int | None Seasonal differencing order. Requires seasonal=True. Q : int | None Seasonal moving-average order. Requires seasonal=True. period : int | str | None Seasonal period. Requires seasonal=True. xreg : str | None R expression naming an exogenous regressor. index : str Date-index conversion used by the R model. Default "auto". label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressors. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.midas.ForecastMIDAS

Bases: ForecastModel

MIDAS regression wrapper for the forecast_realtime framework.

Parameters

method : str Weighting scheme: 'almon', 'exp_almon', 'beta', or 'unrestricted'. Default 'almon'. n_lags : int Number of high-frequency (monthly) lags. Default 6. n_pars_weights : int Number of weight-shape parameters for exp_almon/almon. Default 2. estimator : str | None 'ols' or 'nls'. Defaults to 'ols' for unrestricted/almon, 'nls' otherwise. horizons : list | None Horizons for direct multi-step forecasting. Each horizon is fitted as a separate model: y[t+h] ~ X[t]. If None (default), horizons are derived from steps at fit time. start_lag : int Index of the first lag to include (default 0). When start_lag=1 the most recent monthly observation (lag 0) is skipped. dummy_periods : list | None Optional list of low-frequency dates (quarter ends) to include as outlier dummies in the regression. Default None. n_ar_lags : int Number of autoregressive lags of the target to include as additional regressors (default 0 = no AR terms). When > 0 the model becomes y[t+h] = alpha + beta * X[t]'w + gamma'D[t+h] + sum_{k=1..p} phi_k * y[t+h-k] + eps with p = n_ar_lags. label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.midas_combo.ForecastMIDASCombo

Bases: ForecastModel

MIDAS forecast-combination wrapper for forecast_realtime.

Parameters

combo_specs : ComboSpec Root combination node of the SC-MIDAS tree. May contain nested ComboSpec / MidasSpec / OLSSpec / MultiMidasSpec instances. All specs are auto-derived from the tree; no separate midas_specs or ols_specs parameters. The root node's name is used to extract forecasts from the output. horizons : int Number of forecast horizons to fit (default 3). Set dynamically if RealTimeModel passes steps kwarg at fit time. regressor_frequencies : dict[str, str] | None Explicit frequency mapping for each regressor column: {'var_name': 'ME'} for monthly, 'QE' for quarterly. If omitted, frequencies are taken from the shared input-frequency map resolved by ForecastModel. label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressors. aggregate_decomp : bool | None Whether to aggregate decomposition components. Default is False. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.multi_midas.ForecastMultiMIDAS

Bases: ForecastModel

Multi-regressor MIDAS regression wrapper for the forecast_realtime framework.

Parameters

variables : list Regressors to include. Pass a plain string to use the shared defaults; pass a :class:~nowcast_midas.specs.VariableSpec to override any parameter for that regressor. Use VariableSpec(..., frequency='QE') for quarterly regressors. method : str Shared weighting scheme for monthly variables given as plain strings: 'almon', 'exp_almon', 'beta', or 'unrestricted'. Default 'almon'. n_lags : int Shared number of lags (default 3). n_pars_weights : int Shared weight-shape parameters for polynomial schemes (default 2). estimator : str | None Shared estimator override. None (default) chooses automatically per variable based on method. horizons : list | None Horizons for direct multi-step forecasting. Each horizon is fitted as a separate model: y[t+h] ~ X[t]. If None (default), horizons are derived from steps at fit time. start_lag : int Shared starting lag index (default 0). dummy_periods : list | None Optional list of low-frequency dates (quarter ends) to include as outlier dummies in the regression. Default None. n_ar_lags : int Number of autoregressive lags of the target to include as additional regressors (default 0 = no AR terms). label : str | None Name used to identify the model's forecasts. formula : str | None Optional formula selecting the target and regressors. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. conditioning : dict | None Optional model-owned conditioning configuration.

forecast_realtime.models.ols.ForecastOLS

Bases: LinearRegression

Plain vanilla OLS model: y = Xβ + ε.

Fits a single-equation OLS regression of y (one variable) on X (regressors) using numpy.linalg.lstsq.

Parameters

fit_intercept : bool Whether to include an intercept term. Default is True.

forecast_realtime.models.bridge_ols.ForecastBridgeOLS

Bases: ForecastOLS

Bridge-equation OLS: aggregate monthly X to quarterly y, then fit OLS.

Only supports a quarterly target y. Each X column's frequency is inferred from the spacing of its non-NaN index (as in :class:~forecast_realtime.models.midas_combo.ForecastMIDASCombo) and must be monthly or quarterly. Quarterly columns are used as-is; monthly columns are aggregated onto y's quarter using a complete-quarter mean. A quarter with fewer than three months is left as NaN rather than averaged from partial data.

Parameters

aggregation : str Aggregation method for higher-frequency regressors. Only "mean" (simple period-average) is currently supported. Default "mean". fit_intercept : bool Whether to include an intercept term. Default is True. forecast_strategy : str Forecasting strategy to use ("recursive" or "direct"). Default is "recursive". steps : int | None For direct forecasting, the horizon to fit. Required when forecast_strategy="direct". scale : bool Whether to scale X and y before fitting. Default is False. label : str | None Name used to identify the model's forecasts. Defaults to the class name. formula : str | None Optional patsy-style formula selecting the (aggregated) regressors. Default is None. data_transformation : dict[str, str] | None Optional model-owned raw-input transformation configuration. drop_nans : bool Whether to remove rows containing missing values before fitting. align_start_dates : bool Whether to align the starts of the target and regressor series. conditioning : dict | None Optional model-owned conditioning configuration.