Skip to content

API Reference

Public API for nowcast_midas. Start with MidasCombo for the full pipeline, or MIDAS for a single indicator. Generated by scripts/generate_api_docs.py from each module's __all__.

High-level Pipeline

nowcast_midas.midas_combo.MidasCombo

MIDAS forecast combination pipeline.

Fits individual MIDAS / OLS regressions for the leaf referenced by the combination tree and combines them according to the supplied hierarchy of ComboSpec nodes.

The pipeline derives MIDAS, OLS, and MultiMIDAS leaf specs from combo_specs. It registers each spec object that appears as a source and fits the resulting leaves before it fits the combination nodes.

PARAMETER DESCRIPTION
combo_specs

Root combination node. sources may mix variable / combo name strings, MidasSpec / OLSSpec / MultiMidasSpec instances and nested ComboSpec instances. The tree is automatically flattened into dependency order.

TYPE: ComboSpec | None DEFAULT: None

horizons

Number of application forecast steps (default 3). Each leaf fits the direct horizons required to produce those steps, subject to the available target sample.

TYPE: int DEFAULT: 3

RAISES DESCRIPTION
TypeError

If combo_specs is not a ComboSpec.

ValueError

If model names collide or a combination method is invalid.

fit

fit(target: DataFrame, regressors: DataFrame) -> MidasCombo

Fit MIDAS models and combinations according to the specifications.

PARAMETER DESCRIPTION
target

Quarterly target in long format with columns date, variable, frequency, value. Must contain exactly one variable; every frequency entry must be "QE" (case-insensitive); value must be NaN-free.

TYPE: DataFrame

regressors

Regressors in long format with the same four columns. MIDAS indicators must use frequency="ME" (monthly); OLS indicators must use frequency="QE" (quarterly); each variable must carry a single frequency. Trailing NaNs (ragged edge) in value are allowed.

TYPE: DataFrame

RETURNS DESCRIPTION
self

TYPE: MidasCombo

forecast

forecast() -> DataFrame

Compute out-of-sample forecasts for 1qa .. horizons.

Must be called after fit().

Produces one long-format row per leaf and combination for each requested application step. A row is NaN when its leaf lacks the finite data or fitted direct horizon needed for that step.

Attributes set: - self.forecasts_df_: long-format OOS forecasts [date, horizon, value, spec] - self.fits_and_forecasts_df_: concatenation of self.fits_df_ (in-sample) and self.forecasts_df_ (OOS)

RETURNS DESCRIPTION
DataFrame

Long-format OOS forecasts with columns date, horizon, value, spec. One row per spec per horizon step.

RAISES DESCRIPTION
ValueError

If the model has not been fitted.

forecast_decomp

forecast_decomp(spec_name: str | None = None, regressors: DataFrame | None = None, aggregate: bool = False) -> DataFrame

Additive component decomposition of a combo's OOS forecast.

The combined forecast of a ComboSpec is a weighted sum of its source forecasts, and each source is itself a (possibly nested) combination of individual MIDAS / OLS / MultiMIDAS indicator models. This routine flattens that hierarchy down to the indicator models, computes each indicator's effective combination weight in the target combo, and pushes that weight through the indicator's own forecast_decomp() so every component sums back to the combined forecast produced by forecast():

forecast[h] = sum_models  w_eff_model
              * sum_components  contribution_{model, component}

Components are labelled "{model}::{component}". An indicator's block whose weight is NaN (e.g. a MIDAS weighted-lag block) keeps NaN; otherwise the reported weight is the effective combination weight times the indicator's scalar coefficient.

PARAMETER DESCRIPTION
spec_name

Name of the combo (or leaf model) to decompose. Defaults to the root ComboSpec passed at construction.

TYPE: str | None DEFAULT: None

regressors

Long-format regressors to use for the decomposition. If None, the regressors stored at fit time (self.regressors_) are used. Pass a different DataFrame to compute counterfactual decompositions (e.g. old model evaluated on new data for revision attribution).

TYPE: DataFrame | None DEFAULT: None

aggregate

If False (default), emit one row per indicator sub-component, labelled "{model}::{component}" (the disaggregate view). If True, collapse each indicator down to a single row per model named "{model}", with contribution = w_eff * model_forecast and weight = w_eff. Both views individually sum to the same combined forecast at each horizon; they are not meant to be concatenated together.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataFrame

Long-format decomposition with columns horizon, date, component, contribution and weight. Contributions sum to the combined forecast value at every horizon.

RAISES DESCRIPTION
ValueError

If the model has not been fitted or the requested specification cannot be resolved.

summary

summary(horizon: int = 0) -> str

Print a formatted summary of all models and combinations and return it.

PARAMETER DESCRIPTION
horizon

The forecast horizon to summarise.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
str

The formatted summary text (also printed to stdout).

RAISES DESCRIPTION
ValueError

If the model has not been fitted yet.

MIDAS Regression (single indicator)

nowcast_midas.midas.MIDAS

MIDAS regression.

PARAMETER DESCRIPTION
method

Weighting scheme (default 'almon').

TYPE: str DEFAULT: 'almon'

n_lags

Number of high-frequency lags (default 6).

TYPE: int DEFAULT: 6

n_pars_weights

Weight-shape parameters for exp_almon/almon (default 2).

TYPE: int DEFAULT: 2

estimator

'ols' or 'nls'. Defaults to 'ols' for unrestricted/almon, 'nls' otherwise.

TYPE: str | None DEFAULT: None

horizons

Explicit list of forecast horizons to fit, e.g. [0, 1, 4]. None (default) is treated as [0], i.e. nowcast only / no multi-step forecasts. This is a list of horizon indices, unlike MidasCombo(horizons: int), which is a count of application forecast steps. The MIDAS model uses a direct forecasting approach, so each horizon is estimated as a separate model with the target variable shifted accordingly y[t+h] ~ X[t] (direct h-step forecasting).

TYPE: list[int] | None DEFAULT: None

start_lag

Index of the first high-frequency lag to include (default 0).

TYPE: int DEFAULT: 0

n_ar_lags

Number of autoregressive lags of the dependent variable 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.

TYPE: int DEFAULT: 0

dummy_periods

Quarter-end dates to include as dummy variables (default None).

TYPE: list[Timestamp] | None DEFAULT: None

RAISES DESCRIPTION
ValueError

If a model setting is invalid.

fit

fit(target: DataFrame, regressors: DataFrame) -> MIDAS

Fit the MIDAS model from target and regressor DataFrames.

PARAMETER DESCRIPTION
target

Low-frequency target with (at least) date and value columns. Column order does not matter and extra columns are ignored.

TYPE: DataFrame

regressors

High-frequency (monthly) regressor for a single indicator, with (at least) date and value columns. Column order does not matter and extra columns are ignored.

TYPE: DataFrame

RETURNS DESCRIPTION
self

TYPE: MIDAS

RAISES DESCRIPTION
ValueError

If either input is missing a required column, the target has missing values, or a horizon is unsupported.

forecast

forecast(regressors_forecast: DataFrame) -> DataFrame

Compute one out-of-sample point forecast per fitted horizon.

Notes

Direct-forecasting date convention: Let T_X be the date of the latest finite regressor observation (trailing rows with missing values do not advance the information date). The fitted relation is y[t+h] ~ X[t]. Evaluating the horizon-h model on X at T_X therefore forecasts the target h periods after T_X:

forecast_date(h) = T_X + h    (in quarters)

Equivalently, if T is the date of the last observed y and step = forecast_date - T, then the horizon needed to reach y[T+step] from X[T_X] is h = (T + step) - T_X. So a nowcast (h=0) of y[T+1] is only possible when X[T+1] is available (T_X = T+1).

PARAMETER DESCRIPTION
regressors_forecast

Monthly regressor data with date and value columns.

TYPE: DataFrame

RETURNS DESCRIPTION
DataFrame

Long-format forecasts with columns date, horizon, spec, value — one row per fitted horizon. spec is the indicator name (the regressor variable value, else "target").

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

forecast_decomp

forecast_decomp(regressors_forecast: DataFrame, regressor_name: str = 'X') -> DataFrame

Additive component decomposition of each out-of-sample forecast.

Splits every horizon's point forecast into additive components that sum back to the forecast value produced by forecast():

forecast[h] = intercept + MIDAS-block + dummies + AR-lags

The MIDAS regressor block x'(beta * w) is reported as a single component (the weighted high-frequency regressor) with weight set to NaN. The intercept, dummy, and AR components carry their scalar coefficient as weight.

PARAMETER DESCRIPTION
regressors_forecast

Monthly regressor data with date and value columns (same input as forecast()).

TYPE: DataFrame

regressor_name

Component label for the MIDAS regressor block (default "X").

TYPE: str DEFAULT: 'X'

RETURNS DESCRIPTION
DataFrame

Long-format decomposition with columns horizon, date, component, contribution and weight. Contributions sum to the forecast value at every horizon. Horizons whose forecast is undefined (e.g. missing AR lags) emit no rows.

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

summary

summary(horizon: int | None = None) -> str

Print a formatted text summary of the fitted model and return it.

PARAMETER DESCRIPTION
horizon

Which horizon to summarise. When None (default) all fitted horizons are printed in sequence.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
str

The formatted summary text (also printed to stdout).

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

nowcast_midas.midas.FittedMidas dataclass

Stores the fitted parameters and diagnostics for a single MIDAS regression at a specific horizon.

ATTRIBUTE DESCRIPTION
alpha

Estimated intercept.

TYPE: float

beta

Estimated slope on the weighted regressor (1.0 for OLS).

TYPE: float

theta

Weight-shape parameters.

TYPE: ndarray

weights

Evaluated lag weights.

TYPE: ndarray

A

OLS design matrix (None for NLS).

TYPE: ndarray | None

fitted_values

In-sample fitted values with DatetimeIndex.

TYPE: Series

residuals

In-sample residuals.

TYPE: ndarray

nobs

Number of observations used in estimation.

TYPE: int

y

Target vector used in estimation.

TYPE: ndarray

X

Regressor matrix used in estimation.

TYPE: ndarray

dates

Low-frequency target dates aligned to the fitted sample. Populated by fit(); equivalent to fitted_values.index.

TYPE: ndarray | None

gamma

Estimated outlier-dummy coefficients (empty when no dummy_periods).

TYPE: ndarray

phi

Estimated autoregressive coefficients (empty when n_ar_lags == 0).

TYPE: ndarray

Quarterly OLS (single regressor)

nowcast_midas.ols.OLS

Plain OLS regression for a single quarterly regressor.

PARAMETER DESCRIPTION
n_lags

Number of quarterly lags (default 1, i.e. contemporaneous only).

TYPE: int DEFAULT: 1

start_lag

Index of the first lag to include (default 0).

TYPE: int DEFAULT: 0

horizons

Direct-forecast horizons (default [0]).

TYPE: list[int] | None DEFAULT: None

n_ar_lags

Number of autoregressive lags of the dependent variable to include (default 0 = no AR terms). When > 0, the model becomes y[t+h] = alpha + X[t] @ coef + D[t+h] @ gamma + sum_{k=1..p} phi_k * y[t+h-k] + eps with p = n_ar_lags.

TYPE: int DEFAULT: 0

dummy_periods

Optional outlier-dummy quarters.

TYPE: list[Timestamp] | None DEFAULT: None

RAISES DESCRIPTION
ValueError

If a model setting is invalid.

fit

fit(target: DataFrame, regressors: DataFrame) -> OLS

Fit the OLS model from target and quarterly regressor frames.

PARAMETER DESCRIPTION
target

Quarterly target with (at least) date and value columns.

TYPE: DataFrame

regressors

Quarterly regressor for a single variable, with (at least) date and value columns.

TYPE: DataFrame

RETURNS DESCRIPTION
self

TYPE: OLS

RAISES DESCRIPTION
ValueError

If either input has invalid columns, missing target values, or an unsupported horizon.

forecast

forecast(regressors_forecast: DataFrame) -> DataFrame

Compute one out-of-sample point forecast per fitted horizon.

Direct-forecasting date convention (see MIDAS.forecast()): with T_X the latest available regressor date and the model fitted as y[t+h] ~ X[t], the horizon-h forecast targets forecast_date = T_X + h.

PARAMETER DESCRIPTION
regressors_forecast

Quarterly regressor data with date and value columns.

TYPE: DataFrame

RETURNS DESCRIPTION
DataFrame

Long-format forecasts with columns date, horizon, spec, value — one row per fitted horizon. spec is the regressor variable value, else "target".

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

forecast_decomp

forecast_decomp(regressors_forecast: DataFrame, regressor_name: str = 'X') -> DataFrame

Additive component decomposition of each out-of-sample forecast.

Splits every horizon's point forecast into additive components that sum back to the forecast value produced by forecast():

forecast[h] = intercept + sum_k coef_k * X[t-k] + dummies + AR-lags

Each quarterly lag is reported as its own component with its scalar coefficient in weight. When n_lags == 1, the component is named after the regressor. Intercept, dummy, and AR components also include their scalar coefficient in weight.

PARAMETER DESCRIPTION
regressors_forecast

Quarterly regressor data with date and value columns (same input as forecast()).

TYPE: DataFrame

regressor_name

Component label for the regressor block (default "X").

TYPE: str DEFAULT: 'X'

RETURNS DESCRIPTION
DataFrame

Long-format decomposition with columns horizon, date, component, contribution and weight. Contributions sum to the forecast value at every horizon. Horizons whose forecast is undefined (e.g. missing lags or AR lags) emit no rows.

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

nowcast_midas.ols.FittedOLS dataclass

Fitted result for one forecast horizon.

ATTRIBUTE DESCRIPTION
intercept

Estimated intercept.

TYPE: float

coef

Estimated quarterly lag coefficients.

TYPE: ndarray

gamma

Estimated dummy coefficients, or an empty array when no dummies are included.

TYPE: ndarray

phi

Estimated autoregressive coefficients, or an empty array when no AR lags are included.

TYPE: ndarray

fitted_values

In-sample fitted values indexed by target date.

TYPE: Series

residuals

In-sample residuals.

TYPE: ndarray

nobs

Number of observations used for estimation.

TYPE: int

dates

Target dates aligned with the fitted values.

TYPE: ndarray | None

Multi-Regressor MIDAS

nowcast_midas.multi_midas.FittedMultiMidas dataclass

Fitted result for a single horizon of a MultiMIDAS model.

ATTRIBUTE DESCRIPTION
alpha

Estimated intercept.

TYPE: float

variable_fits

Mapping from variable name to VariableFit.

TYPE: dict[str, VariableFit]

gamma

Dummy coefficients (empty if no dummies).

TYPE: ndarray

phi

AR coefficients (empty if n_ar_lags == 0).

TYPE: ndarray

A

OLS design matrix (None for NLS estimation).

TYPE: ndarray | None

fitted_values

In-sample fitted values.

TYPE: ndarray

residuals

In-sample residuals.

TYPE: ndarray

nobs

Number of observations used.

TYPE: int

y

Target vector used in estimation.

TYPE: ndarray

dates

Low-frequency target dates aligned to the fitted sample.

TYPE: ndarray | None

nowcast_midas.multi_midas.MultiMIDAS

Multi-regressor MIDAS regression.

Extends MIDAS regression to multiple high-frequency (monthly) regressors. Each regressor can use either a shared weighting method or its own per-variable specification via VariableSpec.

PARAMETER DESCRIPTION
variables

Regressors to include. Pass a plain string to use the shared defaults; pass a VariableSpec to override any parameter for that regressor. Use VariableSpec(..., frequency='QE') for quarterly regressors.

TYPE: list[str | VariableSpec]

method

Shared weighting scheme for monthly variables given as plain strings (default 'almon'). Ignored for quarterly regressors.

TYPE: str DEFAULT: 'almon'

n_lags

Shared number of lags (default 3). Monthly lags for monthly regressors, quarterly lags for quarterly regressors.

TYPE: int DEFAULT: 3

n_pars_weights

Shared weight-shape parameters for polynomial schemes (default 2).

TYPE: int DEFAULT: 2

estimator

Shared estimator override. None (default) chooses automatically per variable based on method.

TYPE: str | None DEFAULT: None

horizons

Direct-forecast horizons (default [0]).

TYPE: list[int] | None DEFAULT: None

start_lag

Shared starting lag index (default 0).

TYPE: int DEFAULT: 0

n_ar_lags

Number of AR lags of the target to include (default 0).

TYPE: int DEFAULT: 0

dummy_periods

Outlier-dummy quarters (default None).

TYPE: list[Timestamp] | None DEFAULT: None

RAISES DESCRIPTION
ValueError

If a model setting or variable specification is invalid.

Examples:

All regressors share the same method:

mc = MultiMIDAS(["PMI", "IP", "CLI"], method="almon", n_lags=6)
mc.fit(target, regressors)

Per-variable specs with a quarterly regressor:

mc = MultiMIDAS([
    VariableSpec("PMI",  method="exp_almon", n_lags=6),
    VariableSpec("IP",   method="almon",     n_lags=3),
    VariableSpec("UNEMP", frequency="QE",    n_lags=1),
])
mc.fit(target, regressors)

fit

fit(target: DataFrame, regressors: DataFrame) -> MultiMIDAS

Fit the multi-regressor MIDAS model.

PARAMETER DESCRIPTION
target

Quarterly target with at least date and value columns.

TYPE: DataFrame

regressors

High-frequency regressors. Must contain at least date, variable, and value columns. Rows are filtered per variable name to build each regressor's lag matrix.

TYPE: DataFrame

RETURNS DESCRIPTION
self

TYPE: MultiMIDAS

RAISES DESCRIPTION
ValueError

If either input is missing required columns, a variable is absent, or no valid observations are available.

forecast

forecast(regressors: DataFrame) -> DataFrame

Compute out-of-sample forecasts for all fitted horizons.

PARAMETER DESCRIPTION
regressors

High-frequency regressors with date, variable, and value columns.

TYPE: DataFrame

RETURNS DESCRIPTION
DataFrame

Long-format forecasts with columns date, horizon, spec, value — one row per fitted horizon. spec is the "+"-joined regressor variable names (a MultiMIDAS forecast is a single joint prediction).

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

forecast_decomp

forecast_decomp(regressors: DataFrame) -> DataFrame

Additive component decomposition of each out-of-sample forecast.

Splits every horizon's point forecast into additive components that sum back to the forecast value produced by forecast():

forecast[h] = intercept
            + sum_k  monthly-MIDAS-block_k
            + sum_j  quarterly-block_j
            + dummies + AR-lags

Each monthly/quarterly regressor block is reported as one component named after its variable. The weight is NaN for weighted-lag blocks. Intercept, dummy, and AR components carry their scalar coefficient as weight.

PARAMETER DESCRIPTION
regressors

High-frequency regressors with date, variable and value columns (same input as forecast()).

TYPE: DataFrame

RETURNS DESCRIPTION
DataFrame

Long-format decomposition with columns horizon, date, component, contribution and weight. Contributions sum to the forecast value at every horizon. Horizons whose forecast is undefined (e.g. missing AR lags) emit no rows.

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

summary

summary(horizon: int = 0) -> str

Print a formatted summary of the fitted model for one horizon and return it.

PARAMETER DESCRIPTION
horizon

Horizon to summarise (default 0).

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
str

The formatted summary text (also printed to stdout).

RAISES DESCRIPTION
RuntimeError

If the model has not been fitted.

ValueError

If horizon was not fitted.

nowcast_midas.multi_midas.VariableFit dataclass

Fitted parameters for one regressor within a MultiMIDAS model.

ATTRIBUTE DESCRIPTION
beta

Estimated slope. The model estimates it separately for nonlinear methods ('exp_almon', 'beta'); it fixes the value at 1.0 for the linearly-estimated methods ('almon', 'unrestricted') and for quarterly regressors.

TYPE: float

theta

Weight-shape parameters.

TYPE: ndarray

weights

Evaluated lag weights w(theta). Normalised for the nonlinear methods; unnormalised lag coefficients for 'almon' / 'unrestricted' and the linear coefficients for quarterly regressors.

TYPE: ndarray

Specifications

nowcast_midas.specs.ComboSpec dataclass

Specification for a forecast combination node.

PARAMETER DESCRIPTION
name

Unique name for this combination.

TYPE: str

sources

Sources to combine. Each entry may be:

    * a string — the variable or combination name declared elsewhere in
        the pipeline,
    * a `MidasSpec`, `OLSSpec`, or `MultiMidasSpec` —
        an indicator model that the pipeline registers automatically,
    * a nested `ComboSpec` — a combination of combinations.

TYPE: list of str, MidasSpec, OLSSpec, MultiMidasSpec or ComboSpec DEFAULT: list()

method

Combination method: 'average', 'rmse', 'mse', 'mae', or 'regression' (default 'average').

TYPE: str DEFAULT: 'average'

window

Rolling window for error / regression estimation. Use None for an expanding window covering the full sample. Default is None.

TYPE: int or None DEFAULT: None

minimum_sample_size

Minimum number of finite fitted values required for a source to enter this combination. Sources below this threshold are removed before rows with missing sources are filtered. Default is 10. The same argument on an indicator spec controls its model fit requirement.

TYPE: int DEFAULT: 10

discount_rate

Exponential discount rate for error weighting. Default is 1.0 (no discounting).

TYPE: float DEFAULT: 1.0

estimator

Weight estimation method when method='regression'. Either 'constrained_ls' (default) or 'clipped_ols'. Both methods return non-negative weights that sum to one.

TYPE: str DEFAULT: 'constrained_ls'

dummy_periods

Quarters to exclude from weight estimation. Not applicable to method='average'. Rows whose date matches an entry in dummy_periods are masked out of the error/regression estimation. Default is None (no exclusions).

TYPE: list of str or pd.Timestamp or None DEFAULT: None

ATTRIBUTE DESCRIPTION
name

Unique name for this combination.

TYPE: str

sources

Sources to combine.

TYPE: list[str | MidasSpec | OLSSpec | MultiMidasSpec | ComboSpec]

method

Combination method.

TYPE: str

window

Rolling estimation window, or None for an expanding window.

TYPE: int | None

minimum_sample_size

Minimum finite sample size for a source.

TYPE: int

discount_rate

Exponential discount rate for error weighting.

TYPE: float

estimator

Regression weight estimator.

TYPE: str

dummy_periods

Quarters excluded from weight estimation.

TYPE: list[Timestamp] | None

source_names property

source_names: list[str]

Return source names, resolving spec objects to their identifier.

flatten

flatten() -> list[ComboSpec]

Return all ComboSpec nodes in dependency order (leaves first).

collect_indicators

collect_indicators() -> tuple[list[MidasSpec], list[OLSSpec], list[MultiMidasSpec]]

Return all MidasSpec, OLSSpec and MultiMidasSpec instances referenced anywhere in the combination tree, deduplicated by variable / name (first occurrence wins).

nowcast_midas.specs.MidasSpec dataclass

Specification for a single MIDAS indicator model.

PARAMETER DESCRIPTION
variable

Name of the monthly regressor variable (must match a variable value in the regressors DataFrame).

TYPE: str

method

MIDAS weighting scheme: 'exp_almon', 'beta', 'almon', or 'unrestricted' (default 'almon').

TYPE: str DEFAULT: 'almon'

n_lags

Number of monthly lags to include (default 3).

TYPE: int DEFAULT: 3

n_pars_weights

Weight-shape parameters for polynomial schemes (default 2).

TYPE: int DEFAULT: 2

estimator

'ols' or 'nls'. Defaults based on method.

TYPE: str or None DEFAULT: None

start_lag

Starting lag for the MIDAS regression (default 0).

TYPE: int DEFAULT: 0

n_ar_lags

Number of own (target) lags to include as AR regressors (default 0, i.e. no AR augmentation).

TYPE: int DEFAULT: 0

dummy_periods

If not None, list of dates of quarters to include as dummy variables.

TYPE: list of int or None DEFAULT: None

minimum_sample_size

Minimum number of fitted quarterly observations required before this model is considered valid for forecasting. Default is None (no requirement).

TYPE: int or None DEFAULT: None

ATTRIBUTE DESCRIPTION
variable

Name of the monthly regressor variable.

TYPE: str

method

MIDAS weighting scheme.

TYPE: str

n_lags

Number of monthly lags to include.

TYPE: int

n_pars_weights

Number of weight-shape parameters.

TYPE: int

estimator

Estimator override, or None for automatic selection.

TYPE: str | None

start_lag

Index of the first lag to include.

TYPE: int

n_ar_lags

Number of autoregressive lags.

TYPE: int

dummy_periods

Quarter-end dates to include as dummy variables.

TYPE: list[Timestamp] | None

minimum_sample_size

Minimum number of fitted observations required for forecasting.

TYPE: int | None

nowcast_midas.specs.MultiMidasSpec dataclass

Specification for a multi-regressor MIDAS model inside a MidasCombo pipeline.

The fitted values produced by the underlying MultiMIDAS model are exposed to ComboSpec nodes under name.

PARAMETER DESCRIPTION
name

Unique identifier for this model within the pipeline (used as the source name in ComboSpec).

TYPE: str

variables

Regressors to include. Plain strings use the shared defaults; VariableSpec instances override per-variable settings.

TYPE: list of str or VariableSpec DEFAULT: list()

method

Shared weighting scheme for variables given as plain strings (default 'almon').

TYPE: str DEFAULT: 'almon'

n_lags

Shared number of monthly lags (default 3).

TYPE: int DEFAULT: 3

n_pars_weights

Shared weight-shape parameters (default 2).

TYPE: int DEFAULT: 2

estimator

Shared estimator override (default None = auto).

TYPE: str or None DEFAULT: None

start_lag

Shared starting lag index (default 0).

TYPE: int DEFAULT: 0

n_ar_lags

Number of AR lags of the target (default 0).

TYPE: int DEFAULT: 0

dummy_periods

Outlier-dummy quarters (default None).

TYPE: list of pd.Timestamp or None DEFAULT: None

minimum_sample_size

Minimum number of fitted quarterly observations required before this model is considered valid for forecasting. Default is None (no requirement).

TYPE: int or None DEFAULT: None

ATTRIBUTE DESCRIPTION
name

Unique identifier for this model.

TYPE: str

variables

Regressors to include.

TYPE: list[str | VariableSpec]

method

Shared MIDAS weighting scheme.

TYPE: str

n_lags

Shared number of lags.

TYPE: int

n_pars_weights

Shared number of weight-shape parameters.

TYPE: int

estimator

Shared estimator override.

TYPE: str | None

start_lag

Shared starting lag index.

TYPE: int

n_ar_lags

Number of autoregressive lags.

TYPE: int

dummy_periods

Outlier-dummy quarters.

TYPE: list[Timestamp] | None

minimum_sample_size

Minimum number of fitted observations required for forecasting.

TYPE: int | None

nowcast_midas.specs.OLSSpec dataclass

Specification for a quarterly OLS regressor (no MIDAS weighting).

Used for low-frequency indicators that share the target's frequency (quarterly) and therefore need plain OLS rather than mixed-frequency weighting. Fitted values are made available to ComboSpec nodes under variable exactly like a MidasSpec.

PARAMETER DESCRIPTION
variable

Name of the quarterly regressor variable (must match a variable value in the regressors DataFrame with frequency='QE').

TYPE: str

n_lags

Number of quarterly lags to include (default 1, i.e. only the contemporaneous value x_t).

TYPE: int DEFAULT: 1

start_lag

Index of the first quarterly lag to include (default 0).

TYPE: int DEFAULT: 0

n_ar_lags

Number of own (target) lags to include as AR regressors (default 0).

TYPE: int DEFAULT: 0

dummy_periods

Optional outlier-dummy quarters.

TYPE: list of pd.Timestamp or None DEFAULT: None

minimum_sample_size

Minimum number of fitted quarterly observations required before this model is considered valid for forecasting. Default is None (no requirement).

TYPE: int or None DEFAULT: None

ATTRIBUTE DESCRIPTION
variable

Name of the quarterly regressor variable.

TYPE: str

n_lags

Number of quarterly lags to include.

TYPE: int

start_lag

Index of the first quarterly lag to include.

TYPE: int

n_ar_lags

Number of autoregressive lags.

TYPE: int

dummy_periods

Optional outlier-dummy quarters.

TYPE: list[Timestamp] | None

minimum_sample_size

Minimum number of fitted observations required for forecasting.

TYPE: int | None

nowcast_midas.specs.VariableSpec dataclass

Per-variable specification for a MultiMIDAS model.

PARAMETER DESCRIPTION
variable

Name of the regressor variable (must match a variable value in the regressors DataFrame).

TYPE: str

method

MIDAS weighting scheme: 'exp_almon', 'beta', 'almon', or 'unrestricted' (default 'almon'). Ignored when frequency='QE' (quarterly regressors always enter linearly).

TYPE: str DEFAULT: 'almon'

n_lags

Number of lags to include (default 3). Monthly lags for frequency='ME', quarterly lags for frequency='QE'.

TYPE: int DEFAULT: 3

n_pars_weights

Weight-shape parameters for polynomial schemes (default 2). Ignored for quarterly regressors.

TYPE: int DEFAULT: 2

estimator

'ols' or 'nls'. None chooses automatically based on method ('ols' for almon/unrestricted, 'nls' otherwise). Ignored for quarterly regressors.

TYPE: str or None DEFAULT: None

start_lag

Index of the first lag to include (default 0).

TYPE: int DEFAULT: 0

frequency

Sampling frequency of the regressor: 'ME' for monthly (default) or 'QE' for quarterly. Quarterly regressors bypass MIDAS weighting and enter the model linearly.

TYPE: str DEFAULT: 'ME'

ATTRIBUTE DESCRIPTION
variable

Name of the regressor variable.

TYPE: str

method

MIDAS weighting scheme.

TYPE: str

n_lags

Number of lags to include.

TYPE: int

n_pars_weights

Number of weight-shape parameters.

TYPE: int

estimator

Estimator override, or None for automatic selection.

TYPE: str | None

start_lag

Index of the first lag to include.

TYPE: int

frequency

Sampling frequency of the regressor.

TYPE: str

Weighting Schemes

nowcast_midas.temporal_weights.almon

almon(theta: ndarray, n_lags: int) -> ndarray

Polynomial Almon lag weights.

Computes w_j = sum_i theta_i * j^i for j = 0, …, n_lags-1, then normalises so that the weights sum to one.

PARAMETER DESCRIPTION
theta

Polynomial coefficients, one per degree starting from degree 0.

TYPE: ndarray

n_lags

Number of high-frequency lags.

TYPE: int

RETURNS DESCRIPTION
weights

Normalised lag weights.

TYPE: ndarray

nowcast_midas.temporal_weights.beta

beta(theta: ndarray, n_lags: int) -> ndarray

Beta polynomial lag weights.

Evaluates the Beta density on an equally-spaced grid over (0, 1) using shape parameters (a, b) = theta, then normalises the result. Both parameters are clipped to a minimum of 1e-6 for numerical stability.

PARAMETER DESCRIPTION
theta

Shape parameters [a, b] of the Beta distribution.

TYPE: ndarray

n_lags

Number of high-frequency lags.

TYPE: int

RETURNS DESCRIPTION
weights

Normalised lag weights.

TYPE: ndarray

nowcast_midas.temporal_weights.exp_almon

exp_almon(theta: ndarray, n_lags: int) -> ndarray

Normalised Exponential Almon lag weights.

Computes w_j = exp(sum_i theta_i * j^(i+1)) for j = 0, …, n_lags-1, then normalises so that the weights sum to one.

PARAMETER DESCRIPTION
theta

Shape parameters of the exponential polynomial.

TYPE: ndarray

n_lags

Number of high-frequency lags.

TYPE: int

RETURNS DESCRIPTION
weights

Normalised lag weights.

TYPE: ndarray

nowcast_midas.temporal_weights.get_weights

get_weights(method: str, theta: ndarray, n_lags: int) -> ndarray

Return lag weights for the selected weighting scheme.

PARAMETER DESCRIPTION
method

Name of the weighting scheme.

TYPE: str

theta

Shape parameters passed to the weight function.

TYPE: ndarray

n_lags

Number of high-frequency lags.

TYPE: int

RETURNS DESCRIPTION
weights

Lag weights returned by the selected scheme.

TYPE: ndarray

nowcast_midas.temporal_weights.unrestricted

unrestricted(theta: ndarray, n_lags: int) -> ndarray

Unrestricted (U-MIDAS) lag weights.

Returns theta unchanged, so the model estimates one coefficient for each lag without a parametric restriction.

PARAMETER DESCRIPTION
theta

One coefficient for each lag.

TYPE: ndarray

n_lags

Number of high-frequency lags (unused; present for API consistency).

TYPE: int

RETURNS DESCRIPTION
weights

The input theta, unmodified.

TYPE: ndarray

Combination Weights

nowcast_midas.combo_weights.clipped_ols

clipped_ols(X: ndarray, y: ndarray) -> ndarray

OLS with clipping to [0, 1] and sum-to-one normalisation.

Estimates weights via OLS min ||y - X w||^2, clips each weight to [0, 1], and normalises to sum to 1.

PARAMETER DESCRIPTION
X

Design matrix with p regressors.

TYPE: ndarray

y

Target values.

TYPE: ndarray

RETURNS DESCRIPTION
weights

Non-negative weights clipped to [0, 1] and summing to 1.

TYPE: ndarray

nowcast_midas.combo_weights.constrained_least_squares

constrained_least_squares(X: ndarray, y: ndarray) -> ndarray

Estimate non-negative weights that sum to one.

Solves min ||y - X w||^2 subject to w >= 0 and sum(w) = 1.

PARAMETER DESCRIPTION
X

Design matrix.

TYPE: ndarray

y

Target vector.

TYPE: ndarray

RETURNS DESCRIPTION
weights

Non-negative weights summing to 1.

TYPE: ndarray

nowcast_midas.combo_weights.fit_average

fit_average(source_fitted: DataFrame) -> tuple[ndarray, dict[str, ndarray]]

Equal-weight average.

PARAMETER DESCRIPTION
source_fitted

Fitted value matrix with source names as column names.

TYPE: DataFrame

RETURNS DESCRIPTION
combined

Equally-weighted average of sources.

TYPE: ndarray

weights

Source names to time-varying equal weights over available sources.

TYPE: dict[str, ndarray]

nowcast_midas.combo_weights.fit_error_based_weights

fit_error_based_weights(target: Series, source_fitted: DataFrame, *, method: str, window: int | None = None, discount_rate: float = 1.0, dummy_periods: list | None = None) -> tuple[ndarray, dict[str, ndarray]]

Fit time-varying inverse-error weights using MAE, MSE, or RMSE.

nowcast_midas.combo_weights.fit_regression_weights

fit_regression_weights(target: Series, source_fitted: DataFrame, *, method: str, window: int | None = None, dummy_periods: list | None = None, minimum_sample_size: int | None = None) -> tuple[ndarray, dict[str, ndarray]]

Fit time-varying weights using clipped or constrained regression.

Example Data

nowcast_midas.utils.sample_combo_data

sample_combo_data(n_quarters: int = 60, n_lags: int = 6, monthly_vars: list[str] | None = None, quarterly_vars: list[str] | None = None, alpha: float = 1.0, betas: dict[str, float] | None = None, gammas: dict[str, float] | None = None, noise: float = 0.5, seed: int = 42, method: str = 'exp_almon', theta_true: list[float] | ndarray | None = None, horizon: int = 0, outlier_date: str | Timestamp | None = '2020-06-30', outlier_size: float = -25.0) -> tuple[DataFrame, DataFrame, dict]

Generate sample data for the MidasCombo pipeline.

Each monthly indicator v is drawn iid N(0, 1) and enters the target through its own MIDAS DGP; each quarterly indicator z enters linearly. With lead h = horizon the full DGP is:

y[t+h] = alpha + sum_v beta_v * X[v, t] @ w + sum_z gamma_z * Z[z, t] + outlier[t+h] + eps, with eps ~ N(0, noise**2).

The lag weights w come from get_weights() with shape parameters theta_true (default [-0.5, -0.1]).

PARAMETER DESCRIPTION
n_quarters

Number of quarterly observations (default 60).

TYPE: int DEFAULT: 60

n_lags

Number of monthly lags used both to build the regressor matrix and to generate the DGP weights (default 6).

TYPE: int DEFAULT: 6

monthly_vars

Names of the monthly (ME) indicators. Default ['monthly_1', 'monthly_2', 'monthly_3'].

TYPE: list[str] | None DEFAULT: None

quarterly_vars

Names of the quarterly (QE) indicators. Default ['quarterly_1'].

TYPE: list[str] | None DEFAULT: None

alpha

DGP intercept (default 1.0).

TYPE: float DEFAULT: 1.0

betas

Per-indicator MIDAS coefficients. Defaults to {'PMI': 1.0, 'IP': 0.8, 'GDPM': 0.5}; any missing entry falls back to 1.0.

TYPE: dict[str, float] | None DEFAULT: None

gammas

Per-indicator OLS coefficients for quarterly regressors. Defaults to {'UNEMP': -0.5}; missing entries fall back to 1.0.

TYPE: dict[str, float] | None DEFAULT: None

noise

Standard deviation of the Gaussian target noise (default 0.5).

TYPE: float DEFAULT: 0.5

seed

Random seed (default 42).

TYPE: int DEFAULT: 42

method

Weighting scheme used to generate the true weights.

TYPE: str DEFAULT: 'exp_almon'

theta_true

Forwarded to get_weights() to produce the true monthly lag weights.

TYPE: list[float] | ndarray | None DEFAULT: None

horizon

Forecast lead used to generate the relationship y[t+h] ~ X[t] (default 0 = contemporaneous). Must satisfy 0 <= horizon < n_quarters.

TYPE: int DEFAULT: 0

outlier_date

Quarter at which to inject a one-off additive shock to the target. Pass None to skip. Default '2020-06-30'.

TYPE: str | Timestamp | None DEFAULT: '2020-06-30'

outlier_size

Size of the additive shock at outlier_date (default -25).

TYPE: float DEFAULT: -25.0

RETURNS DESCRIPTION
target

Quarterly target in long format with columns date, variable, frequency, value.

TYPE: DataFrame

regressors

Monthly and quarterly regressors in the same long format.

TYPE: DataFrame

info

Ground-truth metadata: outlier_date, alpha, betas, gammas, weights (length n_lags), noise, monthly_vars, quarterly_vars.

TYPE: dict

RAISES DESCRIPTION
ValueError

If the requested horizon or outlier date is outside the simulated sample, or if autoregressive settings are inconsistent.

nowcast_midas.utils.sample_data

sample_data(n_obs: int = 100, n_lags: int = 6, alpha: float = 2.0, beta_: float = 1.0, noise: float = 0.5, seed: int = 42, horizon: int = 0, method: str = 'exp_almon', theta_true: list[float] | ndarray | None = None, n_ar_lags: int = 0, phi_true: list[float] | ndarray | None = None) -> tuple[DataFrame, DataFrame]

Generate sample quarterly target and monthly regressor data.

Generates synthetic data from a specified MIDAS structure.

The target is generated with a direct-forecast lead relationship:

y[t+h] = alpha + beta * X[t] @ w + sum_{k=1..p} phi[k-1] * y[t+h-k] + noise,

where h is the horizon parameter and p = n_ar_lags. When horizon=0 and n_ar_lags=0 (default) this reduces to the contemporaneous y[t] ~ X[t].

PARAMETER DESCRIPTION
n_obs

Number of quarterly observations (default 100).

TYPE: int DEFAULT: 100

n_lags

Number of monthly lags (default 6).

TYPE: int DEFAULT: 6

alpha

Intercept (default 2.0).

TYPE: float DEFAULT: 2.0

beta_

Slope coefficient (default 1.0).

TYPE: float DEFAULT: 1.0

noise

Noise standard deviation (default 0.5).

TYPE: float DEFAULT: 0.5

seed

Random seed (default 42).

TYPE: int DEFAULT: 42

horizon

Forecast lead used to generate the relationship y[t+h] ~ X[t] (default 0).

TYPE: int DEFAULT: 0

method

Weighting scheme used to generate the true weights (default 'exp_almon'). Any scheme accepted by get_weights() is valid.

TYPE: str DEFAULT: 'exp_almon'

theta_true

Weight-shape parameters. When None (default), uses [-0.5, -0.1].

TYPE: list[float] | ndarray | None DEFAULT: None

n_ar_lags

Number of autoregressive lags of the dependent variable to embed in the DGP (default 0 = no AR term).

TYPE: int DEFAULT: 0

phi_true

AR coefficients of length n_ar_lags. When None and n_ar_lags > 0, defaults to [0.3, -0.1, ...] truncated / zero-padded to n_ar_lags entries. Ignored when n_ar_lags == 0.

TYPE: list[float] | ndarray | None DEFAULT: None

RETURNS DESCRIPTION
target

Quarterly target with date and value columns.

TYPE: DataFrame

regressors

Monthly regressors with date and value columns.

TYPE: DataFrame

RAISES DESCRIPTION
ValueError

If the requested autoregressive lags, forecast horizon, or autoregressive coefficient length is invalid for the sample.

Examples:

>>> target, regressors = sample_data(n_obs=100, n_lags=6, seed=0)
>>> from nowcast_midas.midas import MIDAS
>>> m = MIDAS(n_lags=6).fit(target, regressors)