Skip to content

Forecasting & forecast evaluation

The classes and functions of the row "Forecasting & forecast evaluation" 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: The forecast workflow, Growth at risk, Fan charts and the balance of risks, Early-warning signals and ROC analysis.

How do I: Run a forecast round: baseline, judgement, scenarios, report, Check a forecast's record (backtest), Evaluate early-warning signals of crises.

Classes

ForecastStore

ForecastStore(folder: str | Path)

A folder of forecast rounds: one Parquet file of paths and one JSON record per round.

revisions

revisions(old: str, new: str, variables: Sequence[str] | None = None) -> DataFrame

Two rounds side by side, with the revision (new less old), period by period: columns <v> (<round>) and <v> revision, indexed by period.

compare

compare(old: str, new: str, variables: Sequence[str] | None = None) -> Table

revisions as a table.

history

history(variable: str) -> DataFrame

The path of variable in every round, one column per round.

plot_history

plot_history(variable: str, data: Dataset | None = None) -> Any

Every round's path of variable against what happened (a "hedgehog" chart).

accuracy

accuracy(variable: str, data: Dataset, horizons: int | None = None) -> Table

scores as a table.

scores

scores(variable: str, data: Dataset, horizons: int | None = None) -> DataFrame

Real-time accuracy of the rounds by horizon (periods after each round's last data): n, RMSE, MAE, mean error.

Functions

backtest

backtest(fitted: Any, data: Dataset, origins: tuple[Any, Any], horizon: int = 8, vintages: Mapping[Any, Dataset] | None = None, variable: str | None = None, label: str = '', window: int | None = None) -> Backtest

Re-estimate at each origin from origins[0] to origins[1] and forecast horizon periods ahead.

fitted is a fitted equation or VAR (its specification and method are re-estimated on data up to each origin), another fitted model that keeps its specification (spec, e.g. exponential smoothing), a specification with fit(data, span=...), or a function (data, origin) -> fit. With vintages (origin -> the dataset as it was then) each origin uses the data available at the time; errors are always measured against data (the latest release). window: estimate on the last window periods to each origin (a rolling window) instead of all of them (an expanding window). variable names a single-equation forecast's column (default: the fit's dependent variable); it was called target.

Each forecast keeps its predictive standard deviation (sd) and its density is scored against the outcome (log score, crps, pit): as a normal, or from the simulated draws of fits that make them (Bayesian VARs). See density_scores and evaluation.

A logit or probit equation forecasts the probability of the event from its regressors in each target period (so lag them for genuine forecasts): each row's log score is the log of the probability given to what happened, and its squared error the Brier score. See probability_scores, calibration and plot_calibration.

binary_scores

binary_scores(probabilities: Any, outcomes: Any, threshold: float = 0.5, data: Any = None) -> Any

Probability forecasts of a 0/1 outcome at a glance: Brier score (and the base rate's), log score, ROC area, and the hit rate, false-alarm rate and Kuipers score of forecasting an event when the probability is at least threshold. With data (a dataset), probabilities and outcomes name its series, over its active sample.

choose_threshold

choose_threshold(scores: Any, outcomes: Any, direction: Literal['above', 'below', 'auto'] = 'above', criterion: Literal['usefulness', 'youden', 'noise_to_signal'] = 'usefulness', mu: float = 0.5, cost_ratio: float | None = None, loss: Literal['sarlin', 'alessi_detken'] = 'sarlin', min_signals: float | int | None = None, thresholds: Any = None, alpha: float = 0.05, threshold_by: Literal['pooled', 'entity'] = 'pooled', entities: Any = None, data: Any = None) -> ThresholdChoice

The signalling threshold that minimises the policymaker's loss (criterion="usefulness", Sarlin 2013; or Alessi and Detken 2011 with loss="alessi_detken"), maximises the Youden index or Kuipers score ("youden"), or minimises KLR's noise-to-signal ratio ("noise_to_signal"), with the whole trade-off.

mu is the weight on missing an event against a false alarm (0.5: equal), or give cost_ratio (a miss costs c false alarms: mu = c / (1 + c)). Candidate thresholds are every distinct score (default), k quantiles (an int: KLR's percentile grid), or those given. min_signals keeps only thresholds with at least that many signals (a share of the observations if below 1); by default a tenth of the observations for the noise-to-signal ratio, which a single lucky signal would otherwise drive to zero (KLR searched thresholds signalling in 10 to 20 per cent of the periods), and none for the others.

threshold_by="entity": in a panel, each entity (country) gets its own threshold, the same percentile of its own distribution of the scores (Kaminsky, Lizondo and Reinhart 1998), rather than one level for all; the common percentile is searched over thresholds (default 1% to 99% by 1%; an int k: 1/k, ..., (k-1)/k; or a list of percentiles) by the same criterion. Each entity's percentiles are those of its scores as given (linear interpolation, numpy's and R's default; at least two scores each). entities labels each observation's entity (a series aligned with the scores, or one label per observation used); panel data's own entities by default. The chosen percentile is threshold and each entity's level levels.

classification_table

classification_table(scores: Any, outcomes: Any, threshold: float = 0.5, direction: Literal['above', 'below'] = 'above', alpha: float = 0.05, mu: float = 0.5, loss: Literal['sarlin', 'alessi_detken'] = 'sarlin', data: Any = None) -> ClassificationTable

The 2 x 2 table of signals against outcomes at a threshold, with the hit rate (sensitivity), specificity, false-alarm rate, precision, negative predictive value, accuracy, balanced accuracy, F1, Kuipers score (Youden J), KLR's noise-to-signal ratio, the odds ratio and the policymaker's usefulness; Wilson intervals at 1 - alpha.

scores signal when at or above threshold (direction="below": at or below): a probability with the default 0.5, or 0/1 signals as they are. outcomes are 0/1 (the event, or the pre-event target of event_windows). With data, both name its series, over its active sample.

combine_forecasts

combine_forecasts(backtests: Mapping[str, Backtest] | Sequence[Backtest], method: str = 'equal', min_history: int = 4, label: str = '') -> Backtest

Combine the forecasts of several backtests into one, and evaluate it as a backtest of its own.

method: "equal" (the simple average, hard to beat in practice), "inverse_mse" (weights in proportion to 1 / MSE: Bates and Granger without correlations) or "regression" (least squares weights that sum to one: Granger and Ramanathan; they can be negative). Weights are estimated in real time, for each variable and horizon: at each origin only from forecasts whose outcomes were known by then (targets up to the origin), and equal until min_history such forecasts exist (and more than the number of members, for regression weights). Forecasts are matched on origin, target, horizon and variable.

Where every member has a predictive standard deviation and no weight is negative, the combination's density is the linear pool of the members' normal densities (their weighted mixture), and it is scored. weights holds every weight used.

diebold_mariano

diebold_mariano(e1: ndarray, e2: ndarray, horizon: int = 1, loss: str = 'squared', small_sample: bool = True) -> TestResult

Diebold-Mariano (1995) test that two forecasts are equally accurate, from their errors at one horizon.

The loss differential's variance allows for the MA(h-1) correlation of h-step errors; small_sample applies the Harvey, Leybourne and Newbold (1997) correction and Student-t p-values. A negative statistic means the first forecast is more accurate.

early_warning

early_warning(data: Any, indicators: Sequence[str], events: str, horizon: Any = 8, post: int = 0, exclude_events: bool = True, direction: Any = 'auto', criterion: Literal['usefulness', 'youden', 'noise_to_signal'] = 'usefulness', mu: float = 0.5, cost_ratio: float | None = None, loss: Literal['sarlin', 'alessi_detken'] = 'sarlin', min_signals: float | int | None = None, alpha: float = 0.05, method: Literal['delong', 'bootstrap'] = 'delong', draws: int = 2000, seed: int = 0, resample: Literal['stratified', 'cluster', 'block'] = 'stratified', block: int | None = None, sort: Literal['auroc', 'usefulness', 'noise_to_signal'] = 'auroc', threshold_by: Literal['pooled', 'entity'] = 'pooled', fixed_thresholds: Mapping[str, float] | None = None, model: Literal['logit', 'probit'] | None = None, model_indicators: Sequence[str] | None = None, origins: Any = None, window: int | None = None, min_events: int = 1) -> EarlyWarning

Evaluate many candidate early-warning indicators of the 0/1 series events (1 in every period of a crisis) at once, and rank them.

The target is an event starting within horizon periods (event_windows, with post periods after each event and, by default, the events themselves left out; horizon=0: the events themselves). For each indicator, on the periods it is observed: its direction ("auto", "above", "below", or a mapping by indicator, the rest auto), its AUROC with an interval at 1 - alpha (roc_analysis: DeLong or a bootstrap, draws and seed) and DeLong's paired test against the best, the threshold choose_threshold picks (criterion, mu or cost_ratio, loss, min_signals) with its hit rate, false-alarm rate, noise-to-signal ratio and usefulness, and from its signals the share of events called (a signal in the pre-event window) and the average lead time (periods from the first signal to the event). Sorted by AUROC, usefulness or noise-to-signal.

threshold_by="entity" (panels): each entity's threshold is the same percentile of its own distribution of the indicator (all its observed values; Kaminsky, Lizondo and Reinhart 1998), the common percentile chosen from 1% to 99%; the AUROC is then that of the percentile ranks. fixed_thresholds holds some indicators' thresholds at given values (a level; a percentile by entity) instead of choosing them, as a rule of thumb would (their direction must then be given). model="logit" or "probit" adds a multivariate early-warning model: the binary-choice model of the target on model_indicators (default all), its fitted probability evaluated as one more indicator (named "logit model"; one threshold for all); model on the result holds its coefficients.

Out of sample (origins: the first period to score, or (first, last); (None, None) for all): each period is scored with the threshold, direction and model chosen from the data up to the period before it, and an outcome is used only once its window has passed (a publication lag equal to the horizon's end), so nothing is learnt from the future (Alessi and Detken 2011; Holopainen and Sarlin 2017). window: a rolling window of that many periods of resolved outcomes (and of the entity percentiles' history) instead of all of them (recursive, expanding); min_events: a period is scored only once that many events' pre-event windows are known. The result's out_of_sample compares the out-of-sample AUROC (with its interval), hit and false-alarm rates, usefulness and events called with the in-sample ones.

event_windows

event_windows(events: Any, horizon: Any = 8, post: int = 0, exclude_events: bool = True, censor: bool = True, data: Any = None) -> DataFrame

The early-warning target and evaluation sample from a 0/1 event series (1 in every period of a crisis).

A frame with, for each period: event; onset (1 in an event's first period); target, 1 when an event starts within horizon periods (8: in the next 8; (5, 12): between 5 and 12 ahead, the periods closer than 5 left out as "too close"; 0: the events themselves); include, whether to evaluate the period; status (pre-event, calm, event, post-event, too close, unknown); periods to event; and next event, the period the coming event starts. Events' own periods are left out unless exclude_events=False, and the post periods after each event ends (Bussiere and Fratzscher's post-crisis bias); a period after one event and before the next is pre-event. censor: a period whose window runs past the data (or through missing values) without an event is unknown, so left out. Panel data (entity x period) get windows per entity. With data, events names its series.

fan_chart

fan_chart(forecast: Any, variable: str | None = None, uncertainty: Any = None, skew: Any = 0.0, backtest: Any = None, skew_measure: str = 'mean-mode', thresholds: Sequence[float] | float | None = None, bands: str = 'highest-density', coverages: Sequence[float] = COVERAGES, quantiles: Sequence[float] = QUANTILES, data: Dataset | None = None, label: str = '') -> FanChart

A fan chart of a forecast with a judgemental balance of risks: each period's two-piece normal has the forecast path as its mode, an uncertainty and a skew (Britton, Fisher and Whitley 1998; see the module notes).

forecast is a forecast round (ForecastRound), a forecast (the dataset Estimate > Forecast makes), a DataFrame of paths or a Series; variable picks one of its variables. The uncertainty sigma of each period comes from, in turn: uncertainty (one number, one per period, or a mapping of period or horizon to value); the root mean squared error at each horizon of a backtest of the variable, as the Bank of England sets its uncertainty from its past forecast errors; or the forecast's own standard errors. skew (one number, one per period, or a mapping; zero elsewhere) is the judgement: the mean less the mode (skew_measure="mean-mode", the Bank's measure), or the Bank's gamma ("gamma").

The horizon of each period counts from the last period of data: the round's, else the last value of the variable in data, else the period before the forecast starts. thresholds adds the probabilities of being below and above each; quantiles sets the quantile table, coverages the bands of the chart (10% to 90% in steps of 10%, as the Bank's) and bands their kind: "highest-density" (the Bank's: the narrowest band with each probability, around the mode) or "equal-tailed" (between quantiles). data also gives the history the chart starts from.

forecast_accuracy

forecast_accuracy(actual: Series, forecasts: Series | Mapping[str, Series]) -> Table

RMSE, MAE, MAPE and Theil's U for one or more forecasts of the same series.

Observations where the actual or a forecast is missing are skipped.

growth_at_risk

growth_at_risk(data: Dataset, growth: str, regressors: Sequence[str], horizons: Sequence[int] = (1, 4), quantiles: Sequence[float] = (0.05, 0.25, 0.5, 0.75, 0.95), span: Any = None) -> GrowthAtRisk

Quantile local projections of growth averaged over each horizon on regressors, and a skewed t fitted to each period's predicted quantiles (see the module notes).

model_confidence_set

model_confidence_set(losses: Mapping[str, Any], alpha: float = 0.1, horizon: int = 1, draws: int = 1000, block: int | None = None, seed: int = 0) -> Any

The model confidence set of Hansen, Lunde and Nason (2011): the models that contain the best one with probability 1 - alpha, from their losses (one series per model), with the stationary bootstrap (arch's MCS, range statistic). A table: each model's average loss, its MCS p-value, and whether it is in the set.

roc_analysis

roc_analysis(scores: Any, outcomes: Any, direction: Literal['above', 'below', 'auto'] = 'above', alpha: float = 0.05, method: Literal['delong', 'bootstrap'] = 'delong', draws: int = 2000, seed: int = 0, resample: Literal['stratified', 'cluster', 'block'] = 'stratified', clusters: Any = None, block: int | None = None, partial: Any = None, data: Any = None) -> ROCAnalysis

The ROC curve of scores against 0/1 outcomes, and its area (AUROC) with an interval at 1 - alpha.

method="delong": DeLong, DeLong and Clarke-Pearson's (1988) variance, the interval AUROC +/- z se (clipped to 0 and 1), as pROC's ci.auc. "bootstrap": draws resamples with seed, the percentile interval and a pointwise band for the curve; resample events and non-events separately ("stratified", pROC's default), whole entities ("cluster": panel data's entities, or clusters= labels), or moving blocks of block consecutive periods (default n^(1/3); within each entity of a panel) for serially correlated signals. partial (0.2, or a range (0, 0.2)) adds the partial AUC over those false-alarm rates, standardised as McClish (1989). direction="below": low scores signal; "auto": whichever gives an AUROC of at least 0.5.

roc_compare

roc_compare(scores: Any, outcomes: Any, reference: str | None = None, contrast: Any = None, direction: Literal['above', 'below', 'auto'] = 'above', method: Literal['delong', 'bootstrap'] = 'delong', partial: Any = None, draws: int = 2000, seed: int = 0, data: Any = None) -> TestResult

Do several indicators (or models) scored on the same periods have the same AUROC? DeLong, DeLong and Clarke-Pearson's (1988) chi-square test of K correlated areas.

scores: a mapping of names to scores, or a list of series (names of data's series, with data). With the areas theta and their covariance S (DeLong's, from the placements; or, method="bootstrap", the covariance of draws paired stratified bootstrap draws with seed), a contrast matrix L gives the Wald statistic (L theta)' (L S L')^-1 (L theta), chi-square with rank(L) degrees of freedom. By default L compares each area with the reference (default: the first), so the null is that all K are equal (any full set of K - 1 contrasts gives the same statistic); contrast (rows of K weights summing to 0) tests other hypotheses. Each comparison with the reference is also given on its own (a normal statistic, as roc_test) with Holm's (1979) adjustment for the K - 1 comparisons. partial (0.2, or (0, 0.2)) compares McClish-standardised partial AUCs instead, by the bootstrap only (as pROC). For two scores the statistic is the square of roc_test's.

roc_test

roc_test(scores1: Any, scores2: Any, outcomes: Any, outcomes2: Any = None, method: Literal['delong', 'bootstrap'] = 'delong', direction: Literal['above', 'below', 'auto'] = 'above', draws: int = 2000, seed: int = 0, partial: Any = None, data: Any = None) -> TestResult

Do two indicators (or models) have the same AUROC? DeLong, DeLong and Clarke-Pearson's (1988) test.

Paired (outcomes2 not given): both score the same observations, so their AUROCs are correlated; the statistic (AUC1 - AUC2) / sqrt(V1 + V2 - 2 C) is standard normal. Unpaired (outcomes2: the second scores' own outcomes, say another set of countries): (AUC1 - AUC2) / sqrt(V1 + V2), Student's t with Welch's degrees of freedom, as pROC's roc.test. method="bootstrap" (paired only): the difference over the standard deviation of its stratified bootstrap (draws, seed), normal. Two-sided; direction applies to both.

partial (0.2, or a range (0, 0.2) of false-alarm rates) compares the partial AUCs instead, standardised as McClish (1989): by the paired bootstrap only, as pROC (DeLong's variance is for the whole area). The standardisation is the same linear map for both curves, so the statistic is that of the raw partial areas.

spa

spa(benchmark: Any, models: Mapping[str, Any], horizon: int = 1, draws: int = 1000, block: int | None = None, seed: int = 0) -> TestResult

Hansen's (2005) test for superior predictive ability: does any of models have lower expected loss than the benchmark? From the losses (one series per model), with the stationary bootstrap (arch's SPA).

details give the consistent p-value (the test), the lower and upper bounds (the upper is White's 2000 Reality Check), and the model with the lowest average loss. block is the mean block length (default the larger of the horizon and n^(1/3)).

Results

Backtest dataclass

Backtest(errors: DataFrame, label: str = '', provenance: Any = None, weights: Any = None)

Forecasts from each origin, with what happened: one row per origin, horizon and variable.

errors has the origin, target, horizon, variable, forecast, actual and error of each forecast, and, where the forecast has a density, its standard deviation (sd), how the density was formed (density) and its scores (log score, crps, pit). A combination (combine_forecasts) also has its weights.

scores

scores(variables: Sequence[str] | None = None) -> DataFrame

n, RMSE, MAE and mean error by variable and horizon (a two-level index).

accuracy

accuracy(variables: Sequence[str] | None = None) -> Table

scores as a table.

losses

losses(variable: str, horizon: int, loss: str = 'squared', tau: float = 0.5, a: float = 1.0) -> Series

The loss of each forecast of variable at horizon, by target period: the "squared" or "absolute" error, the asymmetric "lin-lin" (with tau) or "linex" (with a) loss of the error, the "crps", or the negative "log score" (so that lower is better for all of them).

compare

compare(other: Backtest, variable: str, horizon: int, loss: str = 'squared', test: str = 'diebold-mariano', tau: float = 0.5, a: float = 1.0) -> TestResult

Test whether these forecasts and other's are equally accurate at one horizon, on the targets both forecast.

test: "diebold-mariano" (with the Harvey-Leybourne-Newbold correction; a negative statistic favours these forecasts), "giacomini-white" (conditional predictive ability), or "clark-west" when these forecasts come from a model that other's model nests (does the larger model forecast better?). loss (not for Clark-West, which uses squared errors): "squared", "absolute", "lin-lin" (tau), "linex" (a), "crps" or "log score"; the last two compare density forecasts. See losses.

encompasses

encompasses(other: Backtest, variable: str, horizon: int = 1) -> TestResult

Do these forecasts encompass other's (Harvey, Leybourne and Newbold), on the targets both forecast?

spa

spa(models: Mapping[str, Backtest], variable: str, horizon: int = 1, loss: str = 'squared', tau: float = 0.5, a: float = 1.0, draws: int = 1000, block: int | None = None, seed: int = 0) -> TestResult

Hansen's (2005) test for superior predictive ability, these forecasts the benchmark: does any of models (backtests, by name) forecast variable at horizon with lower expected loss? Each backtest's losses (loss, tau, a as there) go to pymetrix.spa, with its stationary bootstrap (draws, mean block length, seed). Needs the arch package.

efficiency

efficiency(variable: str, horizon: int = 1) -> TestResult

Mincer-Zarnowitz test that the forecasts are efficient: outcome = a + b forecast, with a = 0 and b = 1.

density_scores

density_scores(variables: Sequence[str] | None = None) -> DataFrame

By variable and horizon: n, the average log score (higher is better), the average CRPS (lower is better, in the variable's units), and the shares of outcomes inside the central 50% and 90% predictive intervals (0.5 and 0.9 when the densities are well calibrated). Empty when the forecasts have no densities.

density_accuracy

density_accuracy(variables: Sequence[str] | None = None) -> Table

density_scores as a table, saying how the densities were formed.

probability_scores

probability_scores(variables: Sequence[str] | None = None) -> DataFrame

A logit or probit backtest's scores by variable and horizon: n, the share of events, the Brier score (lower is better) and the base rate's (the share of events in the outcomes, forecast every time), the Brier skill score (1 - Brier / base rate's; above 0 beats it), the average log score (higher is better) and the ROC area.

probability_accuracy

probability_accuracy(variables: Sequence[str] | None = None) -> Table

probability_scores as a table.

calibration

calibration(variable: str | None = None, horizon: int = 1, bins: int = 10) -> DataFrame

The reliability of the probability forecasts at horizon: the forecasts put in bins equal-width bins of probability, with each bin's count, average forecast and share of events (they match for well-calibrated forecasts).

calibration_table

calibration_table(variable: str | None = None, horizon: int = 1, bins: int = 10) -> Table

calibration as a table, the empty bins left out.

plot_calibration

plot_calibration(variable: str | None = None, horizon: int = 1, bins: int = 10) -> Any

The reliability diagram: each bin's share of events against its mean forecast, with the diagonal of perfect calibration.

pit

pit(variable: str, horizon: int = 1) -> Series

The probability integral transforms of the forecasts of variable at horizon, by target period.

pit_test

pit_test(variable: str, horizon: int = 1) -> TestResult

Berkowitz test that the PITs are independent and uniform (for one-step forecasts: h-step PITs are correlated).

interval_test

interval_test(variable: str, horizon: int = 1, coverage: float = 0.9) -> TestResult

Christoffersen test of the central coverage predictive intervals: the right share of outcomes falls outside them, and the misses do not cluster.

summary

summary() -> Table

The backtest's evaluation table, as evaluation() gives it: what every result answers.

evaluation

evaluation(variables: Sequence[str] | None = None, coverage: float = 0.9) -> Table

The tests of each variable and horizon at a glance (p-values): Mincer-Zarnowitz efficiency, and for density forecasts the Berkowitz test of the PITs and the Christoffersen test of the coverage intervals.

weights_table

weights_table() -> Table

A combination's average weight on each member, by variable and horizon.

plot_pit

plot_pit(variables: Sequence[str] | None = None, horizon: int = 1, bins: int = 10) -> Any

Histograms of the PITs at horizon, as densities (1 throughout for well-calibrated forecasts): a hump means the predictive densities are too wide, a U too narrow, a slope a biased forecast.

plot

plot(variables: Sequence[str] | None = None) -> Any

RMSE by horizon for each variable.

ClassificationTable dataclass

ClassificationTable(tp: int, fp: int, fn: int, tn: int, threshold: float, direction: str = 'above', alpha: float = 0.05, mu: float = 0.5, loss: str = 'sarlin', label: str = '', provenance: Any = None)

Signals against outcomes at one threshold: the counts tp (A: signal and event), fp (B: false alarm), fn (C: missed event) and tn (D: neither), and the rates and scores they give (rates()), with Wilson intervals at 1 - alpha for the proportions and Woolf's for the odds ratio. mu and loss set the usefulness (see the module).

hit_rate property

hit_rate: float

A / (A + C): the share of events signalled (sensitivity, power, true positive rate).

specificity property

specificity: float

D / (B + D): the share of calm periods without a signal.

false_alarm_rate property

false_alarm_rate: float

B / (B + D) = 1 - specificity (type II error rate, false positive rate).

precision property

precision: float

A / (A + B): the share of signals followed by an event (positive predictive value).

npv property

npv: float

D / (C + D): the share of quiet periods that were calm (negative predictive value).

kuipers property

kuipers: float

The Kuipers score (Youden's J): hit rate less false-alarm rate.

noise_to_signal property

noise_to_signal: float

KLR's noise-to-signal ratio: [B / (B + D)] / [A / (A + C)]; below 1 the signals beat noise.

odds_ratio property

odds_ratio: float

(A D) / (B C): the odds of an event after a signal over the odds without one.

rates

rates() -> DataFrame

Each rate and score: its value, the counts it is made of, and its interval (Wilson for the proportions, Woolf's log interval for the odds ratio; none for the others).

counts

counts() -> DataFrame

The 2 x 2 table: signal or not (rows) against event or not (columns), with totals.

EarlyWarning dataclass

EarlyWarning(ranking: DataFrame, rocs: Mapping[str, ROCAnalysis], thresholds: Mapping[str, ThresholdChoice], leads: Mapping[str, DataFrame], windows: DataFrame, data: DataFrame, events: str, horizon: Any, post: int, criterion: str, mu: float, alpha: float, method: str, provenance: Any = None, threshold_by: str = 'pooled', scores: DataFrame | None = None, model: Series | None = None, out_of_sample: OutOfSampleSignals | None = None)

Candidate early-warning indicators, each judged by how well it signals the coming events: ranking (one row per indicator, best AUROC first: direction, sample, AUROC with its interval and DeLong p-value against the best, the chosen threshold, hit and false-alarm rates, noise-to-signal ratio, usefulness, share of events called and average lead time); for each indicator its rocs, thresholds (a ThresholdChoice) and leads (each event: called or not, first signal, lead time); windows, the event windows (event_windows); data the series evaluated (with a model's in-sample probability, if any); and the settings. With threshold_by="entity" each threshold is a common percentile of each entity's own distribution, and scores the percentile ranks the ROC curves are of. model: the logit or probit early-warning model's coefficients, fitted on the whole sample; out_of_sample: the recursive or rolling evaluation (OutOfSampleSignals), if asked for.

indicators property

indicators: list[str]

The indicators, best AUROC first.

classification

classification(indicator: str | None = None, alpha: float | None = None) -> ClassificationTable

The classification table of indicator (default the best) at its chosen threshold.

compare

compare(first: str, second: str, method: Literal['delong', 'bootstrap'] = 'delong', draws: int = 2000, seed: int = 0) -> TestResult

DeLong's paired test of two indicators' AUROCs, on the periods both are observed.

compare_all

compare_all(indicators: Sequence[str] | None = None, reference: str | None = None, method: Literal['delong', 'bootstrap'] = 'delong', draws: int = 2000, seed: int = 0) -> TestResult

DeLong's chi-square test that several indicators' AUROCs are equal (roc_compare; default all of them, against the best), on the periods all are observed.

roc_plot

roc_plot(indicators: Sequence[str] | None = None) -> Figure

The ROC curves of two indicators (default the two best), each with its chosen threshold marked.

threshold_plot

threshold_plot(indicator: str | None = None) -> Figure

Hit rate, specificity and relative usefulness against the threshold (default the best indicator).

signal_plot

signal_plot(indicator: str | None = None, entity: Any = None) -> Figure

The indicator over time with its threshold, the events shaded and the pre-event windows as a band; in a panel, for one entity (default the first with an event).

out_of_sample_table

out_of_sample_table() -> Table

In-sample against out-of-sample: AUROC (with the out-of-sample interval), hit and false-alarm rates, usefulness and the share of events called, by indicator.

model_table

model_table() -> Table

The early-warning model's coefficients on the whole sample (and their range across the out-of-sample dates).

threshold_path_plot

threshold_path_plot(indicators: Sequence[str] | None = None) -> Figure

The thresholds chosen at each evaluation date, out of sample (default the two best indicators).

FanChart dataclass

FanChart(variable: str, parameters: DataFrame, levels: tuple[float, ...] = QUANTILES, coverages: tuple[float, ...] = COVERAGES, thresholds: tuple[float, ...] = (), bands: str = 'highest-density', history: Series | None = None, label: str = '', provenance: Any = None)

A forecast's fan chart: by period, a two-piece normal whose mode is the forecast path, with the uncertainty and skew (the balance of risks) of each horizon; its quantiles, bands and the probabilities of being above or below thresholds. See fan_chart.

distribution property

distribution: TwoPieceNormal

Every period's two-piece normal, as one (array-valued) distribution.

quantiles

quantiles(levels: Sequence[float] | None = None) -> DataFrame

The quantiles by period (columns: the levels, 0.05 ... 0.95 by default).

band_edges

band_edges(coverages: Sequence[float] | None = None) -> DataFrame

Each band's lower and upper edge by period (lo90, hi90, ...), as the chart draws them.

probabilities

probabilities(thresholds: Sequence[float] | None = None) -> DataFrame

By period, the probability of being below and above each threshold.

density

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

One period's density (default: the last), on grid or a grid over its 0.1% to 99.9% quantiles.

scores

scores(actual: Any) -> DataFrame

Each period's density scored against what happened (a Series by period, or a Dataset holding the variable): the outturn, the PIT, the log score and the CRPS; periods without an outturn are left out.

table

table() -> Table

The parameters by period: horizon, mode, uncertainty, skew, the two standard deviations, mean, median.

summary

summary() -> Table

The parameters and, with thresholds, the probabilities, by period.

plot

plot(history: int = 16) -> Figure

The fan: the forecast's bands (the darkest the narrowest, around the mode), after the recent history, with each threshold as a dashed line.

ForecastRound dataclass

ForecastRound(name: str, paths: DataFrame, made: str = (lambda: isoformat(timespec='seconds'))(), data_end: str | None = None, notes: str = '', adjustments: tuple[dict[str, Any], ...] = (), source: Mapping[str, Any] = dict(), base: DataFrame | None = None, history: DataFrame | None = None, conditions: tuple[dict[str, Any], ...] = (), provenance: Any = None)

The forecast paths of one round, with their record: when, from which data, notes, source, judgement and the conditions it was made under (a conditional forecast's paths and ranges, or a model plan's holds).

from_forecast classmethod

from_forecast(name: str, forecast: Any, variables: Sequence[str] | None = None, data: Dataset | None = None, notes: str = '', source: Mapping[str, Any] | None = None, as_name: str | None = None, conditions: Sequence[Mapping[str, Any]] | None = None) -> ForecastRound

A round from a forecast: an equation's (as_name names its variable), a VAR's or Bayesian VAR's, or a model Solution (give variables and keep only the forecast periods). data sets data_end.

The round records the conditions the forecast was made under: a VAR's conditional forecast's (exact values and ranges, and the shocks that met them) or a model plan's holds and ranges, read from the forecast; or give conditions as rows such as {"variable": "r", "period": "2026Q1", "value": 2.0} or {"variable": "pi", "period": "2026Q1", "lower": 3.0, "upper": 4.0}.

adjust

adjust(variable: str, values: Mapping[Any, float] | float, reason: str, how: str = 'add') -> ForecastRound

Judgement: add to (how="add") or replace ("set") the path of variable in some periods (a mapping) or all of them (a number). Each change is logged with reason; the path before judgement is kept.

judgement

judgement() -> Table

Every adjustment: period, the path before, after, and why.

conditions_table

conditions_table() -> Table

The conditions the round was made under: what, when, the value or range, and the shocks that met them.

summary

summary() -> Table

The round's paths as a table, as table() gives them: what every result answers.

plot

plot(data: Dataset | None = None, variables: Sequence[str] | None = None, history: int = 16, coverages: Sequence[float] = (0.3, 0.6, 0.9)) -> Any

A fan chart of each variable, after its recent history: from data when given, else the history the round kept when it was made.

fan

fan(variable: str | None = None, uncertainty: Any = None, skew: Any = 0.0, backtest: Any = None, skew_measure: str = 'mean-mode', thresholds: Sequence[float] | float | None = None, bands: str = 'highest-density', data: Dataset | None = None) -> FanChart

The round's fan chart of variable with a balance of risks: a two-piece normal around its path, with the uncertainty given, from a backtest's errors by horizon or from the round's standard errors, and the skew of judgement (pymetrix.fan_chart, which has the details).

GrowthAtRisk dataclass

GrowthAtRisk(dependent: str, regressors: tuple[str, ...], horizons: tuple[int, ...], levels: tuple[float, ...], fits: dict[tuple[int, float], Any], predicted: dict[int, DataFrame], skewt: dict[int, DataFrame], provenance: Any = None)

Quantile projections of future growth, and the skewed-t distribution fitted to each period's quantiles.

quantiles

quantiles(horizon: int | None = None) -> DataFrame

The predicted quantiles by period (rearranged where they cross).

at_risk

at_risk(horizon: int | None = None, level: float = 0.05) -> DataFrame

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

density

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

The fitted skewed-t density for one period (default: the last).

ROCAnalysis dataclass

ROCAnalysis(auc: float, se: float, lower: float, upper: float, alpha: float, method: str, curve: DataFrame, events: int, non_events: int, direction: str = 'above', label: str = '', partial: Mapping[str, Any] | None = None, band: DataFrame | None = None, draws: ndarray | None = None, resample: str = '', provenance: Any = None)

The ROC curve of an indicator or model, with inference on its area: auc (the probability that a pre-event period scores higher than a calm one, ties half), its standard error se and interval (lower, upper) at 1 - alpha by DeLong or the bootstrap (method); curve (threshold, false-alarm rate, hit rate); partial, the partial AUC over a range of false-alarm rates with McClish's standardisation; band, the bootstrap's pointwise band for the hit rate at each false-alarm rate; draws the bootstrap's AUCs.

plot

plot(other: ROCAnalysis | None = None, threshold: float | None = None, other_threshold: float | None = None) -> Figure

The ROC curve (with the bootstrap's band, if any) against the diagonal of no skill; other overlays a second indicator's curve, and threshold marks a threshold's point on the curve.

ThresholdChoice dataclass

ThresholdChoice(threshold: float, criterion: str, direction: str, mu: float, loss: str, min_signals: int, trade_off: DataFrame, label: str = '', alpha: float = 0.05, provenance: Any = None, threshold_by: str = 'pooled', levels: Series | None = None)

The threshold chosen by criterion and the whole trade-off it was chosen from: trade_off has one row per candidate threshold (from the fewest signals to the most) with the counts, hit and false-alarm rates, specificity, noise-to-signal ratio, Youden J, the policymaker's loss and usefulness, and whether it was eligible (enough signals: min_signals). Ties go to the first, the threshold with the fewest signals. With threshold_by= "entity" the threshold is a common percentile of each entity's own distribution (Kaminsky, Lizondo and Reinhart 1998) and levels each entity's threshold on the indicator's scale.

chosen property

chosen: Series

The chosen threshold's row of the trade-off.

classification

classification(alpha: float | None = None) -> ClassificationTable

The classification table at the chosen threshold.

levels_table

levels_table() -> Table

Each entity's threshold on the indicator's scale (threshold_by="entity").

plot

plot() -> Figure

Hit rate, specificity and relative usefulness against the threshold, the chosen one marked.

TwoPieceNormal dataclass

TwoPieceNormal(mode: Any, sigma1: Any, sigma2: Any)

The two-piece (split) normal distribution with mode mode and standard deviations sigma1 below it and sigma2 above it; the fields may be arrays (one distribution per element). TwoPieceNormal.bank(mode, uncertainty, skew) builds it from the Bank of England's parameters.

mean property

mean: ndarray

mode + sqrt(2 / pi) (sigma2 - sigma1).

variance property

variance: ndarray

(1 - 2 / pi) (sigma2 - sigma1)^2 + sigma1 sigma2.

third_moment property

third_moment: ndarray

The third central moment, sqrt(2 / pi) (sigma2 - sigma1) [(4 / pi - 1) (sigma2 - sigma1)^2 + sigma1 sigma2].

uncertainty property

uncertainty: ndarray

The Bank's sigma: sqrt(2 / (1 / sigma1^2 + 1 / sigma2^2)).

gamma property

gamma: ndarray

The Bank's gamma: (sigma2^2 - sigma1^2) / (sigma1^2 + sigma2^2).

skew property

skew: ndarray

The mean less the mode, the Bank's measure of the balance of risks.

bank classmethod

bank(mode: Any, uncertainty: Any, skew: Any = 0.0, skew_measure: str = 'mean-mode') -> TwoPieceNormal

From the mode, the uncertainty sigma and the skew (the mean less the mode, or gamma): see two_piece_scales.

band

band(coverage: Any, bands: str = 'highest-density') -> tuple[ndarray, ndarray]

The interval holding coverage of the probability: the narrowest, around the mode ("highest-density"), or between the (1 - coverage) / 2 and (1 + coverage) / 2 quantiles ("equal-tailed").