Skip to content

Nowcasting & mixed frequency

The classes and functions of the row "Nowcasting & mixed frequency" of Analytical tools, with what calls return (the results and their methods: forecasts, impulse responses, tests). Import them from pymetrix (from pymetrix import ...) unless a heading names another module. Parameters and return types are in each signature; the text says what each does.

Help topics: Quantile nowcasts, targeted predictors, weekly data and the mixed-frequency BVAR, Nowcasting and the ragged edge, MIDAS: mixed-frequency regression, Component bridges: GDP nowcast from its components (GDPNow style), State space and the Kalman filter, Temporal disaggregation, Bayesian VARs, Nowcast backtests and tracking, Surveillance heatmaps.

How do I: Nowcast GDP.

Classes

Bridge dataclass

Bridge(formula: str, how: str = 'mean', fill_lags: int = 2, method: Any = None, mask: Any = None)

A bridge equation: a quarterly series on monthly indicators averaged to quarters (Baffigi, Golinelli and Parigi 2004). The current quarter's missing months are forecast by an AR model of each indicator first.

bridge = Bridge("400*dlog(y) ~ 400*dlog(retail) + pmi").fit(quarterly, monthly)
bridge.nowcast(quarterly, monthly.as_of("2025-02-15"))   # the quarter(s) after the last GDP figure
bridge.nowcast_density(quarterly, monthly.as_of("2025-02-15"))   # with its standard error and interval

The formula uses the quarterly series' names and the indicators' names (averaged within each quarter, or as how says: "mean", "sum", "last"). fill_lags is the order of the autoregressions that complete the quarter. Any estimation method for equations can be given (method); OLS by default.

ComponentBridge dataclass

ComponentBridge(components: Mapping[str, Any], levels: Mapping[str, str], aggregation: str = 'shares', deflators: Mapping[str, str] | None = None, growth: str = 'log', scale: float = 400.0, correlation: Any = 'residuals', name: str = 'aggregate')

An aggregate nowcast built from its components' nowcasts, aggregated as the national accounts do (GDPNow style).

components: for each component's quarterly growth series (in the quarterly data), its model: a Bridge, MIDAS, DynamicFactor, QuantileBridge or TargetedPredictors specification, or a fitted model. levels: each component's nominal level series (the shares' weights; the previous quarter's). aggregation: "shares" (the shares-weighted sum of the components' growth) or "chained" (the BEA's Fisher contributions, with deflators, each component's price index series, if given). growth: "log" (scale * dlog) or "percent" (scale * (x / x[-1] - 1)), the form of the components' series and of the aggregate. correlation of the components' errors, for the bands: "residuals" (estimated from the models' in-sample errors), a number for every pair, a matrix, a frame of historical errors by component, or a NowcastBacktest of a component bridge. name: the aggregate's name. See the module's docstring for the formulas and their approximation errors.

names property

names: list[str]

The components, in order.

fit

Estimate each component's model on the quarterly low and monthly high data, and the correlation of their errors.

DynamicFactor dataclass

DynamicFactor(monthly: tuple[str, ...], quarterly: tuple[str, ...] = (), factors: int | Mapping[str, Sequence[str]] = 1, factor_order: int = 2, idiosyncratic_ar1: bool = True, max_iter: int = 500, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict(), full_sample: bool = False, mask: Any = None, outliers: float | None = None, outlier_method: str = 'iqr')

A dynamic factor model of monthly and quarterly series (Banbura and Modugno 2014; quarterly series as in Mariano and Murasawa 2003), estimated by EM and filtered by the Kalman filter, so any pattern of missing values (the ragged edge) is handled as it is. The engine is statsmodels' DynamicFactorMQ.

dfm = DynamicFactor(monthly=["gr", "gip", "gemp", "pmi"], quarterly=["gy"]).fit(quarterly, monthly)
dfm.nowcast("gy")                          # each quarter after the last GDP figure, from the indicators
dfm.nowcast_density("gy")                  # the same with its standard error and a 90% interval
later = dfm.update(quarterly, monthly2)    # the same model on newer data (not re-estimated)
later.news(dfm, "gy")                      # how each new figure moved the nowcast

Series must be stationary (growth rates, surveys): transform them first with with_series.

factors is the number of common factors, each loading on every series, or a block structure: a dict from each series to the factors (blocks) it loads on, as statsmodels takes it. Every series needs at least one block. A factor that loads on every series is global, one that loads on some is a block factor (Banbura, Giannone, Modugno and Reichlin 2013; the New York Fed's global, soft, real and labour blocks):

blocks = {"gr": ["Global", "Real"], "gip": ["Global", "Real"], "gemp": ["Global", "Real"],
          "pmi": ["Global", "Soft"], "gy": ["Global", "Real"]}
DynamicFactor(monthly=["gr", "gip", "gemp", "pmi"], quarterly=["gy"], factors=blocks)

Each block's factors follow a VAR(factor_order), independent of the other blocks.

By default the sample starts in the first month every monthly series has data, which keeps the EM steps well conditioned when one series starts a little earlier. full_sample=True keeps each series' whole history, from the first month any of them has data, and EM treats the months before a series starts as missing: what a panel of series with very different start dates needs.

mask sets chosen periods to missing for estimation, so EM and the Kalman filter treat them as not observed: {"2020-03": "2021-06"} (a range, for every series), a list of periods, or a dict from series to either ({"gip": {"2020-03": "2020-12"}}); a quarter is masked when any of its months is. outliers: values more than that many interquartile ranges (outlier_method="iqr") or scaled median absolute deviations ("mad") from the series' median, after the mask, are set to missing too. What was removed is in masked, the summary and the provenance. The same masks and rule apply to the data given to update.

blocks property

blocks: dict[str, list[str]]

Each factor (block) and the series that load on it; with a number of factors, each loads on every series.

fit

fit(low: Dataset | None, high: Dataset) -> FittedDynamicFactor

Estimate on monthly high and quarterly low data (low may be None).

MIDAS dataclass

MIDAS(formula: str, lags: int = 12, weights: Weights = 'exp_almon', ar: int = 0, high_lag: int = 0, mask: Any = None)

formula: the low-frequency series on one or more high-frequency indicators (gdp ~ ip + sales).

design

design(low: Dataset, high: Dataset, periods: PeriodIndex | None = None) -> tuple[PeriodIndex, dict[str, ndarray]]

For each low-frequency period: each indicator's lags high-frequency values, latest first.

MixedFrequencyBVAR dataclass

MixedFrequencyBVAR(monthly: tuple[str, ...], quarterly: tuple[str, ...] = (), lags: int = 3, prior: Minnesota = (lambda: Minnesota(own_mean=0.0))(), aggregation: Literal['mean', 'growth'] = 'mean', draws: int = 1000, burn: int = 500, seed: int = 0)

A monthly VAR of monthly series and monthly versions of the quarterly ones, under a Minnesota prior, estimated by Gibbs sampling with a simulation smoother (see the module notes).

lags: the VAR's lags, in months; prior: a Minnesota prior (own_mean 0 for growth rates, the default here; optimize=True chooses its hyperparameters by the marginal likelihood); aggregation: "mean" (the quarter's three months averaged) or "growth" (Mariano and Murasawa's weights); draws kept after burn; seed for the sampler (the same seed, the same draws).

fit

fit(low: Dataset | None, high: Dataset, through: Any = None) -> FittedMixedFrequencyBVAR

Gibbs sampling on the quarterly data low and the monthly data high, the months through the quarter of the latest month (or through, a quarter).

QuantileBridge dataclass

QuantileBridge(formula: str, quantiles: tuple[float, ...] = LEVELS, form: Literal['bridge', 'umidas'] = 'bridge', how: str = 'mean', fill_lags: int = 2, mask: Any = None)

Quantile regressions of a quarterly series on monthly indicators, for quantile nowcasts and growth at risk.

QuantileBridge("gy ~ gr + pmi")                  # the quarterly averages of the indicators (a bridge)
QuantileBridge("gy ~ gr + pmi", form="umidas")   # each month of the quarter separately (U-MIDAS)

formula: the quarterly series on the indicators (and quarterly series, lags of the left-hand side such as gy[-1]); quantiles: the quantiles estimated, which must include 0.05, 0.25, 0.75 and 0.95 (the skewed t is matched to them); form: "bridge" (averages, or how) or "umidas" (the months; indicators written as plain names); fill_lags: the order of the AR models that complete the quarter; mask: quarters left out of the estimation sample, as Bridge's.

fit

fit(low: Dataset, high: Dataset, span: Any = None) -> FittedQuantileBridge

Each quantile's regression on the quarterly data and the indicators (complete quarters only).

SurveillanceSpec dataclass

SurveillanceSpec(series: Sequence[str], normalise: Literal['zscore', 'robust_zscore', 'pctrank', 'level', 'gap'] = 'zscore', window: int | None = None, reference: tuple[Any, Any] | None = None, gap_filter: Literal['hp', 'hamilton', 'mean'] = 'hp', higher_is_worse: bool | Sequence[str] | Mapping[str, bool] = True, thresholds: Sequence[float] = (), groups: Mapping[str, Sequence[str]] | None = None, composite: Literal['equal', 'pca', 'none'] | None = None, order: Literal['given', 'group', 'cluster'] = 'given', frequency: str | None = None, fill: Literal['repeat', 'once', 'latest'] = 'repeat', last: int | None = None, changes: Sequence[int] = (3, 6, 12), dendrogram: bool = False, cmap: str = '', annotate: bool = False, hatch: str = '///', date_format: str = '', title: str = '')

The settings of a surveillance heatmap, kept so the same heatmap is drawn again on newer data (spec.draw(data); a recorded step does so when its data are refreshed). The fields are surveillance_heatmap's arguments; see pymetrix.heatmap.

composite_rule property

composite_rule: str

The composite row's weights: "equal", "pca", or "none" (no composite row).

draw

draw(data: Any, span: tuple[Any, Any] | None = None, regimes: Any = None, calendar: Any = None) -> SurveillanceHeatmap

The heatmap of data (a Dataset, or several of different frequencies), showing the periods of span (first, last) and then the last of them; regimes are drawn as bands of colour above the dates: a k-means result (kmeans(...), its clusters by date), a series (a recession dummy, an MS-VAR's most likely regime), the name of a series in the data, or a mapping of band names to any of those (or a list of them). calendar, a ReleaseCalendar, dates the lower-frequency readings by their actual release days under fill="latest" (instead of each series' fixed publication lag).

TargetedPredictors dataclass

TargetedPredictors(variable: str, candidates: tuple[str, ...] | None = None, rule: Literal['hard', 'lars', 'elastic_net'] = 'hard', threshold: float = 1.65, keep: int = 5, lags: int = 1, model: Literal['factor', 'bridge'] = 'factor', factors: int = 1, l1_ratio: float = 0.5)

Choose the indicators for variable (Bai and Ng's targeted predictors), then nowcast it with a factor model or a bridge equation on those kept. See the module notes.

select

select(low: Dataset, high: Dataset) -> DataFrame

The selection table on these data (see select_predictors).

fit

Choose the indicators, then estimate the model on them.

Functions

nowcast_backtest

nowcast_backtest(model: Any, low: Dataset, high: Dataset, variable: str, quarters: tuple[Any, Any], days: tuple[int, int] = (-180, 30), step: int = 7, reestimate: Any = 'each', benchmark: Any = 'ar', lags: Mapping[str, int] | None = None, workers: int = 1, label: str = '', calendar: Any = None, vintages: Any = None, weekly: Dataset | None = None, outturn: Any = 'latest') -> NowcastBacktest

Nowcast each quarter from quarters[0] to quarters[1] on days around its end, from the data as known then.

model: a Bridge, MIDAS or DynamicFactor specification (or a fitted one: its specification is used), any specification with fit(low, high) whose fit has nowcast(low, high, through=), or a function model(low, high) -> pd.Series giving the target by quarter. low: the quarterly data with variable; high: the monthly indicators. Each series' publication lag (Variable.release_lag, or lags) says when its values came out (as_of); a series made from others (with_series) with no lag of its own takes the longest lag of the series its formula names (gy = 400*dlog(y) is published when y is).

days: the first and last day of the grid, in days from the end of each target quarter (-180: half a year before, 30: a month after); step: days between nowcasts (7 weekly, 14, 30 about monthly). reestimate: "each" day (the default), on the first day of each "quarter" or "year", "once" (on the first day), or a number of days; in between the parameters are kept and only the data are new. benchmark: "ar" (an AR(1) of the target as known each day), "mean" (its mean), None, or another model. workers: processes to run the re-estimations in (each run of days between two re-estimations goes to one); a function defined in a script runs here.

calendar: a ReleaseCalendar, the actual release date of each figure (series and periods it does not list keep their lag). vintages: a VintageTable (read_vintages), a list of them or a dict of them by series, for a real-time backtest: each day uses the vintage of each of those series published by then (the column vintage says which), instead of the latest data; series derived from them (derive) are recomputed.

outturn: what the nowcasts are scored against: "latest" (the target in low, the default), "first" (each quarter's first release) or a number k (its k-th release, 1 the first), read from the vintages: the target's own VintageTable in vintages, or, for a target derived from quarterly series with vintages (derive(gy="400*dlog(y)")), the target recomputed in each of their vintages. A quarter without that release is not scored.

weekly: weekly or daily series for the model, made monthly on each day from what was known then (weekly_to_monthly: complete months' means, and the month so far as name_mtd) and put beside high.

Returns a NowcastBacktest: the nowcasts by quarter and day, RMSE and MAE by horizon, the comparison with the benchmark (Diebold-Mariano at each horizon) and a figure of RMSE against the horizon.

nowcast_refresh

nowcast_refresh(spec: Any, store: Any, day: Any = None, report: Any = None) -> NowcastRefresh

Read the data the specification spec names (a TOML or JSON file, or a dict), keep what was known on day (default today), estimate each model, and append each quarter's nowcast, band and news to store (CSV or Parquet); report: a Markdown file to write. See the module's documentation for the specification.

nowcast_tracking

nowcast_tracking(model: Any, low: Dataset, high: Dataset, variable: str, quarter: Any, days: tuple[int, int] = (-180, 30), step: int = 7, groups: Mapping[str, Sequence[str]] | None = None, reestimate: Any = 'once', lags: Mapping[str, int] | None = None, label: str = '', calendar: Any = None, weekly: Dataset | None = None) -> NowcastTracking

Follow the nowcast of variable for quarter from days[0] to days[1] days around the quarter's end, every step days (stopping when the quarter's figure comes out), from the data as known on each day.

model: a DynamicFactor specification or fitted model (news figure by figure), or a Bridge, MIDAS or any specification with fit(low, high) (the change split into new data and re-estimation), as for nowcast_backtest. groups: names for sets of series, e.g. {"surveys": ["pmi"], "real": ["gr", "gip"]}, whose news is added up; series in no group stand alone. reestimate: "once" (on the first day; the default, so every change is news), on the first day of each "quarter" or "year", "each" day, or a number of days. lags: publication lags, as for as_of. calendar: a ReleaseCalendar, the actual release dates (as for as_of); series in no group then have their news added up by the release they come out in (the Employment Situation's payrolls, unemployment and hours together), and with step=0 the days are the calendar's release days in the window instead of a fixed grid. weekly: weekly or daily series for the model, made monthly on each day from what was known then (weekly_to_monthly: complete months' means, and the month so far as name_mtd) and put beside high, as in nowcast_backtest.

The parts of each day's change (news by figure, revisions, re-estimation) add up to the change exactly.

select_predictors

select_predictors(low: Dataset, high: Dataset, variable: str, candidates: Sequence[str] | None = None, rule: str = 'hard', threshold: float = 1.65, keep: int = 5, lags: int = 1, l1_ratio: float = 0.5) -> DataFrame

The selection step of TargetedPredictors alone: a row per candidate with its statistic (hard: the t-statistic; soft: the step at which it entered, blank if it did not), and whether it is kept.

surveillance_heatmap

surveillance_heatmap(data: Any, series: Sequence[str], normalise: Literal['zscore', 'robust_zscore', 'pctrank', 'level', 'gap'] = 'zscore', window: int | None = None, reference: tuple[Any, Any] | None = None, gap_filter: Literal['hp', 'hamilton', 'mean'] = 'hp', higher_is_worse: bool | Sequence[str] | Mapping[str, bool] = True, thresholds: Sequence[float] = (), groups: Mapping[str, Sequence[str]] | None = None, composite: Literal['equal', 'pca', 'none'] | None = None, order: Literal['given', 'group', 'cluster'] = 'given', frequency: str | None = None, fill: Literal['repeat', 'once', 'latest'] = 'repeat', last: int | None = None, changes: Sequence[int] = (3, 6, 12), span: tuple[Any, Any] | None = None, regimes: Any = None, dendrogram: bool = False, cmap: str = '', annotate: bool = False, hatch: str = '///', date_format: str = '', title: str = '', calendar: Any = None) -> SurveillanceHeatmap

A surveillance heatmap of series in data (a Dataset, or a list of datasets of different frequencies): each reading coloured by how unusual it is (normalise: "zscore", "robust_zscore", "pctrank", "level" or "gap") over a trailing window, every period up to the date (window=None) or a reference span. See pymetrix.heatmap for every option; SurveillanceSpec(series, ...).draw(data) is the same, with the settings kept to draw again on newer data. calendar, a ReleaseCalendar, dates the lower-frequency readings by their release days under fill="latest", as as_of(..., calendar=) cuts the data.

Results

ComponentNowcast dataclass

ComponentNowcast(name: str, aggregate: Series, se: Series, components: DataFrame, component_se: DataFrame, weights: DataFrame, contributions: DataFrame, correlation: DataFrame, aggregation: str = 'shares', coverage: float = 0.9, published: DataFrame | None = None, rolled: tuple[str, ...] = (), correlation_source: str = '', provenance: Any = None)

A component bridge's nowcast: the aggregate with its band, and each component's nowcast, share and contribution.

aggregate and se by quarter; components: each component's growth used (its figure where published, else its model's nowcast), with standard errors component_se (0 where published); weights: the previous quarter's nominal shares; contributions: each component's contribution to the aggregate's growth (they add up to it); correlation: of the components' errors.

discrepancy property

discrepancy: float

The largest gap between the aggregate and the sum of the contributions (zero but for rounding).

density

density() -> Any

The aggregate's normal density (a NowcastDensity: interval, scores against outturns).

interval

interval(coverage: float | None = None) -> DataFrame

The aggregate's central interval with probability coverage (default the nowcast's): lower and upper.

to_frame

to_frame(view: str | None = None) -> DataFrame

A row per quarter and component (and the aggregate): growth, standard error, share, contribution, and whether the growth is a published figure.

plot

plot() -> Any

The contributions bar figure: each component's contribution as stacked bars, the aggregate as a line.

FittedBridge dataclass

FittedBridge(spec: Bridge, equation: Any, masked: tuple[str, ...] = ())

A bridge equation estimated: the quarterly equation (equation) and how to nowcast with it.

provenance property

provenance: Any

The bridge equation's provenance (on the quarterly averages of the monthly indicators).

nowcast

nowcast(low: Dataset, high: Dataset, through: Any = None) -> Series

The left-hand side for each quarter after the last observation of the target, through the quarter of the indicators' latest month (or through): missing months forecast, months averaged, the equation applied.

nowcast_density

nowcast_density(low: Dataset, high: Dataset, through: Any = None, coverage: float = 0.9) -> NowcastDensity

The nowcast (as nowcast) with its standard error and a coverage interval.

The variance adds two parts: the equation's forecast variance at the quarterly aggregates (residual and coefficient uncertainty, as FittedEquation.forecast), and the uncertainty of the months filled by each indicator's AR model, carried through the aggregation and the equation by the delta method (exact when the equation is linear in the indicators). The AR forecast errors are correlated across horizons through the AR's moving-average weights and across indicators as their residuals are; the AR coefficients are taken as known.

FittedComponentBridge dataclass

FittedComponentBridge(spec: ComponentBridge, fits: Mapping[str, Any], correlation: DataFrame, provenance: Any = None, correlation_source: str = '')

A component bridge estimated: each component's fitted model (fits) and the correlation of their errors.

fitted.nowcast(q, m) # the aggregate, by quarter fitted.nowcast_components(q, m) # each component's nowcast, share and contribution, with bands fitted.nowcast_density(q, m) # the aggregate's density (a NowcastDensity)

component_nowcasts

component_nowcasts(low: Dataset, high: Dataset, through: Any = None) -> DataFrame

Each component's nowcast by quarter, from its own model exactly as alone: quarters after its last figure, through the quarter of the indicators' latest month (or through).

nowcast

nowcast(low: Dataset, high: Dataset, through: Any = None) -> Series

The aggregate for each quarter after the first quarter a component's figure is missing, through the quarter of the indicators' latest month (or through): components' figures where published, else their nowcasts.

nowcast_frame

nowcast_frame(low: Dataset, high: Dataset, through: Any = None) -> DataFrame

The aggregate (column nowcast) and each component's growth used ("component: gc"...), by quarter: what nowcast_backtest records for a component bridge.

nowcast_components

nowcast_components(low: Dataset, high: Dataset, through: Any = None, coverage: float = 0.9) -> ComponentNowcast

Each component's nowcast with its standard error, share and contribution, and the aggregate with its standard error and a coverage interval (see the module's docstring for how they are combined).

nowcast_density

nowcast_density(low: Dataset, high: Dataset, through: Any = None, coverage: float = 0.9) -> Any

The aggregate nowcast with its standard error and a coverage interval (a NowcastDensity).

table

table() -> DataFrame

Each component: its model, its level series (and deflator) and the standard deviation of its in-sample errors.

FittedDynamicFactor dataclass

FittedDynamicFactor(spec: DynamicFactor, result: Any, provenance: Any = None, masked: DataFrame | None = None)

Bases: BackendResult

A dynamic factor model estimated: factors, nowcasts, and the same model on newer data.

backend_result property

backend_result: Any

The library's own result object (result).

factors property

factors: DataFrame

The smoothed factors, month by month.

loadings property

loadings: DataFrame

How much each series moves with each factor.

nowcast

nowcast(variable: str, through: Any = None) -> Series

variable for each period after its last observation, through the quarter of the latest month (or through): quarterly series by quarter, monthly series by month. Uses all the data (smoothed estimates), so it equals the after value of news.

nowcast_density

nowcast_density(variable: str, through: Any = None, coverage: float = 0.9) -> NowcastDensity

The nowcast (as nowcast) with its standard error and a coverage interval: statsmodels' own variance of the smoothed prediction (get_prediction(...).var_pred_mean), the uncertainty of the factors and the idiosyncratic terms given all the data. The parameters are taken as known (their estimation error is not in it), so the bands are narrower than the nowcast's error out of sample: check them with a backtest.

update

update(low: Dataset | None, high: Dataset) -> FittedDynamicFactor

The same model (parameters unchanged) on newer data: for nowcasts as new figures arrive, and for news.

news

news(previous: FittedDynamicFactor, variable: str, period: Any = None) -> News

How the new figures in this model's data, compared with previous (an earlier update), moved the nowcast of variable for period (default: the quarter of the latest month).

FittedMIDAS dataclass

FittedMIDAS(spec: MIDAS, params: Any, weights: dict[str, Series], resid: Series, fitted: Series, stats: dict[str, float] = dict(), provenance: Any = None)

nowcast

nowcast(low: Dataset, high: Dataset, through: Any = None) -> Series

Predictions for every low-frequency period whose indicator lags are available (to through, default the last period the indicators reach), including periods after the low-frequency data end.

nowcast_density

nowcast_density(low: Dataset, high: Dataset, through: Any = None, coverage: float = 0.9) -> Any

The nowcasts (as nowcast) with forecast standard errors and a coverage interval (a NowcastDensity).

The variance is the regression's residual variance plus the coefficients' uncertainty at the period's indicator values: for U-MIDAS without autoregressive terms exactly least squares' prediction variance, s^2 (1 + z'(Z'Z)^-1 z); for the parametric weights by the delta method (the gradient of the prediction in the slope, the weights' parameters and the constant). With ar, a period whose earlier target values are themselves nowcasts also carries their errors, through the autoregressive coefficients.

plot

plot() -> Any

The estimated lag weights of each indicator.

FittedMixedFrequencyBVAR dataclass

FittedMixedFrequencyBVAR(spec: MixedFrequencyBVAR, panel: _Panel, draws_B: ndarray, draws_sigma: ndarray, draws_z: ndarray, hyperparameters: dict[str, float] = dict(), initial: tuple[ndarray, ndarray] = (zeros(0), zeros(0)), provenance: Any = None)

A mixed-frequency BVAR's posterior draws: coefficients draws_B (draw, regressor, equation: constant first, then lag 1 of each variable, lag 2...), covariances draws_sigma and the completed monthly panel draws_z.

params property

params: DataFrame

The posterior mean of the coefficients: rows the regressors, columns the equations.

monthly

monthly(variable: str | None = None, coverage: float = 0.9) -> DataFrame

A variable's monthly path: the posterior mean and the central coverage band of the draws, by month (for a quarterly variable, the monthly series the model infers).

predictive_draws

predictive_draws(variable: str | None = None, low: Dataset | None = None, high: Dataset | None = None, through: Any = None) -> DataFrame

The posterior predictive draws of each quarter to nowcast (columns; rows the draws): the variable's monthly draws aggregated to quarters. With data, the parameters' draws are kept and the months drawn on these data.

nowcast

nowcast(low: Dataset | None = None, high: Dataset | None = None, through: Any = None, variable: str | None = None) -> Series

The posterior predictive mean of each quarter after the variable's last figure (default: the first quarterly variable). With data, the parameters' draws are kept and only the months are drawn again.

nowcast_density

nowcast_density(low: Dataset | None = None, high: Dataset | None = None, through: Any = None, coverage: float = 0.9, variable: str | None = None) -> Any

The nowcast with the posterior predictive standard deviation, as a NowcastDensity (its interval normal; predictive_draws has the draws for quantiles and sample-based scores).

FittedQuantileBridge dataclass

FittedQuantileBridge(spec: QuantileBridge, fits: dict[float, FittedBridge])

A quantile bridge equation estimated: one FittedBridge (quantile regression) per quantile.

params property

params: DataFrame

The coefficients: rows the terms, columns the quantiles.

nowcast_quantiles

nowcast_quantiles(low: Dataset, high: Dataset, through: Any = None) -> QuantileNowcast

Each quarter after the target's last figure through the indicators' latest quarter (or through): its predicted quantiles (rearranged where they cross) and the skewed t matched to them.

nowcast

nowcast(low: Dataset, high: Dataset, through: Any = None) -> Series

The median nowcast (the 0.5 quantile regression if estimated, else the skewed t's median).

FittedTargetedPredictors dataclass

FittedTargetedPredictors(spec: TargetedPredictors, selection: DataFrame, kept: tuple[str, ...], model: Any)

Targeted predictors chosen and the model estimated on them: kept, the selection table and model.

nowcast

nowcast(low: Dataset, high: Dataset, through: Any = None) -> Series

The variable for each quarter after its last figure: the factor model's parameters kept and the data new (update), or the bridge equation applied.

nowcast_density

nowcast_density(low: Dataset, high: Dataset, through: Any = None, coverage: float = 0.9) -> Any

The nowcast with its standard error and a coverage interval (the model's own nowcast_density).

News dataclass

News(variable: str, period: str, before: float, after: float, details: DataFrame, revisions: float = 0.0, provenance: Any = None)

How new figures moved a nowcast: after - before is the sum of the details impacts plus revisions.

by_series property

by_series: Series

The impact of each series' new figures, added up.

NowcastBacktest dataclass

NowcastBacktest(nowcasts: DataFrame, variable: str, label: str = '', benchmark_label: str = '', provenance: Any = None, densities: DataFrame | None = None, components: DataFrame | None = None)

Nowcasts of each target quarter made on days around its end, from the data as known on each day.

nowcasts has a row per target quarter and day: the day, the quarter, days from the quarter's end (negative before it ends), the stage (forecast before the quarter starts, nowcast within it, backcast after it), the model's nowcast, the benchmark's, the actual value (the latest data, or the release outturn chose), both errors (actual less nowcast), the day the parameters used were estimated (estimated) and, in a real-time backtest, the vintages used (vintage: each series and the date of its vintage).

levels property

levels: tuple[float, ...]

The quantile levels of a quantile model's nowcasts (empty without densities).

component_names property

component_names: list[str]

The components of a component bridge's backtest (empty for any other model).

density_table

density_table() -> DataFrame

Each nowcast's scores against the actual value: the pinball loss at each quantile and their mean, and the skewed t's CRPS, log score and PIT (with the date, quarter, days and stage).

quantile_scores

quantile_scores() -> DataFrame

By days from the quarter's end: n, the mean pinball (quantile) loss at each quantile and their mean, and the share of outturns at or below each quantile (near its level when the quantiles are calibrated).

density_scores

density_scores() -> DataFrame

By days from the quarter's end: n, the mean CRPS (lower is better), mean log score (higher is better) and the PITs' mean and standard deviation (0.5 and 0.29 when uniform), of the skewed-t densities.

pit

pit(days: int | None = None) -> Series

The PITs of the skewed-t densities (every horizon, or those days from the quarter's end), by quarter and days.

component_errors

component_errors() -> DataFrame

Each component's error (its outturn less the growth the component bridge used: its nowcast, or its figure where already published), by nowcast (rows as nowcasts; columns the components). A ComponentBridge(correlation=backtest) estimates the components' error correlation from them.

component_scores

component_scores() -> DataFrame

By days from the quarter's end: each component's RMSE, and the aggregate's (the nowcast column).

selected

selected() -> DataFrame

The series a model with a selection step (targeted predictors) kept, by the day it was estimated.

scores

scores() -> DataFrame

By days from the quarter's end: the stage, n, RMSE, MAE and mean error of the nowcasts and, with a benchmark, its RMSE and MAE, the ratio of RMSEs (below 1: the model is more accurate) and Diebold-Mariano's statistic and p-value (squared errors, Harvey-Leybourne-Newbold correction; negative favours the model).

accuracy

accuracy() -> Table

scores as a table.

compare

compare() -> Table

The model against the benchmark at each horizon: Diebold-Mariano's test of equal accuracy (squared errors).

table

table() -> DataFrame

The nowcasts as a quarter-by-days table (rows: quarters; columns: days from the quarter's end).

path

path(quarter: Any) -> Series

How one quarter's nowcast moved, day by day.

as_backtest

as_backtest() -> Any

The nowcasts as a Backtest (origin: the day; horizon: days from the quarter's end), for the forecast evaluation tools (compare, losses, combine_forecasts).

plot

plot() -> Any

RMSE against days from the quarter's end, the model's and the benchmark's.

NowcastDensity dataclass

NowcastDensity(variable: str, forecast: Series, se: Series, coverage: float = 0.9, source: str = '', provenance: Any = None)

A nowcast with its standard error: a normal density for each period, its interval, and scores against outturns.

density = dfm.nowcast_density("gy")         # or bridge.nowcast_density(q, m), midas.nowcast_density(q, m)
density.to_frame()                          # forecast, se, lower, upper (the ``coverage`` interval)
density.crps(outturn), density.log_score(outturn)   # once the figure is out (a Series, or one number)

forecast equals the model's nowcast. How se is made depends on the model and is in source.

interval

interval(coverage: float | None = None) -> DataFrame

The central interval with probability coverage (default the density's own): columns lower and upper.

to_frame

to_frame(view: str | None = None) -> DataFrame

forecast, se, lower and upper, by period (or the table of the window's view).

log_score

log_score(outturn: Any) -> Series

The log of the predictive density at each outturn (higher is better); periods without one left out.

crps

crps(outturn: Any) -> Series

The continuous ranked probability score at each outturn, in the units of the variable (lower is better).

pit

pit(outturn: Any) -> Series

The predictive probability of a value at or below each outturn.

scores

scores(outturn: Any) -> DataFrame

outturn, error, log score, CRPS and PIT for each period with an outturn.

NowcastRefresh dataclass

NowcastRefresh(day: str, rows: DataFrame, news: DataFrame, history: DataFrame, store: str, report: str = '', provenance: Any = None)

One refresh: rows (the day's nowcasts, as added to the store), news (the figures behind the change since the previous refresh), history (the store after the refresh), and where the store and report are.

plot

plot() -> Any

Each model's nowcasts of the latest quarter in the store, refresh by refresh.

NowcastTracking dataclass

NowcastTracking(variable: str, quarter: str, path: DataFrame, news: DataFrame, actual: float = float('nan'), groups: Mapping[str, tuple[str, ...]] = dict(), label: str = '', provenance: Any = None, components: tuple[str, ...] = ())

A target quarter's nowcast day by day, and what moved it.

path: by day, the nowcast, its change from the day before, the news of the figures published in between, the effect of revisions to earlier figures and of re-estimation, and the stage (forecast, nowcast, backcast). news: one row per new figure (day, period, series, group, observed, expected, news, weight, impact). actual: the outturn in the data given (NaN if not yet known).

parts property

parts: list[str]

The columns of contributions: groups (in the order given, then series in no group), new data for a model without news, then revisions and re-estimation when they moved the nowcast.

discrepancy property

discrepancy: float

The largest gap between a day's change in the nowcast and the sum of its parts (zero but for rounding).

contributions

contributions(cumulative: bool = False, by: str = 'group') -> DataFrame

The change in the nowcast on each day (after the first), by group of series (each series alone when no group names it) plus revisions and re-estimation; cumulative: added up from the first day, so each row sums to the nowcast less the first day's. by: "group" (the default: the groups given, a calendar's releases, or a component bridge's components), "indicator" (each series), "component" (a component bridge's components) or "kind" (news, revisions, re-estimation, new data). Each row adds up to the day's change.

by_group

by_group() -> Series

Each part's total contribution over all the days.

within

within(component: str, cumulative: bool = False) -> DataFrame

A component bridge's tracking: one component's contribution to each day's change, by release (each series' figures, or the release a calendar puts it in, for a dynamic factor model's news) and by part (new data for a model without news, revisions, re-estimation, its own published figure, and changes in the shares or in the other components that move its contribution). Each row adds up to the component's column of contributions.

news_table

news_table() -> Table

Every new figure, with its group.

plot

plot(cumulative: bool = False) -> Any

The tracking chart: the nowcast as steps over stacked bars of each day's contributions by group (with cumulative, the contributions added up since the first day, against the nowcast's change since then), and the outturn when known.

plot_news_flow

plot_news_flow(by: str = 'group', top: int | None = 8) -> Any

The news flow: the nowcast as a step line, one step on each day the data changed, over stacked bars of each day's change split into its parts (positive above zero, negative below), so the bars on a day add up to that day's step; the outturn as a dashed line when known. by: the parts, as in contributions ("group", "indicator", "component" or "kind"); top: how many parts are drawn apart, the largest over the quarter, the rest added up as "other" (None: all). "other" also takes anything the parts leave unexplained, so the bars always add up to the change.

plot_waterfall

plot_waterfall(by: str = 'group', top: int | None = 8) -> Any

From the quarter's first nowcast to its last: each part's contribution over all the days, as floating bars that step from the first nowcast to the last (a waterfall chart), and the outturn when known. by and top as in plot_news_flow, whose colours the parts keep.

contributions_table

contributions_table(by: str = 'group', top: int | None = 8) -> Table

The news flow's numbers: on each day, the nowcast, its change and the parts of the change (as plot_news_flow draws them), the part that moved it most and the series released; the last row the totals from the first day's nowcast to the last.

QuantileNowcast dataclass

QuantileNowcast(variable: str, predicted: DataFrame, skewt: DataFrame, source: str = '', provenance: Any = None)

Quantile nowcasts of each quarter and the skewed t matched to them.

now.predicted # quarter by quantile now.at_risk() # growth at risk (5%), expected shortfall, median now.density("2025Q1") # the skewed-t density on a grid now.scores(outturn) # pinball loss at each quantile, CRPS, log score and PIT, once the figure is out

median property

median: Series

The median: the 0.5 quantile if estimated, else the skewed t's.

knot_gap property

knot_gap: Series

For each period, the largest distance between the skewed t's quantile and the fitted one at the four knots (0.05, 0.25, 0.75, 0.95): near zero when the four parameters match the four quantiles, as they usually do; larger when the quantiles have thinner tails than a normal (the degrees of freedom then reach their bound, 60).

quantile

quantile(level: float) -> Series

The skewed t's level quantile for each period.

at_risk

at_risk(level: float = 0.05) -> DataFrame

Growth at risk (the skewed t's level quantile), the expected shortfall below it and the median.

density

density(period: Any = None, grid: Any = None) -> Series

The skewed-t density of one period (default: the last) on grid (default: 400 points over six scales).

to_frame

to_frame(view: str | None = None) -> DataFrame

The quantiles, the skewed t's parameters, growth at risk and expected shortfall by period.

scores

scores(outturn: Any) -> DataFrame

For each period with an outturn: the pinball loss at each quantile and their mean, and the skewed t's CRPS, log score and PIT.

plot

plot() -> Any

The latest period's density, with a line at growth at risk (5%).

SurveillanceHeatmap dataclass

SurveillanceHeatmap(spec: SurveillanceSpec, values: DataFrame, raw: DataFrame, latest: DataFrame, history: DataFrame, weights: Series, groups: dict[str, str] = dict(), kinds: dict[str, str] = dict(), linkage: ndarray | None = None, leaves: tuple[str, ...] = (), bands: DataFrame | None = None, provenance: Any = None)

A surveillance heatmap: values (rows: the indicators, their groups' averages and the composite; columns: the dates shown), raw (the readings themselves, on the same calendar), latest (each row's latest reading, its normalised value and its changes), history (every date's normalised values, dates down the side), weights (the composite's), groups (each row's group), linkage (the clustering, when ordered by it) and bands (the regimes drawn above the dates). spec holds the settings: redraw(newer) draws it again.

label property

label: str

What the colours show: "percentile rank (40-period window)", "z-score (against 2010Q1 to 2019Q4)".

table

table() -> Table

The normalised values: rows the indicators (and groups and composite), columns the dates shown.

raw_table

raw_table() -> Table

The readings themselves on the heatmap's calendar (before normalising or flipping).

latest_table

latest_table() -> Table

Each row's latest reading: its date, value, normalised value, and the change in the normalised value over each of changes periods.

to_frame

to_frame(view: str | None = None) -> DataFrame

The normalised values, rows the indicators, columns the dates shown.

plot

plot() -> Figure

The heatmap: indicators down the side, dates across, the regimes (if any) as bands above.

latest_plot

latest_plot() -> Figure

Each row's latest normalised reading as a one-column heatmap, with its value written in.

dendrogram

dendrogram() -> Figure

The clustering of the rows by their correlations (when order="cluster"): average linkage on 1 - correlation, leaves in the heatmap's order.

redraw

redraw(data: Any, span: tuple[Any, Any] | None = None, regimes: Any = None) -> SurveillanceHeatmap

The same heatmap (spec) on newer data.