Skip to content

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).

is_fitted property

is_fitted: bool

Check if the model has been fitted (posterior samples drawn).

dimensions property

dimensions: tuple[int, int, int, int]

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: DataFrame

nb_restart

Number of random restarts for the BFGS optimiser to avoid local minima. Default is 0 (single optimisation run).

TYPE: int DEFAULT: 0

initial_values

Initial hyperparameter values. If None, the method starts from default values with small random perturbations.

TYPE: Optional[ndarray] DEFAULT: None

target_series

Series names to target when scoring cross-validation error (used only when optimisation_method="cross_validation"). If None, the method averages predictive accuracy over every series.

TYPE: Optional[list[str]] DEFAULT: None

cv_options

Settings for cross-validation methods (e.g., number of folds, window size).

TYPE: Optional[dict] DEFAULT: None

add_priors

Whether to add Gamma hyperpriors on the hyperparameters when computing the marginal likelihood. Default is True.

TYPE: bool DEFAULT: True

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: Optional[int] DEFAULT: None

optimisation_backend

Backend for marginal-likelihood optimisation. "auto" uses JAX when installed and otherwise falls back to the NumPy/SciPy finite-difference implementation. "jax" requires the optional JAX dependency; "numpy" forces the legacy path.

TYPE: str DEFAULT: 'auto'

RETURNS DESCRIPTION
None

The method updates self.model.pars with the optimised hyperparameters.

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: DataFrame

N_draws

Number of posterior draws to retain after burn-in. Default is 5000.

TYPE: Optional[int] DEFAULT: None

N_burn

Number of initial burn-in draws to discard. Only relevant for MCMC samplers (e.g. "independent_niw"). Ignored for direct samplers. Default is N_draws // 2 for MCMC samplers, 0 for direct samplers.

TYPE: Optional[int] DEFAULT: None

point_only

If True, only compute the posterior point estimate without drawing samples. Useful for fast point estimates. Default is False.

TYPE: bool DEFAULT: False

progressbar

Whether to display a progress bar during sampling. Default is True.

TYPE: bool DEFAULT: True

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 transformations argument of forecast(), not here. Example: {"GDP": "log_diff", "CPI": "levels"}. The method stores this information and uses it to transform output in forecast(). Default is None.

TYPE: Optional[dict] DEFAULT: None

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 forecast calls; otherwise the method uses the instance generator. The global NumPy random state remains unchanged. Default is None.

TYPE: Optional[int] DEFAULT: None

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 : PosteriorState view of the point estimate

RAISES DESCRIPTION
Exception

If posterior sampling fails.

ValueError

If a draw or burn-in count is invalid.

compute_fitted_values

compute_fitted_values() -> None

Calculate fitted values across all posterior draws.

RAISES DESCRIPTION
RuntimeError

If model has not been fitted yet.

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: ndarray

cv_method

Cross-validation method. Only supports "predictive_ml".

TYPE: str DEFAULT: 'predictive_ml'

cv_options

Options for cross-validation. Required keys: H (forecast horizon) and oos_test_window_size. Optional key grid: a dict mapping hyperparameter names (c1, c3, mu, theta) to the number of points to keep on that axis, evenly spaced across the model's default grid, to coarsen the search. Default is None.

TYPE: Optional[dict] DEFAULT: None

target_indices

Indices of target variables for evaluation. If None, the method uses every variable.

TYPE: Optional[List[int]] DEFAULT: None

random_state

Seed or generator controlling the stochastic draws used across the grid search. Resolved once into a single private numpy.random.Generator (falling back to self.rng if None) and reused -- by identity, never restarted -- for every grid point and rolling window evaluated by marginal_likelihood_H. Default is None.

TYPE: Optional[int] DEFAULT: None

progressbar

Whether to display a progress bar. Default is True.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
None

The method stores optimised hyperparameters in self.model.pars.

RAISES DESCRIPTION
Exception

If a staged grid-search operation fails.

ValueError

If cv_method is not "predictive_ml", or if cv_options is missing or does not contain the required "H" and "oos_test_window_size" keys.

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: ndarray

H

Forecast horizon.

TYPE: int

target_indices

Indices of target variables for evaluation. If None, the method uses every variable.

TYPE: Optional[List[int]] DEFAULT: None

rolling_oos_starting_id

Starting index for the rolling window. If None, defaults to data.shape[0] - n_lags - H, i.e. training on as much data as possible and evaluating a single out-of-sample point at the end of the sample -- the same convention grid_search() uses via starting_t when oos_test_window_size=1. A literal 0 would always leave zero in-sample observations for the first fit (data[: 0 + n_lags] has exactly n_lags rows), which is degenerate.

TYPE: Optional[int] DEFAULT: None

random_state

Seed or generator controlling the stochastic draws used across rolling windows. Resolved once into a single private numpy.random.Generator (falling back to self.rng if None) and reused -- by identity, never restarted -- for every rolling-window sample/forecast call. Default is None.

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION
ml

Sum of log marginal likelihoods across all rolling windows.

TYPE: float

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: Optional[str | int | list] DEFAULT: None

response_var

Variable(s) whose responses to plot. Same format as shock_var. If None, all variables are shown.

TYPE: Optional[str | int | list] DEFAULT: None

quantiles

(lower, median, upper) quantile levels for the credible band. Default is (0.16, 0.50, 0.84).

TYPE: tuple[float, float, float] DEFAULT: (0.16, 0.5, 0.84)

figsize_per_plot

(width, height) of each individual subplot. Default is (4, 3).

TYPE: tuple[float, float] DEFAULT: (4.0, 3.0)

max_cols

Maximum number of subplot columns per row. Default is 4.

TYPE: int DEFAULT: 4

title

Overall figure title. If None, the method uses a default title.

TYPE: Optional[str] DEFAULT: None

zero_line

If True, draw a horizontal zero line on each subplot. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
fig

The figure object.

TYPE: Figure

RAISES DESCRIPTION
RuntimeError

If compute_girf() has not been called yet.

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: float DEFAULT: 95

max_cols

Maximum number of subplot columns per row.

TYPE: int DEFAULT: 3

figsize_per_plot

Size of each subplot (width, height).

TYPE: tuple DEFAULT: (5, 3)

var_names

Column name(s) to plot. If None, the method plots every series.

TYPE: Optional[str | list[str]] DEFAULT: None

RETURNS DESCRIPTION
Figure

The figure containing the fitted-value subplots.

RAISES DESCRIPTION
ValueError

If var_names contains invalid column names.

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: float DEFAULT: 0.05

max_cols

Maximum number of subplot columns per row.

TYPE: int DEFAULT: 3

figsize_per_plot

Size of each subplot (width, height).

TYPE: tuple DEFAULT: (5, 3)

var_names

Column name(s) to plot. If None, the method plots every series.

TYPE: Optional[str | list[str]] DEFAULT: None

from_date

Starting date for the forecast plot. If None, uses default date range.

TYPE: Optional[Period | str] DEFAULT: None

RETURNS DESCRIPTION
Figure

The figure containing the forecast subplots.

RAISES DESCRIPTION
RuntimeError

If forecast results are not available.

ValueError

If var_names contains invalid column names.

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: int

N_draws

Number of posterior draws to use. Default is 5000.

TYPE: int DEFAULT: 5000

point_only

If True, compute only for the posterior point estimates. Default is False.

TYPE: bool DEFAULT: False

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: Optional[dict] DEFAULT: None

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: Optional[dict] DEFAULT: None

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: Optional[dict] DEFAULT: None

progressbar

Whether to display a tqdm progress bar. Default is False.

TYPE: bool DEFAULT: False

base_value

Absolute last observed level for variables recorded as "diff" or "log_diff". A scalar applies to every variable; an array-like value supplies one value per variable. Required for level_change, pct_change, change_yoy, or pct_change_yoy responses of differenced variables. "logs" and "log_levels" derive their baseline from the exponentiated last observation instead.

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

RETURNS DESCRIPTION
GIRF

The BVAR object with GIRF results stored in its IRF attributes. irf_draws has shape (N_draws, H+1, n, n) and irf_var_names has length n.

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:

  1. Conditional conversion to level_changes: Raw IRFs are converted to a common "level_changes" representation for non-raw response types.

  2. "logs" or "log": level_change = baseline * dlog(y)

  3. "log_diff": level_change = baseline * Δlog(y)
  4. "levels": level_change = y (already level changes)
  5. "diff": level_change = Δy (already level changes)

  6. Apply transformations: From the appropriate representation, compute requested response_type for each variable independently.

  7. If response_type[var]=="raw": untouched GIRF

  8. 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: int

N_draws

Number of posterior draws to use for forecasting. Default is 5000.

TYPE: int DEFAULT: 5000

point_only

If True, compute a single plug-in forecast using the stored posterior point estimates. Default is False.

TYPE: bool DEFAULT: False

progressbar

Whether to display a progress bar. Default is False.

TYPE: bool DEFAULT: False

random_state

Seed or generator controlling the residual draws. If given, overrides the generator set at construction and is reused by later forecast/recursive_forecast calls; otherwise the method uses the instance generator. The global NumPy random state remains unchanged. Default is None.

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION
self

The BVAR object with forecasts stored in self.forecast_unconditional (shape: N_draws x (T+H) x n).

TYPE: Forecasting

RAISES DESCRIPTION
RuntimeError

If the model has no posterior draws (sample() was not called).

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: int

constraint_mean

Values to impose for the mean of the conditioned variables. Shape (H, n). Unconstrained values should be NaNs. Default is None (unconditional forecast).

TYPE: Optional[ndarray] DEFAULT: None

constraint_variance

Values to impose for the variance of the conditioned variables. Shape (H, n). Unconstrained values should be NaNs. Default is None (no variance constraints).

TYPE: Optional[ndarray] DEFAULT: None

constraint_shape

Values to impose for the shape/skewness of the conditioned variables. Shape (H, n). Unconstrained values should be NaNs. Default is None (no skewness constraints).

TYPE: Optional[ndarray] DEFAULT: None

method

Method for handling constraints. Default is "andersson_et_al".

TYPE: str DEFAULT: 'andersson_et_al'

N_draws

Number of MCMC draws used to simulate the uncertainty of conditional forecasts. Default is 5000. Must be positive; capped at self.N_draws (the number of stored posterior draws) before the method sets the default burn-in.

TYPE: int DEFAULT: 5000

N_burn

Number of burn-in draws to discard. Default is effective_N_draws // 2 if None, where effective_N_draws is N_draws after capping. If given explicitly, must be an integer in [0, effective_N_draws).

TYPE: Optional[int] DEFAULT: None

point_only

If True, returns only the conditional mean using the median draw from the Bayesian sampling (much faster). Default is False.

TYPE: bool DEFAULT: False

format

Whether to format the output as a DataFrame with dates. Default is False.

TYPE: bool DEFAULT: False

quantiles

List of quantiles to compute if format is True. Default is [0.16, 0.5, 0.84].

TYPE: Optional[list] DEFAULT: None

base_value

Absolute level at the end of the observed sample, required when a forecast tail contains rows reconstructed from "diff" or "log_diff" data. May be a scalar or one value per variable.

TYPE: Optional[ndarray] DEFAULT: None

constraint_sampler

Custom constraint sampler function. Default is None.

TYPE: Optional[Callable] DEFAULT: None

progressbar

Whether to display a progress bar during forecasting. Default is False.

TYPE: bool DEFAULT: False

transformations

Dictionary mapping variable names or indices to transformation types to APPLY to the forecasts. Supported: "qoq", "yoy".

TYPE: Optional[dict] DEFAULT: None

random_state

Seed or generator controlling the stochastic forecast draws. If given, overrides the generator set at construction and is reused in later forecast/recursive_forecast calls; otherwise the method uses the instance generator. The global NumPy random state remains unchanged. Default is None.

TYPE: Optional[int] DEFAULT: None

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 (sample() was not called).

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: int

N_draws

Number of posterior draws to use. Default is 5000.

TYPE: int DEFAULT: 5000

point_only

If True, compute only for the posterior point estimates. Default is False.

TYPE: bool DEFAULT: False

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: Optional[dict] DEFAULT: None

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: Optional[dict] DEFAULT: None

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: Optional[dict] DEFAULT: None

progressbar

Whether to display a tqdm progress bar. Default is False.

TYPE: bool DEFAULT: False

base_value

Absolute last observed level for variables recorded as "diff" or "log_diff". A scalar applies to every variable; an array-like value supplies one value per variable. Required for level_change, pct_change, change_yoy, or pct_change_yoy responses of differenced variables. "logs" and "log_levels" derive their baseline from the exponentiated last observation instead.

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

RETURNS DESCRIPTION
GIRF

The BVAR object with GIRF results stored in its IRF attributes. irf_draws has shape (N_draws, H+1, n, n) and irf_var_names has length n.

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:

  1. Conditional conversion to level_changes: Raw IRFs are converted to a common "level_changes" representation for non-raw response types.

  2. "logs" or "log": level_change = baseline * dlog(y)

  3. "log_diff": level_change = baseline * Δlog(y)
  4. "levels": level_change = y (already level changes)
  5. "diff": level_change = Δy (already level changes)

  6. Apply transformations: From the appropriate representation, compute requested response_type for each variable independently.

  7. If response_type[var]=="raw": untouched GIRF

  8. 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 (T, n).

TYPE: ndarray

levels

Indicator array with shape (n,): 0 for first differences, 1 for levels.

TYPE: ndarray

RETURNS DESCRIPTION
sum_diff

Cumulative changes from the second observation onward, with shape (T-1, n).

TYPE: ndarray

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 (n_draws, n_params).

TYPE: ndarray

true_pars

Array of true parameter values for reference (default: None).

TYPE: Optional[ndarray] DEFAULT: None

max_cols

Maximum number of columns in the subplot grid.

TYPE: int DEFAULT: 3

figsize_per_plot

Size of each subplot (width, height).

TYPE: tuple DEFAULT: (5, 3)

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: int

n

Number of variables.

TYPE: int

n_lags

Number of lags.

TYPE: int

covid

Whether to include COVID dummies (default: False).

TYPE: bool DEFAULT: False

levels

If True, returns integrated (non-stationary) data (default: False).

TYPE: bool DEFAULT: False

ar_mat

First AR coefficient matrix with shape (n, n) (default: None, random generation).

TYPE: Optional[ndarray] DEFAULT: None

constant

Constant vector with shape (n,) (default: None, random generation).

TYPE: Optional[ndarray] DEFAULT: None

Sigma

Covariance matrix for error terms with shape (n, n) (default: None).

TYPE: Optional[ndarray] DEFAULT: None

seed

Seed or numpy.random.Generator for reproducibility (default: None). The function uses a local generator and leaves the global NumPy random state unchanged.

TYPE: Optional[Union[int, Generator]] DEFAULT: None

RETURNS DESCRIPTION
y

Simulated time series data with shape (T, n) and a quarterly pd.PeriodIndex starting 1990Q1 (COVID dummies, when enabled, assume the 2020Q1-2021Q4 window). Re-index the frame for a different frequency.

TYPE: DataFrame

b

True parameter vector with shape (n * (1 + n*n_lags + h),) where h is 8 when COVID dummies are enabled and 0 otherwise.

TYPE: ndarray

sigma

Covariance matrix used for simulation with shape (n, n).

TYPE: ndarray

eps

Simulated error terms with shape (T, n).

TYPE: ndarray

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: int

N_draws

Number of posterior draws to use for forecasting. Default is 5000.

TYPE: int DEFAULT: 5000

point_only

If True, compute a single plug-in forecast using the stored posterior point estimates. Default is False.

TYPE: bool DEFAULT: False

progressbar

Whether to display a progress bar. Default is False.

TYPE: bool DEFAULT: False

random_state

Seed or generator controlling the residual draws. If given, overrides the generator set at construction and is reused by later forecast/recursive_forecast calls; otherwise the method uses the instance generator. The global NumPy random state remains unchanged. Default is None.

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION
self

The BVAR object with forecasts stored in self.forecast_unconditional (shape: N_draws x (T+H) x n).

TYPE: Forecasting

RAISES DESCRIPTION
RuntimeError

If the model has no posterior draws (sample() was not called).

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: int

constraint_mean

Values to impose for the mean of the conditioned variables. Shape (H, n). Unconstrained values should be NaNs. Default is None (unconditional forecast).

TYPE: Optional[ndarray] DEFAULT: None

constraint_variance

Values to impose for the variance of the conditioned variables. Shape (H, n). Unconstrained values should be NaNs. Default is None (no variance constraints).

TYPE: Optional[ndarray] DEFAULT: None

constraint_shape

Values to impose for the shape/skewness of the conditioned variables. Shape (H, n). Unconstrained values should be NaNs. Default is None (no skewness constraints).

TYPE: Optional[ndarray] DEFAULT: None

method

Method for handling constraints. Default is "andersson_et_al".

TYPE: str DEFAULT: 'andersson_et_al'

N_draws

Number of MCMC draws used to simulate the uncertainty of conditional forecasts. Default is 5000. Must be positive; capped at self.N_draws (the number of stored posterior draws) before the method sets the default burn-in.

TYPE: int DEFAULT: 5000

N_burn

Number of burn-in draws to discard. Default is effective_N_draws // 2 if None, where effective_N_draws is N_draws after capping. If given explicitly, must be an integer in [0, effective_N_draws).

TYPE: Optional[int] DEFAULT: None

point_only

If True, returns only the conditional mean using the median draw from the Bayesian sampling (much faster). Default is False.

TYPE: bool DEFAULT: False

format

Whether to format the output as a DataFrame with dates. Default is False.

TYPE: bool DEFAULT: False

quantiles

List of quantiles to compute if format is True. Default is [0.16, 0.5, 0.84].

TYPE: Optional[list] DEFAULT: None

base_value

Absolute level at the end of the observed sample, required when a forecast tail contains rows reconstructed from "diff" or "log_diff" data. May be a scalar or one value per variable.

TYPE: Optional[ndarray] DEFAULT: None

constraint_sampler

Custom constraint sampler function. Default is None.

TYPE: Optional[Callable] DEFAULT: None

progressbar

Whether to display a progress bar during forecasting. Default is False.

TYPE: bool DEFAULT: False

transformations

Dictionary mapping variable names or indices to transformation types to APPLY to the forecasts. Supported: "qoq", "yoy".

TYPE: Optional[dict] DEFAULT: None

random_state

Seed or generator controlling the stochastic forecast draws. If given, overrides the generator set at construction and is reused in later forecast/recursive_forecast calls; otherwise the method uses the instance generator. The global NumPy random state remains unchanged. Default is None.

TYPE: Optional[int] DEFAULT: None

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 (sample() was not called).

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: DataFrame

df_forecast_b

Second forecast DataFrame in long format (same structure).

TYPE: DataFrame

H

Forecast horizon used for filtering.

TYPE: int

labels

Labels for the two forecasts. Default is ["forecast_a", "forecast_b"].

TYPE: Optional[list[str]] DEFAULT: None

n_outturns

Number of preceding outturns to retain.

TYPE: int DEFAULT: 0

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: float DEFAULT: 0.5

minnesota

Whether to use the Minnesota prior.

TYPE: bool DEFAULT: True

soc

Whether to use the sum-of-coefficients prior.

TYPE: bool DEFAULT: True

sur

Whether to use the single-unit-root prior.

TYPE: bool DEFAULT: True

covid

Whether to include COVID dummy observations.

TYPE: bool DEFAULT: False

covid_dates

Start and end dates for the COVID period.

TYPE: Optional[list] DEFAULT: None

ATTRIBUTE DESCRIPTION
requires_burnin

True — Gibbs draws require burn-in.

TYPE: bool

supports_ml

False — no closed-form marginal likelihood.

TYPE: bool

supports_point_only

False — the posterior has no closed-form point estimate, so optimisation_method="cross_validation" is not supported. Use "none" and set hyperparameters manually.

TYPE: bool

set_priors

set_priors(*, c2: float | None = None, **kwargs) -> None

Set prior hyperparameters including cross-variable shrinkage c2.

Also computes Gamma hyperprior parameters for c2.

fill_in_from_vector

fill_in_from_vector(pars: ndarray) -> None

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: ndarray

n_lags

Number of VAR lags.

TYPE: int

covid_indices

Indices for COVID dummy observations.

TYPE: ndarray

vars_in_levels

Indicators for variables in levels.

TYPE: ndarray

N_draws

Number of posterior draws.

TYPE: int

point_only

Whether to request a point estimate.

TYPE: bool DEFAULT: False

progressbar

Whether to display a progress bar.

TYPE: bool DEFAULT: True

soc

Effective sum-of-coefficients flag.

TYPE: Optional[bool] DEFAULT: None

sur

Effective single-unit-root flag.

TYPE: Optional[bool] DEFAULT: None

rng

Random number generator.

TYPE: Optional[Generator] DEFAULT: None

RETURNS DESCRIPTION
SamplingResult

Posterior draws and point estimates.

RAISES DESCRIPTION
ValueError

If point_only is True (no closed-form posterior point estimate).

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

False — draws come directly from the known posterior.

TYPE: bool

supports_ml

True — a closed-form marginal likelihood is available (GLP 2015).

TYPE: bool

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: ndarray

sigma

Flattened covariance matrix.

TYPE: ndarray

extras

Arbitrary model-owned auxiliary state, or None if the model has no additional state beyond beta/sigma.

TYPE: Optional[Any]

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 extras holds an object that cannot be deep-copied (e.g. a lock or other live resource). The method raises this error instead of aliasing the original object. A model with such a payload should override sample_posterior_state to manage that state's isolation itself instead of relying on this default copy().

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 True; with False the coefficient prior is effectively flat.

TYPE: bool DEFAULT: True

soc

Add sum-of-coefficients dummy observations. Default True. Disabled for a fit when stationary=True is passed to BVAR.

TYPE: bool DEFAULT: True

sur

Add a single-unit-root dummy observation. Default True. Disabled for a fit when stationary=True is passed to BVAR.

TYPE: bool DEFAULT: True

covid

Include COVID-19 outlier dummies. Default False.

TYPE: bool DEFAULT: False

covid_dates

Two-element list [start, end] defining the COVID period. Each element may be anything pandas can interpret as a date (e.g. a string "2020-03-01", a pd.Timestamp or a pd.Period). The method matches dates against the data index at the data's own frequency, so it supports monthly, quarterly, and other frequencies. Defaults to the 2020Q1-2021Q4 window if None.

TYPE: Optional[list] DEFAULT: None

ATTRIBUTE DESCRIPTION
requires_burnin

True for MCMC samplers whose initial draws should be discarded; False for direct samplers.

TYPE: bool

supports_ml

True if a closed-form marginal likelihood is available for hyperparameter optimisation (GLP 2015).

TYPE: bool

supports_point_only

True if the model has a closed-form posterior point estimate and supports point_only=True sampling. Required for optimisation_method="cross_validation", which repeatedly refits the model with point_only=True inside the grid search.

TYPE: bool

supports_gaussian_predictive

True when the model uses the reduced-form Gaussian used by :meth:sample_innovations, :meth:sample_conditional_forecast and :meth:predictive_logpdf. True for every current (Gaussian) model. A non-Gaussian model should set this to False and override each hook that needs a different predictive distribution; the default implementations raise NotImplementedError in that case.

TYPE: bool

supports_girf

True if :meth:~bvar.girf.GIRF.compute_girf may be used with this model. True for every current (Gaussian) model. The current GIRF implementation is hard-coded to the Gaussian reduced-form predictive distribution, so compute_girf also requires supports_gaussian_predictive=True; setting supports_girf=True on a model with supports_gaussian_predictive=False does not enable GIRFs. A non-Gaussian model should leave this False until a GIRF implementation compatible with its own predictive distribution exists.

TYPE: bool

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

fill_in_from_vector(pars: ndarray) -> None

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.

to_vector

to_vector() -> ndarray

Extract searchable hyperparameters as a vector.

hyperparameter_grid

hyperparameter_grid() -> list[ndarray]

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 (T_total, n) (before lag trimming).

TYPE: ndarray

n_lags

Number of VAR lags.

TYPE: int

covid_indices

Observation indices for COVID dummy variables.

TYPE: ndarray

vars_in_levels

Boolean array with shape (n,) indicating which variables are in levels.

TYPE: ndarray

N_draws

Total number of posterior draws to generate, including draws that the caller will discard as burn-in.

TYPE: int

point_only

If True, compute only the posterior point estimate.

TYPE: bool DEFAULT: False

progressbar

Whether to display a progress bar.

TYPE: bool DEFAULT: True

soc

Effective sum-of-coefficients flag for this fit. The flag records whether the code stacks SOC dummy observations. It defaults to self.soc; callers should pass a fit-specific value, such as False when no variable uses levels, rather than mutate self.soc.

TYPE: Optional[bool] DEFAULT: None

sur

Effective single-unit-root flag for this fit, analogous to soc. Defaults to self.sur if not given.

TYPE: Optional[bool] DEFAULT: None

rng

Generator for the posterior draws. Defaults to a fresh numpy.random.default_rng() if not given.

TYPE: Optional[Generator] DEFAULT: None

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: ndarray

Z

Regressor matrix (with dummies already stacked if applicable).

TYPE: ndarray

current_state

The previous draw's state. Direct samplers (e.g. :class:~bvar.models.conjugate.NaturalConjugate) sample independently and ignore this state. MCMC samplers (e.g. :class:~bvar.models.independent_niw.IndependentNIW) use current_state.sigma as the starting point for the next Gibbs sweep; the Independent-NIW Gibbs kernel does not need current_state.beta either — β is freshly sampled conditional on Σ within each sweep.

TYPE: PosteriorState

rng

Generator for the draw. Defaults to a fresh numpy.random.default_rng() if not given.

TYPE: Optional[Generator] DEFAULT: None

RETURNS DESCRIPTION
PosteriorState

The next draw's state. extras is None unless the model carries auxiliary state beyond beta/sigma, in which case the override should update and forward its own payload.

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 BVAR.posterior_state_point when point_only).

TYPE: PosteriorState

H

Forecast horizon (number of steps ahead).

TYPE: int

rng

Generator for the draw. Defaults to a fresh numpy.random.default_rng() if not given.

TYPE: Optional[Generator] DEFAULT: None

point_only

If True, return an all-zero array (point-estimate forecast, no random innovations). Default False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
ndarray

Reduced-form innovations, one row per forecast step.

RAISES DESCRIPTION
NotImplementedError

If supports_gaussian_predictive is False: the default Gaussian implementation does not apply, and the subclass must override this method.

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: PosteriorState

C

Constraint-selection matrix, as returned by :func:~bvar.forecast.conditional.get_constraint, with shape (nb_constraints, H*n).

TYPE: ndarray

f

Constraint locations with shape (nb_constraints,).

TYPE: ndarray

Sigma_f

Constraint scale matrix with shape (nb_constraints, nb_constraints).

TYPE: ndarray

shape_f

Constraint shape parameters with shape (nb_constraints,).

TYPE: ndarray

last_p_obs

Last p observations before the forecast period, with shape (p, n).

TYPE: ndarray

p

Number of lags.

TYPE: int

n

Number of variables.

TYPE: int

h

Number of COVID dummies.

TYPE: int

H

Forecast horizon.

TYPE: int

point_only

If True, return only the conditional mean (no sampling).

TYPE: bool

constraint_sampler

Custom function to sample from the constraint distribution.

TYPE: Optional[Callable] DEFAULT: None

method

Algorithm: "andersson_et_al", "antolin_diaz_et_al", or "labonne_renzetti". Default "andersson_et_al".

TYPE: str DEFAULT: 'andersson_et_al'

rng

Generator for the draw. Defaults to a fresh numpy.random.default_rng() if not given.

TYPE: Optional[Generator] DEFAULT: None

RETURNS DESCRIPTION
ndarray

Forecast values (flattened), with shape (H*n,).

RAISES DESCRIPTION
NotImplementedError

If supports_gaussian_predictive is False: the default Gaussian implementation does not apply, and the subclass must override this method.

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 BVAR.posterior_state_point) accompanying mean/covariance.

TYPE: PosteriorState

observation

The realised out-of-sample observation with shape (n_targets,).

TYPE: ndarray

mean

Predictive mean at the forecast horizon with shape (n_targets,).

TYPE: ndarray

covariance

Predictive covariance at the forecast horizon with shape (n_targets, n_targets).

TYPE: ndarray

RETURNS DESCRIPTION
float

Log predictive density of observation.

RAISES DESCRIPTION
NotImplementedError

If supports_gaussian_predictive is False: the default Gaussian implementation does not apply, and the subclass must override this method.

Container for the output of a model's sample() method.

ATTRIBUTE DESCRIPTION
beta_draws

Posterior draws of VAR coefficients (vectorised), with shape (N_draws, nk).

TYPE: ndarray

sigma_draws

Posterior draws of the covariance matrix (flattened), with shape (N_draws, n**2).

TYPE: ndarray

beta_point

Posterior point estimate of VAR coefficients, with shape (nk,).

TYPE: ndarray

sigma_point

Posterior point estimate of the covariance matrix, with shape (n**2,). For the conjugate model this is the posterior mean.

TYPE: ndarray

extras_point

Model-owned auxiliary state accompanying the point estimate, or None for models that carry no state beyond beta/sigma (the default for all current models).

TYPE: Optional[Any]

extras_draws

Model-owned auxiliary state for each retained draw, one entry per row of beta_draws/sigma_draws, or None for models that carry no per-draw state beyond beta/sigma (the default for all current models). Validated at construction (see :meth:__post_init__) to have exactly one entry per draw.

TYPE: Optional[list]

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__

__post_init__() -> None

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: float DEFAULT: 95

max_cols

Maximum number of subplot columns per row.

TYPE: int DEFAULT: 3

figsize_per_plot

Size of each subplot (width, height).

TYPE: tuple DEFAULT: (5, 3)

var_names

Column name(s) to plot. If None, the method plots every series.

TYPE: Optional[str | list[str]] DEFAULT: None

RETURNS DESCRIPTION
Figure

The figure containing the fitted-value subplots.

RAISES DESCRIPTION
ValueError

If var_names contains invalid column names.

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: float DEFAULT: 0.05

max_cols

Maximum number of subplot columns per row.

TYPE: int DEFAULT: 3

figsize_per_plot

Size of each subplot (width, height).

TYPE: tuple DEFAULT: (5, 3)

var_names

Column name(s) to plot. If None, the method plots every series.

TYPE: Optional[str | list[str]] DEFAULT: None

from_date

Starting date for the forecast plot. If None, uses default date range.

TYPE: Optional[Period | str] DEFAULT: None

RETURNS DESCRIPTION
Figure

The figure containing the forecast subplots.

RAISES DESCRIPTION
RuntimeError

If forecast results are not available.

ValueError

If var_names contains invalid column names.

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: Optional[str | int | list] DEFAULT: None

response_var

Variable(s) whose responses to plot. Same format as shock_var. If None, all variables are shown.

TYPE: Optional[str | int | list] DEFAULT: None

quantiles

(lower, median, upper) quantile levels for the credible band. Default is (0.16, 0.50, 0.84).

TYPE: tuple[float, float, float] DEFAULT: (0.16, 0.5, 0.84)

figsize_per_plot

(width, height) of each individual subplot. Default is (4, 3).

TYPE: tuple[float, float] DEFAULT: (4.0, 3.0)

max_cols

Maximum number of subplot columns per row. Default is 4.

TYPE: int DEFAULT: 4

title

Overall figure title. If None, the method uses a default title.

TYPE: Optional[str] DEFAULT: None

zero_line

If True, draw a horizontal zero line on each subplot. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
fig

The figure object.

TYPE: Figure

RAISES DESCRIPTION
RuntimeError

If compute_girf() has not been called yet.

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:compare_forecasts.

TYPE: DataFrame

var_names

Variable(s) to plot. Defaults to all variables.

TYPE: Optional[str | list[str]] DEFAULT: None

title

Figure suptitle.

TYPE: str DEFAULT: 'Forecast revision'

figsize_per_plot

(width, height) of each subplot panel.

TYPE: tuple DEFAULT: (5, 3.5)

show

"difference" (default) plots the revision; "forecasts" overlays both forecast series.

TYPE: str DEFAULT: 'difference'

n_rows

Number of rows in the subplot grid. Default is 1.

TYPE: int DEFAULT: 1

metric_labels

Mapping variable -> str appended to each subplot title (e.g. the reporting transformation such as "yoy"/"qoq"/"levels").

TYPE: Optional[dict] DEFAULT: None

extra_data

Long-format DataFrame with columns [date, variable, value] (and optionally series and quantile) drawn as extra dashed line(s) per subplot when show="forecasts" (e.g. an external published projection). If a series column is present, one line is drawn per series and labelled with its name; otherwise a single line labelled "extra" is drawn. Dates are aligned to the plotted timeline; dates outside the axis are ignored.

TYPE: Optional[DataFrame] DEFAULT: None

RETURNS DESCRIPTION
Figure

The figure containing the forecast-revision subplots.

RAISES DESCRIPTION
ValueError

If show is not "difference" or "forecasts".

Plot KDEs for multiple series from a 2D data array.

PARAMETER DESCRIPTION
data

Data for which to compute and plot KDEs, with shape (n_samples, n_series).

TYPE: ndarray

labels

Labels for each series. If None, uses "Series 0", "Series 1", etc.

TYPE: Optional[list[str]] DEFAULT: None

title

Title for the plot.

TYPE: Optional[str] DEFAULT: None

figsize

Figure size (width, height).

TYPE: tuple DEFAULT: (10, 6)

bw

Bandwidth for KDE. If None, uses default ('scott').

TYPE: Optional[float | str] DEFAULT: None

ax

Axes object to plot on. If None, creates a new figure and axes.

TYPE: Optional[Axes] DEFAULT: None

RETURNS DESCRIPTION
fig

The figure object.

TYPE: Figure

ax

The axes object.

TYPE: Axes

RAISES DESCRIPTION
ValueError

If labels does not match the number of data series.

Plot histograms for multiple series from a 2D data array.

PARAMETER DESCRIPTION
data

Data for which to plot histograms, with shape (n_samples, n_series).

TYPE: ndarray

labels

Labels for each series. If None, uses "Series 0", "Series 1", etc.

TYPE: Optional[list[str]] DEFAULT: None

title

Title for the plot.

TYPE: Optional[str] DEFAULT: None

figsize

Figure size (width, height).

TYPE: tuple DEFAULT: (10, 6)

bins

Number of bins for the histograms. Default is 30.

TYPE: int DEFAULT: 30

alpha

Opacity of the histogram bars. Default is 0.5.

TYPE: float DEFAULT: 0.5

colors

Colours for each series. If None, uses the default colour cycle.

TYPE: Optional[list] DEFAULT: None

ax

Axes object to plot on. If None, creates a new figure and axes.

TYPE: Optional[Axes] DEFAULT: None

RETURNS DESCRIPTION
fig

The figure object.

TYPE: Figure

ax

The axes object.

TYPE: Axes

RAISES DESCRIPTION
ValueError

If labels does not match the number of data series.