API Reference¶
This file is generated by scripts/generate_api_docs.py from each package's __all__. Core API is what you call to use bvar. Forecasting / Models / Plotting also expose extension points (Forecasting, SamplingModel, PosteriorState, SamplingResult, PlotBVAR, PlotGIRF) — base classes BVAR inherits or that you subclass; you rarely instantiate them directly. Start from the user guide.
Core API¶
Bayesian Vector Autoregression (BVAR) Model Module¶
This module provides the main BVAR class for estimating Bayesian Vector Autoregression models with various prior specifications. The implementation supports Minnesota priors, sum-of-coefficients priors, single-unit-root priors, and automatic hyperparameter optimisation using marginal likelihood maximisation.
| CLASS | DESCRIPTION |
|---|---|
BVAR : class |
Main class for Bayesian Vector Autoregression estimation and forecasting. |
Notes
The BVAR class integrates several components: - Natural conjugate sampling for efficient posterior simulation (Chan, 2020) - Minnesota-style priors with optional hyperparameter optimisation (GLP, 2015) - Dummy observation implementation for sum-of-coefficients and single-unit-root priors - Unconditional and conditional forecasting capabilities (Waggoner & Zha, 1999; Antolín-Díaz et al., 2021) - Support for skewed constraint distributions in conditional forecasting
The model supports various data transformations and can handle: - Variables in levels or differences - COVID-19 dummy variables for structural break modelling - Recursive forecasting for out-of-sample evaluation
References
Chan, J. C. C. (2020). Large Bayesian vector autoregressions. Giannone, D., Lenza, M., & Primiceri, G. E. (2015). Prior selection for vector autoregressions. Review of Economics and Statistics, 97(2), 436-451. Antolín-Díaz, J., Petrella, I., & Rubio-Ramírez, J. F. (2021). Structural scenario analysis with SVARs. Journal of Monetary Economics, 117, 798-815.
BVAR ¶
Bayesian Vector Autoregression (BVAR) model class.
Provides methods for estimating posterior distributions of VAR parameters, generating fitted values, and producing unconditional and conditional forecasts.
The model is specified as: y_t = c + A_1 y_{t-1} + ... + A_p y_{t-p} + ε_t where ε_t ~ N(0, Σ).
Notes
df_data : pd.DataFrame
Original input data.
data : np.ndarray
Data as numpy array.
n_lags : int
Number of lags.
n : int
Number of variables.
T : int
Effective sample size (total observations minus lags).
k : int
Number of regressors per equation (1 + np + h).
nk : int
Total number of coefficients (n * k).
model : SamplingModel
Sampling model instance (e.g. NaturalConjugate or IndependentNIW).
vars_in_levels : np.ndarray
Boolean array indicating which variables are in levels.
covid_indices : list
Indices of COVID-19 dummy observations.
soc_ : bool or None
Effective sum-of-coefficients flag for the last fit (model.soc
combined with whether any variable is in levels). Computed per-fit
rather than mutating self.model.soc. Callers can reuse the same
model instance with independent BVAR fits.
sur_ : bool or None
Effective single-unit-root flag for the last fit, analogous to
soc_.
data_transformation : dict or None
Dictionary describing the original transformations of the input data.
Maps variable names/indices to input data states such as "levels",
"logs" (or "log_levels"), "diff", and "log_diff".
Set during sampling via the sample() method.
beta : np.ndarray
Posterior draws of VAR coefficients, shape (N_draws, nk).
sigma : np.ndarray
Posterior draws of covariance matrix (flattened), shape (N_draws, n²).
extras : list, optional
Model-owned auxiliary state for each retained draw in beta/
sigma, or None for models that carry no such state (the
default for all current models).
beta_point : np.ndarray
Posterior point estimate of VAR coefficients.
sigma_point : np.ndarray
Posterior point estimate of the covariance matrix. For the conjugate
model this is the posterior mean.
posterior_state_point : PosteriorState
Extensible state carrier wrapping *_point plus any model-owned
extras (None for current models).
dimensions
property
¶
Return (n_vars, n_regressors, n_total_coeffs, n_effective_obs).
optimise_hyperparameters ¶
optimise_hyperparameters(data: DataFrame, nb_restart: int = 0, initial_values: Optional[ndarray] = None, target_series: Optional[list[str]] = None, cv_options: Optional[dict] = None, add_priors: bool = True, random_state: Optional[int] = None, optimisation_backend: str = 'auto') -> None
Optimise prior hyperparameters using the specified method.
This method updates self.model.pars in place based on the
optimisation_method set during initialisation.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Time series data with variables in columns. If covid is True, the index should be a regularly-spaced pd.PeriodIndex or pd.DatetimeIndex (any frequency, not only quarterly).
TYPE:
|
nb_restart
|
Number of random restarts for the BFGS optimiser to avoid local minima. Default is 0 (single optimisation run).
TYPE:
|
initial_values
|
Initial hyperparameter values. If
TYPE:
|
target_series
|
Series names to target when scoring cross-validation error (used
only when
TYPE:
|
cv_options
|
Settings for cross-validation methods (e.g., number of folds, window size).
TYPE:
|
add_priors
|
Whether to add Gamma hyperpriors on the hyperparameters when computing the marginal likelihood. Default is True.
TYPE:
|
random_state
|
Seed or generator controlling the random perturbations applied to the initial guess and to each multi-start restart during "ml" hyperparameter optimisation, and the stochastic draws used across grid points and rolling windows during "cross_validation" optimisation (unused by "none"). If given, overrides the generator set at construction for this call; otherwise the the method uses the instance generator. The global NumPy random state remains unchanged. Default is None.
TYPE:
|
optimisation_backend
|
Backend for marginal-likelihood optimisation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
The method updates |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If a staged optimisation operation fails. |
Notes
For "ml" method, optimises c1, c3, and optionally mu (if SOC prior) and theta (if SUR prior) by maximising the marginal likelihood. BFGS uses JAX-compiled, double-precision values and automatic gradients. The first fit for each matrix shape includes compilation overhead; subsequent fits of the same shape reuse the compiled code.
sample ¶
sample(data: DataFrame, N_draws: Optional[int] = None, N_burn: Optional[int] = None, point_only: bool = False, progressbar: bool = True, data_transformation: Optional[dict] = None, random_state: Optional[int] = None) -> None
Draw samples from the posterior distribution of VAR parameters.
self.model determines the sampler:
NaturalConjugate: Direct sampling from the known Normal-Inverse-Wishart posterior (Chan, 2020). The sampler needs no burn-in.IndependentNIW: Gibbs sampler with independent Normal-Inverse-Wishart priors. The sampler discards burn-in draws.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Time series data with variables in columns.
TYPE:
|
N_draws
|
Number of posterior draws to retain after burn-in. Default is 5000.
TYPE:
|
N_burn
|
Number of initial burn-in draws to discard. Only relevant for MCMC
samplers (e.g.
TYPE:
|
point_only
|
If True, only compute the posterior point estimate without drawing samples. Useful for fast point estimates. Default is False.
TYPE:
|
progressbar
|
Whether to display a progress bar during sampling. Default is True.
TYPE:
|
data_transformation
|
Dictionary describing the original transformations of the input data.
Maps variable names or indices to input data states. Supported
values are "levels", "logs" (or "log_levels"), "diff", and
"log_diff". These labels describe transformations applied before
sampling; they do not transform the data themselves. Forecast
output transformations such as "qoq" and "yoy" belong in the
TYPE:
|
random_state
|
Seed or generator controlling the posterior draws (and any
subsequent forecast simulation). If given, overrides the generator
set at construction and reused in later
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
The method stores results in these attributes:
- self.beta : Posterior draws of coefficients, shape (N_draws, n*k)
- self.sigma : Posterior draws of Σ (flattened), shape (N_draws, n²)
- self.beta_point : Posterior point estimate of coefficients
- self.sigma_point : Posterior point estimate of Σ
- self.posterior_state_point : |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If posterior sampling fails. |
ValueError
|
If a draw or burn-in count is invalid. |
compute_fitted_values ¶
Calculate fitted values across all posterior draws.
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If model has not been fitted yet. |
grid_search ¶
grid_search(data: ndarray, cv_method: str = 'predictive_ml', cv_options: Optional[dict] = None, target_indices: Optional[List[int]] = None, random_state: Optional[int] = None, progressbar: bool = False) -> None
Optmise hyperparameters with a grid search on cross-validated errors.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input data array.
TYPE:
|
cv_method
|
Cross-validation method. Only supports "predictive_ml".
TYPE:
|
cv_options
|
Options for cross-validation. Required keys:
TYPE:
|
target_indices
|
Indices of target variables for evaluation. If
TYPE:
|
random_state
|
Seed or generator controlling the stochastic draws used across
the grid search. Resolved once into a single private
TYPE:
|
progressbar
|
Whether to display a progress bar. Default is True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
The method stores optimised hyperparameters in |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If a staged grid-search operation fails. |
ValueError
|
If |
marginal_likelihood_H ¶
marginal_likelihood_H(data: ndarray, H: int, target_indices: Optional[List[int]] = None, rolling_oos_starting_id: Optional[int] = None, random_state: Optional[int] = None) -> float
Compute the marginal likelihood at forecast horizon H using rolling window.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input data array.
TYPE:
|
H
|
Forecast horizon.
TYPE:
|
target_indices
|
Indices of target variables for evaluation. If
TYPE:
|
rolling_oos_starting_id
|
Starting index for the rolling window. If None, defaults to
TYPE:
|
random_state
|
Seed or generator controlling the stochastic draws used across
rolling windows. Resolved once into a single private
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ml
|
Sum of log marginal likelihoods across all rolling windows.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the horizon, rolling-window index, or target indices are invalid. |
plot_girf ¶
plot_girf(shock_var: Optional[str | int | list] = None, response_var: Optional[str | int | list] = None, quantiles: tuple[float, float, float] = (0.16, 0.5, 0.84), figsize_per_plot: tuple[float, float] = (4.0, 3.0), max_cols: int = 4, title: Optional[str] = None, zero_line: bool = True) -> Figure
Plot posterior distributions of Generalised Impulse Response Functions.
Displays the posterior median and a credible band for each (shock variable, response variable) pair.
| PARAMETER | DESCRIPTION |
|---|---|
shock_var
|
Variable(s) to shock. Can be a column name, a 0-based index, or a list of names/indices. If None, all variables are shown.
TYPE:
|
response_var
|
Variable(s) whose responses to plot. Same format as
TYPE:
|
quantiles
|
(lower, median, upper) quantile levels for the credible band. Default is (0.16, 0.50, 0.84).
TYPE:
|
figsize_per_plot
|
(width, height) of each individual subplot. Default is (4, 3).
TYPE:
|
max_cols
|
Maximum number of subplot columns per row. Default is 4.
TYPE:
|
title
|
Overall figure title. If
TYPE:
|
zero_line
|
If True, draw a horizontal zero line on each subplot. Default is True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig
|
The figure object.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If |
plot_fitted_values ¶
plot_fitted_values(confidence_level: float = 95, max_cols: int = 3, figsize_per_plot: tuple = (5, 3), var_names: Optional[str | list[str]] = None) -> Figure
Plot fitted values with credible intervals against actual data.
| PARAMETER | DESCRIPTION |
|---|---|
confidence_level
|
Confidence level for credible intervals (in percent).
TYPE:
|
max_cols
|
Maximum number of subplot columns per row.
TYPE:
|
figsize_per_plot
|
Size of each subplot (width, height).
TYPE:
|
var_names
|
Column name(s) to plot. If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure containing the fitted-value subplots. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
plot_forecast ¶
plot_forecast(alpha: float = 0.05, max_cols: int = 3, figsize_per_plot: tuple = (5, 3), var_names: Optional[str | list[str]] = None, from_date: Optional[Period | str] = None) -> Figure
Plot forecast means and credible intervals for each series.
| PARAMETER | DESCRIPTION |
|---|---|
alpha
|
Significance level for credible intervals (e.g., 0.05 for 95% interval). Default is 0.05.
TYPE:
|
max_cols
|
Maximum number of subplot columns per row.
TYPE:
|
figsize_per_plot
|
Size of each subplot (width, height).
TYPE:
|
var_names
|
Column name(s) to plot. If
TYPE:
|
from_date
|
Starting date for the forecast plot. If None, uses default date range.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure containing the forecast subplots. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If forecast results are not available. |
ValueError
|
If |
compute_girf ¶
compute_girf(H: int, N_draws: int = 5000, point_only: bool = False, data_transformation: Optional[dict] = None, response_type: Optional[dict] = None, shock_size: Optional[dict] = None, progressbar: bool = False, base_value: Optional[float | list[float] | ndarray] = None) -> GIRF
Compute Generalised Impulse Response Functions from posterior draws.
For each posterior draw of (β, Σ), the method computes the reduced-form MA matrices Ψ_0, …, Ψ_H and evaluates the GIRF formula of Pesaran & Shin (1998).
IRF responses are kept in their raw model representation and also converted to a common "level_changes" representation for response transformations.
| PARAMETER | DESCRIPTION |
|---|---|
H
|
Maximum horizon (number of periods ahead).
TYPE:
|
N_draws
|
Number of posterior draws to use. Default is 5000.
TYPE:
|
point_only
|
If True, compute only for the posterior point estimates. Default is False.
TYPE:
|
data_transformation
|
Dictionary mapping variable names or integer indices to data transformation types: "logs", "log_diff", "levels", or "diff". Example: {"GDP": "log_diff", "Inflation": "levels"}. Default is None.
TYPE:
|
response_type
|
Dictionary mapping variable names to response types: "raw" (untransformed GIRF), "raw_cumulated", "level_change", "pct_change", "change_yoy", or "pct_change_yoy". YoY types are only available for data with sufficient frequency (e.g., monthly, quarterly). If None, all default to "raw". Example: {"GDP": "pct_change_yoy", "Inflation": "level_change"}. Default is None.
TYPE:
|
shock_size
|
Dictionary mapping variable names to shock magnitudes in the variable's natural units. If None or a variable is missing, defaults to 1 std-dev. Example: {"GDP": 0.02, "Inflation": 0.5} for 2% increase in log GDP and 0.5 unit increase in inflation (interpreted in data units). Default is None.
TYPE:
|
progressbar
|
Whether to display a tqdm progress bar. Default is False.
TYPE:
|
base_value
|
Absolute last observed level for variables recorded as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GIRF
|
The BVAR object with GIRF results stored in its IRF attributes.
|
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If the fitted model does not support GIRFs. |
RuntimeError
|
If the model has not been fitted. |
ValueError
|
If a supplied horizon, draw count, shock, or response is invalid. |
Notes
Two-stage pipeline:
-
Conditional conversion to level_changes: Raw IRFs are converted to a common "level_changes" representation for non-raw response types.
-
"logs" or "log": level_change = baseline * dlog(y)
- "log_diff": level_change = baseline * Δlog(y)
- "levels": level_change = y (already level changes)
-
"diff": level_change = Δy (already level changes)
-
Apply transformations: From the appropriate representation, compute requested response_type for each variable independently.
-
If response_type[var]=="raw": untouched GIRF
- Otherwise apply response_type (level_change or pct_change, etc.)
Shock scaling:
The default GIRF computes responses to a one-standard-deviation shock. Use shock_size to specify shocks in natural units. For example, shock_size={"GDP": 0.02} for a 2 percentage point shock to log GDP. The method converts natural units to standard-deviation equivalents with the error covariance matrix.
recursive_forecast ¶
recursive_forecast(H: int, N_draws: int = 5000, point_only: bool = False, progressbar: bool = False, random_state: Optional[int] = None) -> Forecasting
Generate unconditional forecasts from the BVAR posterior draws using recursive form.
This function is mainly useful when using the conditional mean only (otherwise use self.forecast). Also used to double-check the results of self.forecast which is faster but more complex.
| PARAMETER | DESCRIPTION |
|---|---|
H
|
Forecast horizon (number of steps ahead to forecast).
TYPE:
|
N_draws
|
Number of posterior draws to use for forecasting. Default is 5000.
TYPE:
|
point_only
|
If True, compute a single plug-in forecast using the stored posterior point estimates. Default is False.
TYPE:
|
progressbar
|
Whether to display a progress bar. Default is False.
TYPE:
|
random_state
|
Seed or generator controlling the residual draws. If given,
overrides the generator set at construction and is reused by
later
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
self
|
The BVAR object with forecasts stored in self.forecast_unconditional (shape: N_draws x (T+H) x n).
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the model has no posterior draws ( |
forecast ¶
forecast(H: int, constraint_mean: Optional[ndarray] = None, constraint_variance: Optional[ndarray] = None, constraint_shape: Optional[ndarray] = None, method: str = 'andersson_et_al', N_draws: int = 5000, N_burn: Optional[int] = None, point_only: bool = False, format: bool = False, quantiles: Optional[list] = None, base_value: Optional[ndarray] = None, constraint_sampler: Optional[Callable] = None, progressbar: bool = False, transformations: Optional[dict] = None, random_state: Optional[int] = None) -> Forecasting
Generate conditional forecasts from the BVAR posterior draws.
Implementation following Waggoner & Zha (1999) and Antolín-Díaz et al. (2021). Supports mean, variance, and shape/skewness constraints on forecasts.
| PARAMETER | DESCRIPTION |
|---|---|
H
|
Forecast horizon (number of steps ahead).
TYPE:
|
constraint_mean
|
Values to impose for the mean of the conditioned variables.
Shape
TYPE:
|
constraint_variance
|
Values to impose for the variance of the conditioned variables.
Shape
TYPE:
|
constraint_shape
|
Values to impose for the shape/skewness of the conditioned variables.
Shape
TYPE:
|
method
|
Method for handling constraints. Default is "andersson_et_al".
TYPE:
|
N_draws
|
Number of MCMC draws used to simulate the uncertainty
of conditional forecasts. Default is 5000. Must be positive;
capped at
TYPE:
|
N_burn
|
Number of burn-in draws to discard. Default is
TYPE:
|
point_only
|
If True, returns only the conditional mean using the median draw from the Bayesian sampling (much faster). Default is False.
TYPE:
|
format
|
Whether to format the output as a DataFrame with dates. Default is False.
TYPE:
|
quantiles
|
List of quantiles to compute if format is True. Default is [0.16, 0.5, 0.84].
TYPE:
|
base_value
|
Absolute level at the end of the observed sample, required when a
forecast tail contains rows reconstructed from
TYPE:
|
constraint_sampler
|
Custom constraint sampler function. Default is None.
TYPE:
|
progressbar
|
Whether to display a progress bar during forecasting. Default is False.
TYPE:
|
transformations
|
Dictionary mapping variable names or indices to transformation types
to APPLY to the forecasts. Supported:
TYPE:
|
random_state
|
Seed or generator controlling the stochastic forecast draws. If
given, overrides the generator set at construction and is reused
in later
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Forecasting
|
The BVAR object with forecast results stored in its forecast, summary, horizon, and last-observation attributes. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the model has no posterior draws ( |
ValueError
|
If forecast constraints, draw counts, or transformations are invalid. |
References
Waggoner, D. F., & Zha, T. (1999). Conditional forecasts in dynamic multivariate models. Antolín-Díaz, J., Petrella, I., & Rubio-Ramírez, J. F. (2021). Structural scenario analysis with SVARs.
Generalised Impulse Response Function methods for the BVAR class.
This mixin class provides methods for computing and plotting GIRFs from
posterior draws of VAR coefficients and error covariance matrices. All
methods operate on the posterior distributions already estimated by
BVAR.sample().
GIRFs are order-invariant: unlike Cholesky-based orthogonalised IRFs they do not depend on the ordering of variables in the system.
See module docstring for the mathematical details.
compute_girf ¶
compute_girf(H: int, N_draws: int = 5000, point_only: bool = False, data_transformation: Optional[dict] = None, response_type: Optional[dict] = None, shock_size: Optional[dict] = None, progressbar: bool = False, base_value: Optional[float | list[float] | ndarray] = None) -> GIRF
Compute Generalised Impulse Response Functions from posterior draws.
For each posterior draw of (β, Σ), the method computes the reduced-form MA matrices Ψ_0, …, Ψ_H and evaluates the GIRF formula of Pesaran & Shin (1998).
IRF responses are kept in their raw model representation and also converted to a common "level_changes" representation for response transformations.
| PARAMETER | DESCRIPTION |
|---|---|
H
|
Maximum horizon (number of periods ahead).
TYPE:
|
N_draws
|
Number of posterior draws to use. Default is 5000.
TYPE:
|
point_only
|
If True, compute only for the posterior point estimates. Default is False.
TYPE:
|
data_transformation
|
Dictionary mapping variable names or integer indices to data transformation types: "logs", "log_diff", "levels", or "diff". Example: {"GDP": "log_diff", "Inflation": "levels"}. Default is None.
TYPE:
|
response_type
|
Dictionary mapping variable names to response types: "raw" (untransformed GIRF), "raw_cumulated", "level_change", "pct_change", "change_yoy", or "pct_change_yoy". YoY types are only available for data with sufficient frequency (e.g., monthly, quarterly). If None, all default to "raw". Example: {"GDP": "pct_change_yoy", "Inflation": "level_change"}. Default is None.
TYPE:
|
shock_size
|
Dictionary mapping variable names to shock magnitudes in the variable's natural units. If None or a variable is missing, defaults to 1 std-dev. Example: {"GDP": 0.02, "Inflation": 0.5} for 2% increase in log GDP and 0.5 unit increase in inflation (interpreted in data units). Default is None.
TYPE:
|
progressbar
|
Whether to display a tqdm progress bar. Default is False.
TYPE:
|
base_value
|
Absolute last observed level for variables recorded as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GIRF
|
The BVAR object with GIRF results stored in its IRF attributes.
|
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If the fitted model does not support GIRFs. |
RuntimeError
|
If the model has not been fitted. |
ValueError
|
If a supplied horizon, draw count, shock, or response is invalid. |
Notes
Two-stage pipeline:
-
Conditional conversion to level_changes: Raw IRFs are converted to a common "level_changes" representation for non-raw response types.
-
"logs" or "log": level_change = baseline * dlog(y)
- "log_diff": level_change = baseline * Δlog(y)
- "levels": level_change = y (already level changes)
-
"diff": level_change = Δy (already level changes)
-
Apply transformations: From the appropriate representation, compute requested response_type for each variable independently.
-
If response_type[var]=="raw": untouched GIRF
- Otherwise apply response_type (level_change or pct_change, etc.)
Shock scaling:
The default GIRF computes responses to a one-standard-deviation shock. Use shock_size to specify shocks in natural units. For example, shock_size={"GDP": 0.02} for a 2 percentage point shock to log GDP. The method converts natural units to standard-deviation equivalents with the error covariance matrix.
Compute cumulative changes (cumulated growth) for forecast paths.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Forecast data (log-levels or log-differences) with shape
TYPE:
|
levels
|
Indicator array with shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
sum_diff
|
Cumulative changes from the second observation onward, with shape
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the variables are a mix of levels and differences. |
Notes
Returns the cumulative sum of first differences of a levels or log-difference series (the first row is dropped as it is not a forecast).
Plot posterior distributions (histograms) for MCMC draws of parameters.
| PARAMETER | DESCRIPTION |
|---|---|
draws
|
Array of MCMC draws for each parameter, with shape
TYPE:
|
true_pars
|
Array of true parameter values for reference (default: None).
TYPE:
|
max_cols
|
Maximum number of columns in the subplot grid.
TYPE:
|
figsize_per_plot
|
Size of each subplot (width, height).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure containing the posterior-distribution subplots. |
Simulate synthetic VAR(p) data, optionally with COVID dummies and integration.
| PARAMETER | DESCRIPTION |
|---|---|
T
|
Number of time periods.
TYPE:
|
n
|
Number of variables.
TYPE:
|
n_lags
|
Number of lags.
TYPE:
|
covid
|
Whether to include COVID dummies (default: False).
TYPE:
|
levels
|
If True, returns integrated (non-stationary) data (default: False).
TYPE:
|
ar_mat
|
First AR coefficient matrix with shape
TYPE:
|
constant
|
Constant vector with shape
TYPE:
|
Sigma
|
Covariance matrix for error terms with shape
TYPE:
|
seed
|
Seed or
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
y
|
Simulated time series data with shape
TYPE:
|
b
|
True parameter vector with shape
TYPE:
|
sigma
|
Covariance matrix used for simulation with shape
TYPE:
|
eps
|
Simulated error terms with shape
TYPE:
|
Forecasting¶
Forecasting methods for the BVAR class.
This class provides methods for generating both unconditional and conditional forecasts from Bayesian Vector Autoregression (BVAR) models. It implements the Waggoner & Zha (1999) and Antolín-Díaz et al. (2021) algorithms for conditional forecasting. It supports mean, variance, and skewness constraints.
recursive_forecast ¶
recursive_forecast(H: int, N_draws: int = 5000, point_only: bool = False, progressbar: bool = False, random_state: Optional[int] = None) -> Forecasting
Generate unconditional forecasts from the BVAR posterior draws using recursive form.
This function is mainly useful when using the conditional mean only (otherwise use self.forecast). Also used to double-check the results of self.forecast which is faster but more complex.
| PARAMETER | DESCRIPTION |
|---|---|
H
|
Forecast horizon (number of steps ahead to forecast).
TYPE:
|
N_draws
|
Number of posterior draws to use for forecasting. Default is 5000.
TYPE:
|
point_only
|
If True, compute a single plug-in forecast using the stored posterior point estimates. Default is False.
TYPE:
|
progressbar
|
Whether to display a progress bar. Default is False.
TYPE:
|
random_state
|
Seed or generator controlling the residual draws. If given,
overrides the generator set at construction and is reused by
later
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
self
|
The BVAR object with forecasts stored in self.forecast_unconditional (shape: N_draws x (T+H) x n).
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the model has no posterior draws ( |
forecast ¶
forecast(H: int, constraint_mean: Optional[ndarray] = None, constraint_variance: Optional[ndarray] = None, constraint_shape: Optional[ndarray] = None, method: str = 'andersson_et_al', N_draws: int = 5000, N_burn: Optional[int] = None, point_only: bool = False, format: bool = False, quantiles: Optional[list] = None, base_value: Optional[ndarray] = None, constraint_sampler: Optional[Callable] = None, progressbar: bool = False, transformations: Optional[dict] = None, random_state: Optional[int] = None) -> Forecasting
Generate conditional forecasts from the BVAR posterior draws.
Implementation following Waggoner & Zha (1999) and Antolín-Díaz et al. (2021). Supports mean, variance, and shape/skewness constraints on forecasts.
| PARAMETER | DESCRIPTION |
|---|---|
H
|
Forecast horizon (number of steps ahead).
TYPE:
|
constraint_mean
|
Values to impose for the mean of the conditioned variables.
Shape
TYPE:
|
constraint_variance
|
Values to impose for the variance of the conditioned variables.
Shape
TYPE:
|
constraint_shape
|
Values to impose for the shape/skewness of the conditioned variables.
Shape
TYPE:
|
method
|
Method for handling constraints. Default is "andersson_et_al".
TYPE:
|
N_draws
|
Number of MCMC draws used to simulate the uncertainty
of conditional forecasts. Default is 5000. Must be positive;
capped at
TYPE:
|
N_burn
|
Number of burn-in draws to discard. Default is
TYPE:
|
point_only
|
If True, returns only the conditional mean using the median draw from the Bayesian sampling (much faster). Default is False.
TYPE:
|
format
|
Whether to format the output as a DataFrame with dates. Default is False.
TYPE:
|
quantiles
|
List of quantiles to compute if format is True. Default is [0.16, 0.5, 0.84].
TYPE:
|
base_value
|
Absolute level at the end of the observed sample, required when a
forecast tail contains rows reconstructed from
TYPE:
|
constraint_sampler
|
Custom constraint sampler function. Default is None.
TYPE:
|
progressbar
|
Whether to display a progress bar during forecasting. Default is False.
TYPE:
|
transformations
|
Dictionary mapping variable names or indices to transformation types
to APPLY to the forecasts. Supported:
TYPE:
|
random_state
|
Seed or generator controlling the stochastic forecast draws. If
given, overrides the generator set at construction and is reused
in later
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Forecasting
|
The BVAR object with forecast results stored in its forecast, summary, horizon, and last-observation attributes. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the model has no posterior draws ( |
ValueError
|
If forecast constraints, draw counts, or transformations are invalid. |
References
Waggoner, D. F., & Zha, T. (1999). Conditional forecasts in dynamic multivariate models. Antolín-Díaz, J., Petrella, I., & Rubio-Ramírez, J. F. (2021). Structural scenario analysis with SVARs.
Compare two conditional forecasts and compute revisions.
Takes two formatted forecast DataFrames (output from forecast(..., format=True))
and computes their differences.
| PARAMETER | DESCRIPTION |
|---|---|
df_forecast_a
|
First forecast DataFrame in long format with columns: date, quantile, variable, value.
TYPE:
|
df_forecast_b
|
Second forecast DataFrame in long format (same structure).
TYPE:
|
H
|
Forecast horizon used for filtering.
TYPE:
|
labels
|
Labels for the two forecasts. Default is ["forecast_a", "forecast_b"].
TYPE:
|
n_outturns
|
Number of preceding outturns to retain.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Combined DataFrame in long format containing: - First forecast values (labelled with labels[0]) - Second forecast values (labelled with labels[1]) - Differences (labelled "difference") With columns: date, quantile, variable, value, type. |
Models¶
BVAR with independent Normal-Inverse-Wishart priors.
The prior is β ~ N(β₀, V_β) independently of Σ ~ IW(S₀, ν₀),
where V_β is a full (nk, nk) precision matrix encoding
cross-variable scaling σ_i / σ_j.
| PARAMETER | DESCRIPTION |
|---|---|
c2
|
Cross-variable shrinkage (Litterman 1986 uses 0.5).
TYPE:
|
minnesota
|
Whether to use the Minnesota prior.
TYPE:
|
soc
|
Whether to use the sum-of-coefficients prior.
TYPE:
|
sur
|
Whether to use the single-unit-root prior.
TYPE:
|
covid
|
Whether to include COVID dummy observations.
TYPE:
|
covid_dates
|
Start and end dates for the COVID period.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
requires_burnin |
TYPE:
|
supports_ml |
TYPE:
|
supports_point_only |
TYPE:
|
set_priors ¶
Set prior hyperparameters including cross-variable shrinkage c2.
Also computes Gamma hyperprior parameters for c2.
fill_in_from_vector ¶
Vector layout: [c1, c3, c2, mu?, theta?].
sample ¶
sample(data: ndarray, n_lags: int, covid_indices: ndarray, vars_in_levels: ndarray, N_draws: int, point_only: bool = False, progressbar: bool = True, soc: Optional[bool] = None, sur: Optional[bool] = None, rng: Optional[Generator] = None) -> SamplingResult
Run the full independent-NIW Gibbs estimation pipeline.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input data array.
TYPE:
|
n_lags
|
Number of VAR lags.
TYPE:
|
covid_indices
|
Indices for COVID dummy observations.
TYPE:
|
vars_in_levels
|
Indicators for variables in levels.
TYPE:
|
N_draws
|
Number of posterior draws.
TYPE:
|
point_only
|
Whether to request a point estimate.
TYPE:
|
progressbar
|
Whether to display a progress bar.
TYPE:
|
soc
|
Effective sum-of-coefficients flag.
TYPE:
|
sur
|
Effective single-unit-root flag.
TYPE:
|
rng
|
Random number generator.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SamplingResult
|
Posterior draws and point estimates. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If point_only is |
sample_posterior_state ¶
sample_posterior_state(Y: ndarray, Z: ndarray, current_state: PosteriorState, rng: Optional[Generator] = None) -> PosteriorState
Return the next Gibbs-sampled posterior state.
Performs one full Gibbs sweep (β|Σ then Σ|β) using the stored prior
from the last call to :meth:sample. current_state.sigma seeds
the sweep's covariance. The Gibbs kernel accepts
current_state.beta for interface compatibility but ignores it;
it samples β conditional on Σ within this sweep rather than carrying
β forward.
BVAR with Natural-Conjugate (Normal-Inverse-Wishart) priors.
The prior is vec(A) | Σ ~ N(β₀, Σ ⊗ V_A⁻¹) and
Σ ~ IW(S₀, ν₀). Posterior sampling follows Chan (2020).
| ATTRIBUTE | DESCRIPTION |
|---|---|
requires_burnin |
TYPE:
|
supports_ml |
TYPE:
|
sample ¶
sample(data: ndarray, n_lags: int, covid_indices: ndarray, vars_in_levels: ndarray, N_draws: int, point_only: bool = False, progressbar: bool = True, soc: Optional[bool] = None, sur: Optional[bool] = None, rng: Optional[Generator] = None) -> SamplingResult
Run the full conjugate estimation pipeline.
sample_posterior_state ¶
sample_posterior_state(Y: ndarray, Z: ndarray, current_state: PosteriorState, rng: Optional[Generator] = None) -> PosteriorState
Return a single random posterior draw as a PosteriorState.
Draws one sample from the known Normal-Inverse-Wishart posterior
using the stored prior (self.beta_0, self.V_A_inv,
self.pars.S_0, self.pars.nu_0) from the last call to
:meth:sample. The method accepts current_state for interface
compatibility but ignores it because the posterior comes directly
from the closed-form distribution rather than an MCMC update.
Extensible carrier for a single posterior draw's state.
beta and sigma are the required core VAR parameters shared by
every model. extras is an optional, model-owned payload for any
additional state a model needs to carry between draws (e.g. a sampled
degrees of freedom parameter for a Student-t model). extras is left
untyped so each model may choose its representation, such as an array,
scalar, or mapping.
Forecasting._conditional_forecast threads this dataclass through its
Gibbs chain (seeded from a copy of BVAR.posterior_state_point) via
:meth:SamplingModel.sample_posterior_state, carrying extras
forward between iterations rather than discarding it. The seed copy is
fully isolated from the fitted point-estimate state -- including nested mutable
objects inside extras -- so the chain can never mutate
BVAR.posterior_state_point (see :meth:copy).
| ATTRIBUTE | DESCRIPTION |
|---|---|
beta |
Flattened VAR coefficients.
TYPE:
|
sigma |
Flattened covariance matrix.
TYPE:
|
extras |
Arbitrary model-owned auxiliary state, or
TYPE:
|
copy ¶
copy() -> PosteriorState
Return an independent copy for use as the seed of a draw chain.
The method copies beta/sigma with np.ndarray.copy so a
chain iterating over the returned state cannot mutate arrays owned by
the caller (e.g. BVAR.beta_point/sigma_point). It deep-copies
extras via copy.deepcopy to isolate nested mutable
containers (e.g. a dict holding a list) as well as the
top-level object. A model that mutates its own extras payload
inside sample_posterior_state therefore leaves the fitted
point-estimate state unchanged.
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
| RETURNS | DESCRIPTION |
|---|---|
PosteriorState
|
An independent copy of this state. |
Abstract base class for BVAR estimation models.
Each subclass owns the entire estimation pipeline and the prior hyperparameters that drive it. Common prior flags (minnesota, soc, sur, covid) and the shared hyperparameter infrastructure live here; subclasses add model-specific parameters.
| PARAMETER | DESCRIPTION |
|---|---|
minnesota
|
Apply Minnesota shrinkage to the coefficient prior. Default
TYPE:
|
soc
|
Add sum-of-coefficients dummy observations. Default
TYPE:
|
sur
|
Add a single-unit-root dummy observation. Default
TYPE:
|
covid
|
Include COVID-19 outlier dummies. Default
TYPE:
|
covid_dates
|
Two-element list
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
requires_burnin |
TYPE:
|
supports_ml |
TYPE:
|
supports_point_only |
TYPE:
|
supports_gaussian_predictive |
TYPE:
|
supports_girf |
TYPE:
|
set_priors ¶
set_priors(c1: float = 0.2, c3: float = 2.0, lambda_constant: float = 10.0, mu: float = 1.0, theta: float = 1.0, lambda_covid: float = 10000.0, c1_mode: float = 0.2, c1_sd: float = 0.4, c3_mode: float = 2.0, c3_sd: float = 0.5, mu_mode: float = 1.0, mu_sd: float = 1.0, theta_mode: float = 1.0, theta_sd: float = 1.0) -> None
Set prior hyperparameters.
Subclasses may override to accept model-specific parameters
(e.g. c2 for :class:IndependentNIW).
fill_in_from_vector ¶
Update hyperparameters from an optimisation vector.
The vector layout is [c1, c3, ...] followed by mu (if SOC)
and theta (if SUR). Subclasses may override to insert
model-specific hyperparameters.
hyperparameter_grid ¶
Return default grid arrays for cross-validation.
The order matches :meth:fill_in_from_vector.
sample
abstractmethod
¶
sample(data: ndarray, n_lags: int, covid_indices: ndarray, vars_in_levels: ndarray, N_draws: int, point_only: bool = False, progressbar: bool = True, soc: Optional[bool] = None, sur: Optional[bool] = None, rng: Optional[Generator] = None) -> SamplingResult
Run the full estimation pipeline and return posterior draws.
During estimation, store the prior mean
(self.beta_0) and prior precision (self.V_A_inv)
so that :meth:sample_posterior_state can reuse them.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Raw data array with shape
TYPE:
|
n_lags
|
Number of VAR lags.
TYPE:
|
covid_indices
|
Observation indices for COVID dummy variables.
TYPE:
|
vars_in_levels
|
Boolean array with shape
TYPE:
|
N_draws
|
Total number of posterior draws to generate, including draws that the caller will discard as burn-in.
TYPE:
|
point_only
|
If
TYPE:
|
progressbar
|
Whether to display a progress bar.
TYPE:
|
soc
|
Effective sum-of-coefficients flag for this fit. The flag records
whether the code stacks SOC dummy observations. It defaults to
TYPE:
|
sur
|
Effective single-unit-root flag for this fit, analogous to
TYPE:
|
rng
|
Generator for the posterior draws. Defaults to a fresh
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SamplingResult
|
Dataclass containing posterior draws. |
sample_posterior_state
abstractmethod
¶
sample_posterior_state(Y: ndarray, Z: ndarray, current_state: PosteriorState, rng: Optional[Generator] = None) -> PosteriorState
Return the next posterior state given the current one.
This is the sole posterior-update extension point: called each
iteration by Forecasting._conditional_forecast, which threads a
:class:PosteriorState through its Gibbs chain (seeded from a copy
of BVAR.posterior_state_point) to re-sample parameters after
augmenting the data with constrained forecasts, so model-owned
extras persist across iterations. The method uses
self.beta_0, self.V_A_inv, and self.pars (S_0, nu_0)
that :meth:sample stored.
| PARAMETER | DESCRIPTION |
|---|---|
Y
|
Dependent-variable matrix (with dummies already stacked if applicable).
TYPE:
|
Z
|
Regressor matrix (with dummies already stacked if applicable).
TYPE:
|
current_state
|
The previous draw's state. Direct samplers (e.g.
:class:
TYPE:
|
rng
|
Generator for the draw. Defaults to a fresh
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PosteriorState
|
The next draw's state. |
sample_innovations ¶
sample_innovations(state: PosteriorState, H: int, rng: Optional[Generator] = None, point_only: bool = False) -> ndarray
Draw reduced-form forecast innovations for a complete posterior state.
Dispatched once per retained draw by
Forecasting.recursive_forecast and
Forecasting._unconditional_forecast, passing the draw's complete
:class:PosteriorState (beta/sigma/extras) so models
that carry auxiliary predictive state in extras (e.g. a sampled
degrees of freedom parameter for a Student-t model) can shape the
innovation distribution accordingly. The default implementation
below only uses state.sigma and draws Gaussian reduced-form
innovations ~ N(0, Sigma) -- the existing behaviour for every
current model, which ignores extras. Models that need a
different predictive distribution should override this method.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Complete posterior draw state for this draw (or
TYPE:
|
H
|
Forecast horizon (number of steps ahead).
TYPE:
|
rng
|
Generator for the draw. Defaults to a fresh
TYPE:
|
point_only
|
If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Reduced-form innovations, one row per forecast step. |
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If |
sample_conditional_forecast ¶
sample_conditional_forecast(state: PosteriorState, C: ndarray, f: ndarray, Sigma_f: ndarray, shape_f: ndarray, last_p_obs: ndarray, p: int, n: int, h: int, H: int, point_only: bool, constraint_sampler: Optional[Callable] = None, method: str = 'andersson_et_al', rng: Optional[Generator] = None) -> ndarray
Draw a constrained forecast for a complete posterior state.
Dispatched once per Gibbs iteration by
Forecasting._conditional_forecast, passing the iteration's
complete :class:PosteriorState (beta/sigma/extras) so
models that carry auxiliary predictive state in extras can
shape the constrained-forecast distribution accordingly. The
default implementation below only uses state.beta/
state.sigma and routes to the existing
:func:~bvar.forecast.conditional.draw_constrained_forecasts
algorithm -- the existing behaviour for every current model, which
ignores extras. Models that need a different predictive
distribution should override this method.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Complete posterior draw state for this Gibbs iteration.
TYPE:
|
C
|
Constraint-selection matrix, as returned by
:func:
TYPE:
|
f
|
Constraint locations with shape
TYPE:
|
Sigma_f
|
Constraint scale matrix with shape
TYPE:
|
shape_f
|
Constraint shape parameters with shape
TYPE:
|
last_p_obs
|
Last p observations before the forecast period, with shape
TYPE:
|
p
|
Number of lags.
TYPE:
|
n
|
Number of variables.
TYPE:
|
h
|
Number of COVID dummies.
TYPE:
|
H
|
Forecast horizon.
TYPE:
|
point_only
|
If
TYPE:
|
constraint_sampler
|
Custom function to sample from the constraint distribution.
TYPE:
|
method
|
Algorithm:
TYPE:
|
rng
|
Generator for the draw. Defaults to a fresh
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Forecast values (flattened), with shape |
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If |
predictive_logpdf ¶
predictive_logpdf(state: PosteriorState, observation: ndarray, mean: ndarray, covariance: ndarray) -> float
Evaluate the log predictive density of an out-of-sample observation.
Dispatched by GridSearch.marginal_likelihood_H for each
rolling-window out-of-sample point, passing the fitted model's
posterior_state_point so models that carry auxiliary predictive
state in extras can shape the predictive distribution
accordingly. The default implementation below only uses mean and
covariance and evaluates the Gaussian
scipy.stats.multivariate_normal.logpdf -- the existing
behaviour for every current model, which ignores state.extras.
Models that need a different predictive distribution should
override this method.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Complete posterior state (typically
TYPE:
|
observation
|
The realised out-of-sample observation with shape
TYPE:
|
mean
|
Predictive mean at the forecast horizon with shape
TYPE:
|
covariance
|
Predictive covariance at the forecast horizon with shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Log predictive density of observation. |
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If |
Container for the output of a model's sample() method.
| ATTRIBUTE | DESCRIPTION |
|---|---|
beta_draws |
Posterior draws of VAR coefficients (vectorised), with shape
TYPE:
|
sigma_draws |
Posterior draws of the covariance matrix (flattened), with shape
TYPE:
|
beta_point |
Posterior point estimate of VAR coefficients, with shape
TYPE:
|
sigma_point |
Posterior point estimate of the covariance matrix, with shape
TYPE:
|
extras_point |
Model-owned auxiliary state accompanying the point estimate, or
TYPE:
|
extras_draws |
Model-owned auxiliary state for each retained draw, one entry per
row of
TYPE:
|
state_point
property
¶
state_point: PosteriorState
PosteriorState view of the posterior point estimates.
Built on demand rather than stored, so models that do not use
extras_point incur no extra allocation.
__post_init__ ¶
Validate draw counts are consistent across beta/sigma/extras.
Catching a misalignment here -- rather than later, when forecasting
indexes a row/entry by draw number -- turns a confusing
IndexError/broadcasting error deep in the forecast loop into an
immediate, clear ValueError.
Plotting¶
Plotting methods for BVAR class
plot_fitted_values ¶
plot_fitted_values(confidence_level: float = 95, max_cols: int = 3, figsize_per_plot: tuple = (5, 3), var_names: Optional[str | list[str]] = None) -> Figure
Plot fitted values with credible intervals against actual data.
| PARAMETER | DESCRIPTION |
|---|---|
confidence_level
|
Confidence level for credible intervals (in percent).
TYPE:
|
max_cols
|
Maximum number of subplot columns per row.
TYPE:
|
figsize_per_plot
|
Size of each subplot (width, height).
TYPE:
|
var_names
|
Column name(s) to plot. If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure containing the fitted-value subplots. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
plot_forecast ¶
plot_forecast(alpha: float = 0.05, max_cols: int = 3, figsize_per_plot: tuple = (5, 3), var_names: Optional[str | list[str]] = None, from_date: Optional[Period | str] = None) -> Figure
Plot forecast means and credible intervals for each series.
| PARAMETER | DESCRIPTION |
|---|---|
alpha
|
Significance level for credible intervals (e.g., 0.05 for 95% interval). Default is 0.05.
TYPE:
|
max_cols
|
Maximum number of subplot columns per row.
TYPE:
|
figsize_per_plot
|
Size of each subplot (width, height).
TYPE:
|
var_names
|
Column name(s) to plot. If
TYPE:
|
from_date
|
Starting date for the forecast plot. If None, uses default date range.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure containing the forecast subplots. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If forecast results are not available. |
ValueError
|
If |
Plotting methods for Generalised Impulse Response Functions.
plot_girf ¶
plot_girf(shock_var: Optional[str | int | list] = None, response_var: Optional[str | int | list] = None, quantiles: tuple[float, float, float] = (0.16, 0.5, 0.84), figsize_per_plot: tuple[float, float] = (4.0, 3.0), max_cols: int = 4, title: Optional[str] = None, zero_line: bool = True) -> Figure
Plot posterior distributions of Generalised Impulse Response Functions.
Displays the posterior median and a credible band for each (shock variable, response variable) pair.
| PARAMETER | DESCRIPTION |
|---|---|
shock_var
|
Variable(s) to shock. Can be a column name, a 0-based index, or a list of names/indices. If None, all variables are shown.
TYPE:
|
response_var
|
Variable(s) whose responses to plot. Same format as
TYPE:
|
quantiles
|
(lower, median, upper) quantile levels for the credible band. Default is (0.16, 0.50, 0.84).
TYPE:
|
figsize_per_plot
|
(width, height) of each individual subplot. Default is (4, 3).
TYPE:
|
max_cols
|
Maximum number of subplot columns per row. Default is 4.
TYPE:
|
title
|
Overall figure title. If
TYPE:
|
zero_line
|
If True, draw a horizontal zero line on each subplot. Default is True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig
|
The figure object.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If |
Plot forecast comparisons from the DataFrame produced by compare_forecasts.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Long-format DataFrame with columns [date, quantile, variable, value, type]
returned by :func:
TYPE:
|
var_names
|
Variable(s) to plot. Defaults to all variables.
TYPE:
|
title
|
Figure suptitle.
TYPE:
|
figsize_per_plot
|
TYPE:
|
show
|
TYPE:
|
n_rows
|
Number of rows in the subplot grid. Default is 1.
TYPE:
|
metric_labels
|
Mapping
TYPE:
|
extra_data
|
Long-format DataFrame with columns
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure containing the forecast-revision subplots. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Plot KDEs for multiple series from a 2D data array.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data for which to compute and plot KDEs, with shape
TYPE:
|
labels
|
Labels for each series. If None, uses "Series 0", "Series 1", etc.
TYPE:
|
title
|
Title for the plot.
TYPE:
|
figsize
|
Figure size (width, height).
TYPE:
|
bw
|
Bandwidth for KDE. If None, uses default ('scott').
TYPE:
|
ax
|
Axes object to plot on. If None, creates a new figure and axes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig
|
The figure object.
TYPE:
|
ax
|
The axes object.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Plot histograms for multiple series from a 2D data array.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data for which to plot histograms, with shape
TYPE:
|
labels
|
Labels for each series. If None, uses "Series 0", "Series 1", etc.
TYPE:
|
title
|
Title for the plot.
TYPE:
|
figsize
|
Figure size (width, height).
TYPE:
|
bins
|
Number of bins for the histograms. Default is 30.
TYPE:
|
alpha
|
Opacity of the histogram bars. Default is 0.5.
TYPE:
|
colors
|
Colours for each series. If None, uses the default colour cycle.
TYPE:
|
ax
|
Axes object to plot on. If None, creates a new figure and axes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig
|
The figure object.
TYPE:
|
ax
|
The axes object.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |