| Title: | Bayesian Inference of Vector Autoregressive and Error Correction Models |
|---|---|
| Description: | Assists in the set-up of algorithms for Bayesian inference of vector autoregressive (VAR) and error correction (VEC) models. Functions for posterior simulation, forecasting, impulse response analysis and forecast error variance decomposition are largely based on the introductory texts of Chan, Koop, Poirier and Tobias (2019, ISBN: 9781108437493), Koop and Korobilis (2010) <doi:10.1561/0800000013> and Luetkepohl (2006, ISBN: 9783540262398). |
| Authors: | Franz X. Mohr [aut, cre, cph] (ORCID: <https://orcid.org/0009-0003-8890-7781>) |
| Maintainer: | Franz X. Mohr <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 1.0.0 |
| Built: | 2026-10-04 13:31:25 UTC |
| Source: | https://github.com/franzmohr/bvartools |
A generic function used to add dummy variables to the deterministic terms of a model.
add_dummy_variables(object, ...)add_dummy_variables(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_dummy_variables.bvarmodel,
add_dummy_variables.bvecmodel,
add_dummy_variables.expandingwindow,
add_dummy_variables.modellist.
Adds dummy variables to the deterministic terms of a model: impulse dummies for single unusual periods, step dummies for level shifts, or any other series that is known in advance.
## S3 method for class 'bvarmodel' add_dummy_variables(object, impulse = NULL, step = NULL, data = NULL, ...) ## S3 method for class 'bvecmodel' add_dummy_variables(object, impulse = NULL, step = NULL, data = NULL, ...) ## S3 method for class 'expandingwindow' add_dummy_variables(object, impulse = NULL, step = NULL, data = NULL, ...) ## S3 method for class 'modellist' add_dummy_variables(object, ...)## S3 method for class 'bvarmodel' add_dummy_variables(object, impulse = NULL, step = NULL, data = NULL, ...) ## S3 method for class 'bvecmodel' add_dummy_variables(object, impulse = NULL, step = NULL, data = NULL, ...) ## S3 method for class 'expandingwindow' add_dummy_variables(object, impulse = NULL, step = NULL, data = NULL, ...) ## S3 method for class 'modellist' add_dummy_variables(object, ...)
object |
an object of class 'bvarmodel' or 'bvecmodel', usually the
output of |
impulse |
a period, given the way |
step |
a period or a list of periods as in |
data |
an optional time-series object of further dummy variables, or of any other series known in advance, with named columns at the frequency of the model. It has to cover the estimation sample. See 'Details'. |
... |
further arguments passed to or from other methods. |
A dummy variable takes up what a model otherwise has no explanation for: an impulse dummy the one period of a strike, a tax change or a pandemic, a step dummy a lasting shift in the level of the series, such as a change in how they are measured. Without one, a single extreme observation pulls the coefficients of every equation towards itself and inflates the estimated error variance for the whole sample.
The dummies are deterministic terms like the constant. They are appended to
the end of the deterministic terms of the regressors, named after their type
and period – impulse.2020Q2, step.2008M09 – or after the
columns of data, and their coefficients take the prior of the
deterministic terms, v_i_det in add_priors.
The coefficient of an impulse dummy is estimated from a single
observation, so its prior matters more than that of the constant: a tight
one leaves most of the observation to the other coefficients, which is what
the dummy was meant to prevent.
The function has to be called before add_priors,
since it changes the number of coefficients the priors are given for. A
dummy variable that is zero in every period of the estimation sample, or
that the other regressors already span – a step dummy that is one in every
period is the constant again – is refused.
A forecast continues the dummies by their definition: an impulse dummy is
zero after its period and a step dummy stays one. The series in data
are continued with the values they were given, so for a forecast they have
to reach the last forecast period, or all deterministic terms of the
forecast have to be given in argument deterministic of
add_forecast_input.
Of a list of models of class 'expandingwindow', each window gets the dummies
whose periods it reaches and leaves out the rest: a forecast made at the end
of a window that ends before a period could not have known about what
happened in it. use_expanding_window applied to a model with
dummy variables does the same.
In a VEC model the dummies enter the equations of the differences, not the
cointegration term. An impulse dummy there shifts the level of the
series for good, since a one-off change in a difference is a lasting change
in the level. A one-off blip in the level is a dummy that is one in its
period and minus one in the next, which can be given in data.
vec_to_var carries the dummies into the VAR representation.
The object in object with the dummy variables added to
data$train$x and its SUR form data$train$z, to
data$original$deterministic and to the names in
model$deterministic, model$n increased by their number, and
model$dummy_variables, a data frame with one row per dummy variable
giving its name, its type ("impulse", "step" or
"data") and the time of its period, which is what a forecast
continues it by.
Other model set-up:
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # An impulse dummy for the first quarter of 1975 and a step dummy from 1979 model <- add_dummy_variables(model, impulse = c(1975, 1), step = c(1979, 1)) model[["model"]][["deterministic"]] # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1))# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # An impulse dummy for the first quarter of 1975 and a step dummy from 1979 model <- add_dummy_variables(model, impulse = c(1975, 1), step = c(1979, 1)) model[["model"]][["deterministic"]] # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1))
Generic function used to calculate forecast errors and add them to a model object.
add_forecast_errors(object, test_sample = NULL, ...)add_forecast_errors(object, test_sample = NULL, ...)
object |
an object of a class, for which a method should be called. |
test_sample |
a time-series object used as test data. If |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_forecast_errors.bvarmodel,
add_forecast_errors.expandingwindow,
add_forecast_errors.modellist.
Calculates forecast errors and adds them to an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' add_forecast_errors(object, test_sample = NULL, ...)## S3 method for class 'bvarmodel' add_forecast_errors(object, test_sample = NULL, ...)
object |
an object of class 'bvarmodel'. |
test_sample |
a time-series object used as test data. If |
... |
arguments passed forward to method. |
The object in object with posterior$forecast$errors added, a
mcmc object with one row per draw and columns in the
order of posterior$forecast$forecasts, which it is stored beside.
selection_criteria summarises them.
bvartools_model describes the object this returns, element by element.
Other model comparison:
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig)
Calculates the forecast errors of a VEC model against a test sample, in levels.
## S3 method for class 'bvecmodel' add_forecast_errors(object, test_sample = NULL, ...)## S3 method for class 'bvecmodel' add_forecast_errors(object, test_sample = NULL, ...)
object |
an object of class 'bvecmodel', usually, the result of a call to
|
test_sample |
a time-series object of the endogenous variables, in levels, that
covers the forecast periods. If |
... |
further arguments passed to |
The forecasts of a VEC model are of the levels, so the errors are taken against
the levels of test_sample, exactly as for the VAR representation
vec_to_var would give.
The object in object with posterior$forecast$errors added, as
described in add_forecast_errors.bvarmodel.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
Calculates and adds forecast errors for a list of Bayesian models.
## S3 method for class 'expandingwindow' add_forecast_errors(object, test_sample = NULL, ...)## S3 method for class 'expandingwindow' add_forecast_errors(object, test_sample = NULL, ...)
object |
an object of class 'expandingwindow'. |
test_sample |
a time-series object used as test data. If |
... |
arguments passed forward to method. |
The object in object with forecast errors added to each of its models, as
described in add_forecast_errors.bvarmodel.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig)
Calculates and adds forecast errors for a list of Bayesian models.
## S3 method for class 'modellist' add_forecast_errors(object, test_sample = NULL, ...)## S3 method for class 'modellist' add_forecast_errors(object, test_sample = NULL, ...)
object |
an object of class 'modellist'. |
test_sample |
a time-series object used as test data. If |
... |
arguments passed forward to method. |
The object in object with forecast errors added to each of its models, as
described in add_forecast_errors.bvarmodel.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig)
Generic function used to generate and add data matrices for forecast simulation to a model object.
add_forecast_input(object, ...)add_forecast_input(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_forecast_input.bvarmodel,
add_forecast_input.bvecmodel,
add_forecast_input.expandingwindow,
add_forecast_input.externalforecast,
add_forecast_input.modellist.
Generates and adds data matrices for forecast simulation to the elements of an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' add_forecast_input( object, n_ahead = 10, deterministic = NULL, exogen = NULL, ... )## S3 method for class 'bvarmodel' add_forecast_input( object, n_ahead = 10, deterministic = NULL, exogen = NULL, ... )
object |
an object of class 'bvarmodel'. |
n_ahead |
number of steps ahead at which to predict. |
deterministic |
a time-series object with deterministic data. If not specified, the function will try to identify the deterministic terms automatically. If this is not successful, an error message we be returned. |
exogen |
a time-series object with the unmodelled, non-deterministic variables of the
model. Required if the model has such variables. It has to cover the |
... |
arguments passed forward to method. |
The object in object with model$h set to n_ahead and
data$forecast$x added, the regressors of the forecast periods in the layout of
data$train$x, one row per period.
Other posterior simulation:
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4)
Prepares the input data of the forecast periods of a VEC model.
## S3 method for class 'bvecmodel' add_forecast_input( object, n_ahead = 10, deterministic = NULL, exogen = NULL, ... )## S3 method for class 'bvecmodel' add_forecast_input( object, n_ahead = 10, deterministic = NULL, exogen = NULL, ... )
object |
an object of class 'bvecmodel', usually, the result of a call to
|
n_ahead |
an integer of the forecast horizon. |
deterministic, exogen
|
the values of the deterministic terms and of the
unmodelled variables in the forecast periods, as for
|
... |
further arguments passed to |
A VEC model is forecast in levels: it is the same model as its VAR
representation, and the forecast of the differences follows from that of the
levels. The regressors of the forecast periods are therefore those of the VAR
in levels, and are assembled from the data and specification that
vec_to_var builds. The posterior draws are not converted.
The object in object with the forecast horizon in model$h
and the regressors of the forecast periods, in levels, in data$forecast$x.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
Generates and adds data matrices for forecast simulation to the elements of an object of class 'expandingwindow'.
## S3 method for class 'expandingwindow' add_forecast_input(object, ...)## S3 method for class 'expandingwindow' add_forecast_input(object, ...)
object |
an object of class 'expandingwindow' containing objects that can
be passed on to their respective |
... |
arguments passed forward to method. |
The object in object with forecast input added to each of its models, as
described in add_forecast_input.bvarmodel.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4)
Generates and adds data matrices for forecast simulation to the elements of an object of class 'modellist'.
## S3 method for class 'modellist' add_forecast_input(object, ...)## S3 method for class 'modellist' add_forecast_input(object, ...)
object |
an object of class 'modellist' containing objects that can
be passed on to their respective |
... |
arguments passed forward to method. |
The object in object with forecast input added to each of its models, as
described in add_forecast_input.bvarmodel.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4)
A generic function used to generate initial values of an MCMC chain. The function invokes particular methods which depend on the class of the first argument.
add_initial_values(object, ...)add_initial_values(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_initial_values.bvarmodel,
add_initial_values.bvecmodel,
add_initial_values.expandingwindow,
add_initial_values.externalforecast,
add_initial_values.modellist.
Adds initial values to a VAR model.
## S3 method for class 'bvarmodel' add_initial_values(object, method = "ols", ...)## S3 method for class 'bvarmodel' add_initial_values(object, method = "ols", ...)
object |
list of class 'bvarmodel', usually, the result of a call to
|
method |
character specifying the method of how initial values are generated.
Default is |
... |
further arguments passed to or from other methods. |
For argument method the following specifications are possible:
"ols"Inital values are equal to estimates from an unrestricted LS regression.
"prior"Initial values are drawn from the prior. Not possible for uninformative priors.
In case method = "ols", the initial draw of is the result of
the unrestricted LS regression of the model
, where is the matrix of regressors in
SUR form and is the vector of endogenous variables.
The initial draw of is the sum of squared
residuals divided by the number of observations, i.e. ,
with as the residuals of the LS regression.
In case of a model with time varying parameters (TVP), the initial states are
obtained using the approach specified in argument method. The precisions
of the state equations start at the means of their gamma priors in case
method = "ols" and are drawn from those priors in case
method = "prior". So method = "ols" uses no random numbers, and a
seed set after add_initial_values fixes the posterior draws.
The object in object with the element initial added, a list of
starting values with
athe coefficients, an matrix, or
for TVP models, whose initial states and state precisions are held in
a_init and a_sigma_inv.
u_sigma_invfor error = "wishart", the inverse
error covariance matrix.
u_omega_invfor gamma priors, the diagonal matrix of
error precisions.
h, h_init
for stochastic volatility, the
log-volatilities and their initial states.
psifor "gamma+covar" and "sv+covar", the error
covariance coefficients.
a_lambdawith variable selection, the inclusion indicators.
u_scale, w
for error = "ald", the scales
and the latent weights of the asymmetric Laplace distribution.
Elements that do not apply to a model are absent.
The function also stores the seed of the posterior simulation as element
seed of object$model, unless the model has one already. It is
drawn from R's random number generator, so set.seed() before this call
makes it reproducible. add_seed replaces it.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 50, burnin = 10) # Number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 50, burnin = 10) # Number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model)
Adds initial values to a VEC model, which was produced by
function create_bvecmodel in combination with add_priors.
## S3 method for class 'bvecmodel' add_initial_values(object, method = "maxlik", ...)## S3 method for class 'bvecmodel' add_initial_values(object, method = "maxlik", ...)
object |
list of class 'bvecmodel'. |
method |
character specifying the method of how initial values are generated.
Defaults is |
... |
further arguments passed to or from other methods. |
For argument method the following specifications are possible:
"maxlik"Inital values are equal to estimates from maximum likelihood regressions.
"prior"Initial values are drawn from the prior. Not possible for uninformative priors.
In case method = "maxlik", the initial draw of is the result of
a maximum likelihood estimation of the reduced rank model. When used with a
Wishart prior, the initial draw of is the sum of squared
residuals of ML regression divided by the number of observations, i.e.
. In all other cases, the diagonal elements of
are set to the variances of the variables in .
In case method = "prior", all initial draws in the model are random
draws from the respective prior distributions.
In case of a model with time varying parameters (TVP), the initial states are
obtained using the approach specified in argument method. The precisions
of the state equations start at the means of their gamma priors in case
method = "maxlik" and are drawn from those priors in case
method = "prior". The autocorrelation coefficient rho of
the state equation of is taken from the prior specification,
whether it is held there or drawn from the prior on it that
coint$rho_min and coint$rho_max set up.
The object in object with the element initial added, a list with
the starting values beta of the cointegration coefficients, a
matrix, or with initial state
beta_init for time varying cointegration, and the starting values of the
remaining coefficients and the error term with the elements described in
add_initial_values.bvarmodel.
The function also stores the seed of the posterior simulation as element
seed of object$model, unless the model has one already. It is
drawn from R's random number generator, so set.seed() before this call
makes it reproducible. add_seed replaces it.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model)# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model)
Adds initial values to a list of models by passing each element to the respective method.
## S3 method for class 'expandingwindow' add_initial_values(object, ...)## S3 method for class 'expandingwindow' add_initial_values(object, ...)
object |
a list of class 'expandingwindow', usually, the output of a call to
|
... |
further arguments passed to or from other methods. |
The object in object with initial values added to each of its models, as
described in add_initial_values.bvarmodel.
data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # AR(1) models as benchmark model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in draws should be much higher. # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = start_period) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1)) # Add initial values model <- add_initial_values(model)data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # AR(1) models as benchmark model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in draws should be much higher. # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = start_period) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1)) # Add initial values model <- add_initial_values(model)
Adds initial values to a list of models by passing each element to the respective method.
## S3 method for class 'modellist' add_initial_values(object, ...)## S3 method for class 'modellist' add_initial_values(object, ...)
object |
a list of class 'modellist' |
... |
further arguments passed to or from other methods. |
The object in object with initial values added to each of its models, as
described in add_initial_values.bvarmodel.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model)
Generic function used for posterior simulation of model coefficients.
add_posterior_coefficients(object, ...)add_posterior_coefficients(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
Before the method is called, the size the object will have once its
draws are complete is compared with options(bvartools.size_warning),
and a warning is given if it is larger. See expected_model_size.
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_posterior_coefficients.bvarmodel,
add_posterior_coefficients.bvecmodel,
add_posterior_coefficients.expandingwindow,
add_posterior_coefficients.externalforecast,
add_posterior_coefficients.modellist.
Forwards model input to posterior simulation functions for vector autoregressive models.
## S3 method for class 'bvarmodel' add_posterior_coefficients( object, posterior_function = NULL, chains = NULL, ... )## S3 method for class 'bvarmodel' add_posterior_coefficients( object, posterior_function = NULL, chains = NULL, ... )
object |
an object of class 'bvarmodel', usually, a result of a
call to |
posterior_function |
the function to be applied to the model in argument |
chains |
the number of chains to simulate. If |
... |
further arguments passed to or from other methods. |
Unless posterior_function is specified, the function forwards
the model input to the package's own posterior functions.
The internal samplers draw with the seed in object$model$seed, which
add_initial_values sets and add_seed replaces.
R's random number generator is set to that seed, with R's default kinds, for
the simulation and put back as it was afterwards. A call of set.seed()
between add_initial_values() and this function therefore does not
change the draws. A model without a seed draws from R's generator as it
stands. A posterior_function is called as it is and decides itself
what to do with the seed; see bayests_posterior.
A sampler that cannot run raises its error rather than returning something. The message names what about the input it could not work with. Applied to a list of models – a 'modellist', an 'expandingwindow' or, in bgvars, a 'gvarmodel' – that ends the run on the first specification that fails, rather than leaving that one without a posterior and carrying it into whatever reads the results.
The object in object with the element posterior added. Each of its
elements is a list whose element coeffs holds the draws after burn-in as a
mcmc object with one row per draw and one column per parameter:
athe coefficients, columns or for TVP models, in the
order of the columns of data$train$z with the contemporaneous coefficients
of structural models last. With variable selection element lambda holds the
inclusion indicators, and for TVP models element sigma the state variances.
u_sigma_invthe inverse error covariance matrix, columns, or
if the error variances vary over time.
u_omega_invfor all errors but "wishart", the error precisions,
columns or .
psifor "gamma+covar" and "sv+covar", the error covariance
coefficients.
u_scalefor error = "ald", the scales of the asymmetric
Laplace distribution.
yfor a model estimated from a panel not observed whole, the completed
panel, columns ordered by period, and constraints_inv the error
precisions of its soft constraints. See create_bvarmodel.
muunder a steady-state prior, the unconditional means. Under an
adaptive prior, a holds the scales of its groups in element shrinkage
and, for the horseshoe and the normal-gamma prior, the scales of its coefficients
in local; where the normal-gamma prior draws , its draws are in
theta. See
add_prior_options.
Elements that do not apply to a model are absent or NULL. Note that
bvar expects draws in the transposed orientation.
bvartools_model describes the object this returns, element by element.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model)
Forwards model input to posterior simulation functions for vector error correction models.
## S3 method for class 'bvecmodel' add_posterior_coefficients( object, posterior_function = NULL, chains = NULL, ... )## S3 method for class 'bvecmodel' add_posterior_coefficients( object, posterior_function = NULL, chains = NULL, ... )
object |
an object of class 'bvecmodel', usually, a result of a
call to |
posterior_function |
the function to be applied to the model in argument |
chains |
the number of chains to simulate. If |
... |
further arguments passed to or from other methods. |
The function implements commonly used posterior simulation algorithms for Bayesian VAR models with both constant and time varying parameters (TVP) as well as stochastic volatility. It can produce posterior draws for standard BVAR models with independent normal-Wishart priors, which can be augmented by stochastic search variable selection (SSVS) as proposed by Geroge et al. (2008) or Bayesian variable selection (BVS) as proposed in Korobilis (2013). Both SSVS or BVS can also be applied to the covariances of the error term.
The implementation follows the descriptions in Chan et al. (2019), George et al. (2008) and Korobilis (2013). For all approaches the SUR form of a VAR model is used to obtain posterior draws. The algorithm is implemented in C++ to reduce calculation time.
The function also supports structural BVEC models, where the structural coefficients are estimated from contemporary endogenous variables, which corresponds to the so-called (A-model). Currently, only specifications are supported, where the structural matrix contains ones on its diagonal and all lower triangular elements are freely estimated. Since posterior draws are obtained based on the SUR form of the VEC model, the structural coefficients are drawn jointly with the other coefficients.
The internal samplers draw with the seed in object$model$seed, which
add_initial_values sets and add_seed replaces.
R's random number generator is set to that seed, with R's default kinds, for
the simulation and put back as it was afterwards. A call of set.seed()
between add_initial_values() and this function therefore does not
change the draws. A model without a seed draws from R's generator as it
stands. A posterior_function is called as it is and decides itself
what to do with the seed; see bayests_posterior.
A sampler that cannot run raises its error rather than returning something. The message names what about the input it could not work with. Applied to a list of models – a 'modellist', an 'expandingwindow' or, in bgvars, a 'gvecmodel' – that ends the run on the first specification that fails, rather than leaving that one without a posterior and carrying it into whatever reads the results.
The object in object with the element posterior added, whose
elements hold the draws after burn-in as mcmc objects with one
row per draw and one column per parameter, in element coeffs: beta, the
cointegration coefficients, columns or for time
varying cointegration, a, the loadings and the remaining coefficients, and the
draws of the error term as described in add_posterior_coefficients.bvarmodel.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior simulation for cointegrated models with priors on the cointegration space. Econometric Reviews, 29(2), 224–242. doi:10.1080/07474930903382208
Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271
bvartools_model describes the object this returns, element by element.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model)# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model)
Forwards model input to posterior simulation functions.
## S3 method for class 'expandingwindow' add_posterior_coefficients(object, ..., cores = 1)## S3 method for class 'expandingwindow' add_posterior_coefficients(object, ..., cores = 1)
object |
an object of class 'expandingwindow'. |
... |
further arguments passed to or from other methods. |
cores |
the number of worker processes the models are simulated on. Defaults to 1, which simulates them one after the other in this session. See section 'Parallel simulation'. |
The object in object with posterior draws added to each of its models, as
described in add_posterior_coefficients.bvarmodel.
With cores above 1 the models are simulated on a cluster of that many
worker processes, started with makeCluster and
stopped when the call returns, but on no more workers than there are models.
Nested lists, such as the 'modellist' of 'expandingwindow' lists that
use_expanding_window returns for several specifications, are
shared out model by model.
Each worker runs with a single BLAS thread: the function sets
OPENBLAS_NUM_THREADS, OMP_NUM_THREADS, MKL_NUM_THREADS
and VECLIB_MAXIMUM_THREADS to 1 while the workers start, whatever
this session has set, and puts them back afterwards. An optimised BLAS would
otherwise start one thread per core in every worker, and the samplers do not
become faster with more threads. The thread count of this session is not
changed.
The workers use the library paths of this session and load the installed
version of the package, together with every package that provides a method
the models of the list need – dfmtools for its dynamic factor models,
for example. A function passed as posterior_function,
such as the one bayests_posterior returns, is sent to the
workers along with the variables of the environment it was created in, and
must not rely on anything else of this session.
Coefficient draws do not depend on the number of workers. Every model is
simulated with its own seed, see add_seed, and a model
without one is given one from R's random number generator before it is sent
off. The draws equal those of a simulation on one core in a session whose
BLAS runs on one thread, as R's reference BLAS always does. An optimised
BLAS such as OpenBLAS rounds some results differently in the last digits on
one thread than on several, and a Markov chain carries such a difference
forward, so a session running it on several threads gets different draws
from the same posterior. Draws that are not seeded per model, such as those of
add_posterior_forecasts, come from independent random number
streams of the workers, set up with
clusterSetRNGStream from R's generator. They are
reproduced by set.seed for a given number of workers, but
differ from those of a simulation on one core.
Starting the workers takes a moment, so a cluster pays off for lists of models that take longer than that to simulate.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 10, burnin = 2) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 10, burnin = 2) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model)
Forwards model input to posterior simulation functions.
## S3 method for class 'modellist' add_posterior_coefficients(object, ..., cores = 1)## S3 method for class 'modellist' add_posterior_coefficients(object, ..., cores = 1)
object |
an object of class 'modellist'. |
... |
further arguments passed to or from other methods. |
cores |
the number of worker processes the models are simulated on. Defaults to 1, which simulates them one after the other in this session. See section 'Parallel simulation'. |
The object in object with posterior draws added to each of its models, as
described in add_posterior_coefficients.bvarmodel.
With cores above 1 the models are simulated on a cluster of that many
worker processes, started with makeCluster and
stopped when the call returns, but on no more workers than there are models.
Nested lists, such as the 'modellist' of 'expandingwindow' lists that
use_expanding_window returns for several specifications, are
shared out model by model.
Each worker runs with a single BLAS thread: the function sets
OPENBLAS_NUM_THREADS, OMP_NUM_THREADS, MKL_NUM_THREADS
and VECLIB_MAXIMUM_THREADS to 1 while the workers start, whatever
this session has set, and puts them back afterwards. An optimised BLAS would
otherwise start one thread per core in every worker, and the samplers do not
become faster with more threads. The thread count of this session is not
changed.
The workers use the library paths of this session and load the installed
version of the package, together with every package that provides a method
the models of the list need – dfmtools for its dynamic factor models,
for example. A function passed as posterior_function,
such as the one bayests_posterior returns, is sent to the
workers along with the variables of the environment it was created in, and
must not rely on anything else of this session.
Coefficient draws do not depend on the number of workers. Every model is
simulated with its own seed, see add_seed, and a model
without one is given one from R's random number generator before it is sent
off. The draws equal those of a simulation on one core in a session whose
BLAS runs on one thread, as R's reference BLAS always does. An optimised
BLAS such as OpenBLAS rounds some results differently in the last digits on
one thread than on several, and a Markov chain carries such a difference
forward, so a session running it on several threads gets different draws
from the same posterior. Draws that are not seeded per model, such as those of
add_posterior_forecasts, come from independent random number
streams of the workers, set up with
clusterSetRNGStream from R's generator. They are
reproduced by set.seed for a given number of workers, but
differ from those of a simulation on one core.
Starting the workers takes a moment, so a cluster pays off for lists of models that take longer than that to simulate.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(e1, p = 1:2, deterministic = 2, iterations = 20, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # The same on two worker processes model <- add_posterior_coefficients(model, cores = 2)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(e1, p = 1:2, deterministic = 2, iterations = 20, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # The same on two worker processes model <- add_posterior_coefficients(model, cores = 2)
Generic function that calculates and adds forecasts.
add_posterior_forecasts(object, ...)add_posterior_forecasts(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_posterior_forecasts.bvarmodel,
add_posterior_forecasts.expandingwindow,
add_posterior_forecasts.externalforecast,
add_posterior_forecasts.modellist.
Calculates and adds forecasts to an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' add_posterior_forecasts( object, forecast_states = NULL, scenario = NULL, forecast_quantile = NULL, ... )## S3 method for class 'bvarmodel' add_posterior_forecasts( object, forecast_states = NULL, scenario = NULL, forecast_quantile = NULL, ... )
object |
an object of class 'bvarmodel', usually, the result of a call
to |
forecast_states |
character, what a model with time varying coefficients or
stochastic volatility does with them over the forecast horizon. |
scenario |
an optional data frame with columns |
forecast_quantile |
for a grid of quantiles (see |
... |
arguments passed forward to method. |
The object in object with posterior$forecast$forecasts added, a
mcmc object with one row per draw and columns, stacked by
period: the variables of the first forecast period, then those of the second,
and so on. posterior$forecast is the group everything the forecast periods
produce hangs below, the errors of add_forecast_errors beside
these. predict summarises them. A
forecast_states that was given is stored in model$forecast_states.
Simulating the volatility forward needs the variance of the log-volatility
innovations, posterior$u_sigma_inv$sigma, which add_posterior_coefficients
stores. A stochastic volatility model fitted with an earlier version of the package
lacks it and stops with an error unless forecast_states = "hold".
Chavleishvili, S., & Manganelli, S. (2019). Forecasting and stress testing with quantile vector autoregression. ECB Working Paper, 2330.
bvartools_model describes the object this returns, element by element.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model)
Simulates forecasts of a VEC model, in levels, from its posterior draws.
## S3 method for class 'bvecmodel' add_posterior_forecasts(object, forecast_states = NULL, ...)## S3 method for class 'bvecmodel' add_posterior_forecasts(object, forecast_states = NULL, ...)
object |
an object of class 'bvecmodel', usually, the result of a call to
|
forecast_states |
character, what a VEC model with time varying coefficients or
stochastic volatility does with them over the forecast horizon. |
... |
further arguments passed to or from other methods. |
The forecasts are those of the VAR in levels the VEC model implies. For a model
with constant coefficients they are the forecasts vec_to_var followed by
add_posterior_forecasts.bvarmodel gives. For a model with time varying
coefficients they are not: its VAR representation has no state equation of its own and
holds its coefficients at the last period, while this method steps the states of the VEC
model and converts them to levels anew in every forecast period.
Simulating the cointegration vectors forward depends on the units of the data. A step
of their state equation moves the error correction term by
, which for series far from zero – log levels times 100,
say – is of the order of their levels rather than of their variation: the random
walk intercept described in section 'Prior on the cointegration space' of
cointspace_prior, carried forward with nothing in the data to restrain
it. The forecast is then mostly that drift, and its intervals widen accordingly.
A warning names the series in the error correction term that are more than 50
times their standard deviation per period away from zero at the end of the sample;
forecast_states = "hold" is the alternative. Series near zero, such as
interest rates and inflation in percent, do not draw it.
A time varying model estimated on series that scale_error_correction
centred or scaled cannot be simulated forward and stops with an error unless
forecast_states = "hold": the state equation of its cointegration vectors
belongs to the transformed series, while rescale_error_correction
has put the vectors back on the scale of the data and moved the means into the
constant of the last sample period only.
Simulating the volatility forward needs posterior$u_sigma_inv$sigma, the variance
of the log-volatility innovations, which add_posterior_coefficients
stores. A model with stochastic volatility estimated with an earlier version of the
package lacks it and stops with an error unless forecast_states = "hold".
The object in object with posterior$forecast$forecasts added, a
mcmc object with one row per draw and columns of forecasts
of the levels, stacked by period. predict summarises them. A
forecast_states that was given is stored in model$forecast_states.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
Calculates and adds forecasts to the elements of an object of class 'expandingwindow'.
## S3 method for class 'expandingwindow' add_posterior_forecasts(object, ..., cores = 1)## S3 method for class 'expandingwindow' add_posterior_forecasts(object, ..., cores = 1)
object |
an object of class 'expandingwindow', usually, the result of a call
to |
... |
arguments passed forward to method. |
cores |
the number of worker processes the models are simulated on. Defaults to 1, which simulates them one after the other in this session. See section 'Parallel simulation'. |
The object in object with forecast draws added to each of its models, as
described in add_posterior_forecasts.bvarmodel.
With cores above 1 the models are simulated on a cluster of that many
worker processes, started with makeCluster and
stopped when the call returns, but on no more workers than there are models.
Nested lists, such as the 'modellist' of 'expandingwindow' lists that
use_expanding_window returns for several specifications, are
shared out model by model.
Each worker runs with a single BLAS thread: the function sets
OPENBLAS_NUM_THREADS, OMP_NUM_THREADS, MKL_NUM_THREADS
and VECLIB_MAXIMUM_THREADS to 1 while the workers start, whatever
this session has set, and puts them back afterwards. An optimised BLAS would
otherwise start one thread per core in every worker, and the samplers do not
become faster with more threads. The thread count of this session is not
changed.
The workers use the library paths of this session and load the installed
version of the package, together with every package that provides a method
the models of the list need – dfmtools for its dynamic factor models,
for example. A function passed as posterior_function,
such as the one bayests_posterior returns, is sent to the
workers along with the variables of the environment it was created in, and
must not rely on anything else of this session.
Coefficient draws do not depend on the number of workers. Every model is
simulated with its own seed, see add_seed, and a model
without one is given one from R's random number generator before it is sent
off. The draws equal those of a simulation on one core in a session whose
BLAS runs on one thread, as R's reference BLAS always does. An optimised
BLAS such as OpenBLAS rounds some results differently in the last digits on
one thread than on several, and a Markov chain carries such a difference
forward, so a session running it on several threads gets different draws
from the same posterior. Draws that are not seeded per model, such as those of
add_posterior_forecasts, come from independent random number
streams of the workers, set up with
clusterSetRNGStream from R's generator. They are
reproduced by set.seed for a given number of workers, but
differ from those of a simulation on one core.
Starting the workers takes a moment, so a cluster pays off for lists of models that take longer than that to simulate.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 10, burnin = 2) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 10, burnin = 2) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model)
Calculates and adds forecasts to the elements of an object of class 'modellist'.
## S3 method for class 'modellist' add_posterior_forecasts(object, ..., cores = 1)## S3 method for class 'modellist' add_posterior_forecasts(object, ..., cores = 1)
object |
an object of class 'modellist', usually, the result of a call
to |
... |
arguments passed forward to method. |
cores |
the number of worker processes the models are simulated on. Defaults to 1, which simulates them one after the other in this session. See section 'Parallel simulation'. |
The object in object with forecast draws added to each of its models, as
described in add_posterior_forecasts.bvarmodel.
With cores above 1 the models are simulated on a cluster of that many
worker processes, started with makeCluster and
stopped when the call returns, but on no more workers than there are models.
Nested lists, such as the 'modellist' of 'expandingwindow' lists that
use_expanding_window returns for several specifications, are
shared out model by model.
Each worker runs with a single BLAS thread: the function sets
OPENBLAS_NUM_THREADS, OMP_NUM_THREADS, MKL_NUM_THREADS
and VECLIB_MAXIMUM_THREADS to 1 while the workers start, whatever
this session has set, and puts them back afterwards. An optimised BLAS would
otherwise start one thread per core in every worker, and the samplers do not
become faster with more threads. The thread count of this session is not
changed.
The workers use the library paths of this session and load the installed
version of the package, together with every package that provides a method
the models of the list need – dfmtools for its dynamic factor models,
for example. A function passed as posterior_function,
such as the one bayests_posterior returns, is sent to the
workers along with the variables of the environment it was created in, and
must not rely on anything else of this session.
Coefficient draws do not depend on the number of workers. Every model is
simulated with its own seed, see add_seed, and a model
without one is given one from R's random number generator before it is sent
off. The draws equal those of a simulation on one core in a session whose
BLAS runs on one thread, as R's reference BLAS always does. An optimised
BLAS such as OpenBLAS rounds some results differently in the last digits on
one thread than on several, and a Markov chain carries such a difference
forward, so a session running it on several threads gets different draws
from the same posterior. Draws that are not seeded per model, such as those of
add_posterior_forecasts, come from independent random number
streams of the workers, set up with
clusterSetRNGStream from R's generator. They are
reproduced by set.seed for a given number of workers, but
differ from those of a simulation on one core.
Starting the workers takes a moment, so a cluster pays off for lists of models that take longer than that to simulate.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model)
Generic function that calculates the posterior log-likelihoods of a model.
add_posterior_loglik(object, ...)add_posterior_loglik(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_posterior_loglik.bvarmodel,
add_posterior_loglik.bvecmodel,
add_posterior_loglik.expandingwindow,
add_posterior_loglik.externalforecast,
add_posterior_loglik.modellist.
Calculates and adds posterior log-likelihoods to an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' add_posterior_loglik(object, ...)## S3 method for class 'bvarmodel' add_posterior_loglik(object, ...)
object |
an object of class 'bvarmodel', usually, the result of a call to
|
... |
additional arguments. |
The object in object with posterior$loglik added, a
mcmc object with one row per draw and one column per period of the
training sample, holding the pointwise log-likelihood that
selection_criteria uses.
bvartools_model describes the object this returns, element by element.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Add log-likelihoods object <- add_posterior_loglik(object)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Add log-likelihoods object <- add_posterior_loglik(object)
Calculates and adds posterior log-likelihoods to an object of class 'bvecmodel'.
## S3 method for class 'bvecmodel' add_posterior_loglik(object, ...)## S3 method for class 'bvecmodel' add_posterior_loglik(object, ...)
object |
an object of class 'bvecmodel', usually, the result of a call to
|
... |
additional arguments. |
The object in object with posterior$loglik added, a
mcmc object with one row per draw and one column per period of the
training sample, holding the pointwise log-likelihood that
selection_criteria uses.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add log-likelihoods model <- add_posterior_loglik(model)# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add log-likelihoods model <- add_posterior_loglik(model)
Forwards its elements to methods used to calculate posterior log-likelihoods.
## S3 method for class 'expandingwindow' add_posterior_loglik(object, ..., cores = 1)## S3 method for class 'expandingwindow' add_posterior_loglik(object, ..., cores = 1)
object |
an object of class 'expandingwindow', usually, the result of a call to
|
... |
further arguments passed to or from other methods. |
cores |
the number of worker processes the models are simulated on. Defaults to 1, which simulates them one after the other in this session. See section 'Parallel simulation'. |
The object in object with log-likelihood draws added to each of its models, as
described in add_posterior_loglik.bvarmodel.
With cores above 1 the models are simulated on a cluster of that many
worker processes, started with makeCluster and
stopped when the call returns, but on no more workers than there are models.
Nested lists, such as the 'modellist' of 'expandingwindow' lists that
use_expanding_window returns for several specifications, are
shared out model by model.
Each worker runs with a single BLAS thread: the function sets
OPENBLAS_NUM_THREADS, OMP_NUM_THREADS, MKL_NUM_THREADS
and VECLIB_MAXIMUM_THREADS to 1 while the workers start, whatever
this session has set, and puts them back afterwards. An optimised BLAS would
otherwise start one thread per core in every worker, and the samplers do not
become faster with more threads. The thread count of this session is not
changed.
The workers use the library paths of this session and load the installed
version of the package, together with every package that provides a method
the models of the list need – dfmtools for its dynamic factor models,
for example. A function passed as posterior_function,
such as the one bayests_posterior returns, is sent to the
workers along with the variables of the environment it was created in, and
must not rely on anything else of this session.
Coefficient draws do not depend on the number of workers. Every model is
simulated with its own seed, see add_seed, and a model
without one is given one from R's random number generator before it is sent
off. The draws equal those of a simulation on one core in a session whose
BLAS runs on one thread, as R's reference BLAS always does. An optimised
BLAS such as OpenBLAS rounds some results differently in the last digits on
one thread than on several, and a Markov chain carries such a difference
forward, so a session running it on several threads gets different draws
from the same posterior. Draws that are not seeded per model, such as those of
add_posterior_forecasts, come from independent random number
streams of the workers, set up with
clusterSetRNGStream from R's generator. They are
reproduced by set.seed for a given number of workers, but
differ from those of a simulation on one core.
Starting the workers takes a moment, so a cluster pays off for lists of models that take longer than that to simulate.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add log-likelihoods model <- add_posterior_loglik(model)# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add log-likelihoods model <- add_posterior_loglik(model)
Forwards its elements to methods used to calculate posterior log-likelihoods.
## S3 method for class 'modellist' add_posterior_loglik(object, ..., cores = 1)## S3 method for class 'modellist' add_posterior_loglik(object, ..., cores = 1)
object |
a list of class 'modellist', usually, the result of a call to
|
... |
further arguments passed to or from other methods. |
cores |
the number of worker processes the models are simulated on. Defaults to 1, which simulates them one after the other in this session. See section 'Parallel simulation'. |
The object in object with log-likelihood draws added to each of its models, as
described in add_posterior_loglik.bvarmodel.
With cores above 1 the models are simulated on a cluster of that many
worker processes, started with makeCluster and
stopped when the call returns, but on no more workers than there are models.
Nested lists, such as the 'modellist' of 'expandingwindow' lists that
use_expanding_window returns for several specifications, are
shared out model by model.
Each worker runs with a single BLAS thread: the function sets
OPENBLAS_NUM_THREADS, OMP_NUM_THREADS, MKL_NUM_THREADS
and VECLIB_MAXIMUM_THREADS to 1 while the workers start, whatever
this session has set, and puts them back afterwards. An optimised BLAS would
otherwise start one thread per core in every worker, and the samplers do not
become faster with more threads. The thread count of this session is not
changed.
The workers use the library paths of this session and load the installed
version of the package, together with every package that provides a method
the models of the list need – dfmtools for its dynamic factor models,
for example. A function passed as posterior_function,
such as the one bayests_posterior returns, is sent to the
workers along with the variables of the environment it was created in, and
must not rely on anything else of this session.
Coefficient draws do not depend on the number of workers. Every model is
simulated with its own seed, see add_seed, and a model
without one is given one from R's random number generator before it is sent
off. The draws equal those of a simulation on one core in a session whose
BLAS runs on one thread, as R's reference BLAS always does. An optimised
BLAS such as OpenBLAS rounds some results differently in the last digits on
one thread than on several, and a Markov chain carries such a difference
forward, so a session running it on several threads gets different draws
from the same posterior. Draws that are not seeded per model, such as those of
add_posterior_forecasts, come from independent random number
streams of the workers, set up with
clusterSetRNGStream from R's generator. They are
reproduced by set.seed for a given number of workers, but
differ from those of a simulation on one core.
Starting the workers takes a moment, so a cluster pays off for lists of models that take longer than that to simulate.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(e1, p = 1:2, deterministic = 2, iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Add log-likelihoods object <- add_posterior_loglik(object)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(e1, p = 1:2, deterministic = 2, iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Add log-likelihoods object <- add_posterior_loglik(object)
Adds the draws of the one-step-ahead log predictive density to the windows of
an expanding window exercise, which selection_criteria sums to
the log predictive likelihood.
add_predictive_loglik(object, ...) ## S3 method for class 'expandingwindow' add_predictive_loglik(object, ...) ## S3 method for class 'modellist' add_predictive_loglik(object, ...)add_predictive_loglik(object, ...) ## S3 method for class 'expandingwindow' add_predictive_loglik(object, ...) ## S3 method for class 'modellist' add_predictive_loglik(object, ...)
object |
an object of class |
... |
further arguments passed to or from other methods. |
The windows of an expanding window exercise grow by one period at a time, so
window holds exactly one observation that window has not
seen. For every window but the last, the function evaluates the density of
that observation, , given the regressors of period ,
at each posterior draw of the window, and stores the draws in element
predictive of the window, together with the period . The log of
their mean is the log predictive density , and its sum over the windows is the log predictive likelihood
of Geweke and Amisano (2011), which Koop, León-González and Strachan (2011)
use to choose between time varying cointegration models and their ranks.
A draw of a model with constant coefficients and a constant error covariance
describes period as it describes the sample. Everything that follows
a state equation is carried one period forward with that equation first:
time varying coefficients by one step of their random walk with the drawn state variance, and a coefficient that variable selection excluded stays at zero;
a time varying cointegration space by
,
, with the drawn or the one of the prior,
where is the identity unless the prior centres the space;
time varying error covariances by one step of their random walk;
stochastic volatilities by one step of the random walk of the log
variances. Its state variance is taken from posterior$u_sigma_inv$sigma
if the sampler stored it, and is otherwise drawn from its conditional
posterior given the drawn path of the log variances and the prior in
priors$u_sigma.
Unlike the pointwise log-likelihood of add_posterior_loglik,
whose states have seen the observation they are evaluated at, the predictive
density conditions only on the data before period . This is what makes
it the criterion for models whose coefficients or variances follow a state
equation, where leave-one-out importance sampling fails for exactly the
periods a path bends towards.
The function is available for VEC models, which includes the rank zero
models in differences that ranks are compared with, and for VAR models, whose
regressors are the lags of the endogenous variables, the exogenous variables
and the deterministic terms of the period that is predicted. A VAR model is
the case of a VEC model without an error correction term, so the density is
the same expression with the cointegration block left out. The windows of a
VEC model must have been simulated on error correction terms that are neither
scaled nor centred, or put back with
rescale_error_correction first, and structural models are not
supported.
The windows need not share their regressors. use_expanding_window
leaves an impulse, step or data dummy of add_dummy_variables out
of the windows that end before its event, so the window just before the event
has fewer regressors than the observation the next window adds. The density
of that observation uses only the regressors of the window that predicts it:
the regressors of the observation are matched to the ones of the window by
name, and a dummy the window does not have is left out, because a forecast
made at the end of the window could not have known about the event. The
event period is therefore scored as an ordinary forecast, and the dummy only
enters the densities of the windows that contain its event. This applies to
VAR and VEC models alike.
The expression is the normal density of the observation, so the function is
available for the algorithms whose observation is normal given the parameters
of a draw, and refuses the others. The asymmetric Laplace algorithms of
quantile estimation, "VarNormalAld" and "VarTvpAld", are
refused: the precision their samplers store is the one of the normal that
their scale mixture conditions on period by period, not the density of an
observation, whose mixing variable would have to be integrated out.
The methods for a single fitted model, add_predictive_loglik.bvarmodel
and add_predictive_loglik.bvecmodel, score a forecast against
the observations its horizon realised instead. That is the same statistic over
a different set of periods – one step ahead densities, each conditioning on
the realised history before it – and it is BayesTS that computes it rather
than the R code here. It is stored in posterior$forecast$loglik, beside
the forecasts it scores, rather than in predictive.
The object in object, with element predictive added to
every window but the last. It is a list with loglik, the draws of the
log predictive density, and period, the time of the predicted
observation.
Geweke, J., & Amisano, G. (2011). Hierarchical Markov normal mixture models with applications to financial asset returns. Journal of Applied Econometrics, 26(1), 1–29. doi:10.1002/jae.1119
Koop, G., León-González, R., & Strachan, R. W. (2011). Bayesian inference in a time varying cointegration model. Journal of Econometrics, 165(2), 210–220. doi:10.1016/j.jeconom.2011.07.007
Methods for a single fitted model:
add_predictive_loglik.bvarmodel,
add_predictive_loglik.bvecmodel.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e6") e6 <- e6 * 100 # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 0.0001)) # Estimate the model on the last four expanding windows model <- use_expanding_window(model, start = c(1998, 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) # One-step-ahead log predictive densities model <- add_predictive_loglik(model) # The log predictive likelihood is criterion "LPL" selection_criteria(model)# Load data data("e6") e6 <- e6 * 100 # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 0.0001)) # Estimate the model on the last four expanding windows model <- use_expanding_window(model, start = c(1998, 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) # One-step-ahead log predictive densities model <- add_predictive_loglik(model) # The log predictive likelihood is criterion "LPL" selection_criteria(model)
Scores the forecast of an object of class 'bvarmodel' against the observations its horizon realised.
## S3 method for class 'bvarmodel' add_predictive_loglik(object, test_sample = NULL, ...)## S3 method for class 'bvarmodel' add_predictive_loglik(object, test_sample = NULL, ...)
object |
an object of class 'bvarmodel', usually, the result of a call to
|
test_sample |
a time-series object used as test data. If |
... |
further arguments passed to or from other methods. |
The draws of the log predictive density of period are stored in
posterior$forecast$loglik, one row per draw and one column per scored
period, beside the paths in posterior$forecast$forecasts that they
score. The numbers are BayesTS's own: this method fills data$test$y
and hands the object to the same C++ that computes the score when the
bayests programme is run on a model file.
Each column conditions on the observations the periods before it realised,
not on the path the forecast simulated. The log of the mean of the draws of a
column is therefore the one step ahead predictive density given everything
known up to that period, and those sum over the columns to
, the log
predictive likelihood of the whole realised stretch, which
selection_criteria reports as LPL. Scoring against a
simulated history instead would give the marginal density of each period on
its own, which is a different quantity and one whose columns could not be
added up.
With the history realised rather than simulated, the regressors of the scored
periods do not depend on the draw. The score is then the model's own pointwise
log-likelihood over those periods – the same expression as
add_posterior_loglik evaluates, over a different sample – so
nothing is written down twice and the two cannot drift apart. What still moves
with the draw is everything that follows a state equation: time varying
coefficients, time varying error covariances and stochastic volatilities take
one step of their random walk per scored period, in the order and subject to
the same model$forecast_states that add_posterior_forecasts
steps them in. Under "simulate" those steps are drawn, so the score is
drawn too and two runs give two answers, exactly as two runs of a forecast do.
Fewer realised periods than the horizon is not an error. The periods that are
there are the ones that can be scored, and the rest of the forecast is left
alone. A test_sample that does not reach the forecast at all leaves the
object unchanged, which is what a model estimated to the end of a series looks
like.
Structural models are refused: their regressors include the contemporaneous
observations, so the realised row is not built from its lags alone, and their
density carries the Jacobian of besides. So are the asymmetric
Laplace algorithms of quantile estimation, which do not forecast in the first
place.
The object in object with posterior$forecast$loglik
added, a mcmc object with one row per draw and one column
per scored period, and with the values it was scored against in
data$test$y.
bvartools_model describes the object this returns, element by element.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1978, 4)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) # Forecast the four periods that were held back model <- add_forecast_input(model, n_ahead = 4) model <- add_posterior_forecasts(model) # Score them against what those periods realised model <- add_predictive_loglik(model, test_sample = orig) dim(model[["posterior"]][["forecast"]][["loglik"]]) # The log predictive likelihood is criterion "LPL" selection_criteria(model)[["LPL"]]# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1978, 4)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) # Forecast the four periods that were held back model <- add_forecast_input(model, n_ahead = 4) model <- add_posterior_forecasts(model) # Score them against what those periods realised model <- add_predictive_loglik(model, test_sample = orig) dim(model[["posterior"]][["forecast"]][["loglik"]]) # The log predictive likelihood is criterion "LPL" selection_criteria(model)[["LPL"]]
Scores the forecast of an object of class 'bvecmodel' against the levels its horizon realised.
## S3 method for class 'bvecmodel' add_predictive_loglik(object, test_sample = NULL, ...)## S3 method for class 'bvecmodel' add_predictive_loglik(object, test_sample = NULL, ...)
object |
an object of class 'bvecmodel', usually, the result of a call to
|
test_sample |
a time-series object of the endogenous variables, in
levels, that covers the forecast periods. If |
... |
further arguments passed to or from other methods. |
The forecasts of a VEC model are of the levels, so the score is of the levels
too, and it is taken in the VAR representation vec_to_var would
give: every draw is converted to its level VAR coefficients and the realised
row is evaluated against the lags of the realised rows before it. That is the
same route add_forecast_errors.bvecmodel takes and the same one
the forecast itself took, so the three describe one model rather than three.
Everything else is as add_predictive_loglik.bvarmodel describes
it, including what each column conditions on and how a cointegration space or
a volatility that moves with time is carried across the horizon. A model whose
error correction term was scaled or centred has to be put back with
rescale_error_correction first, since the score is taken against
the levels themselves.
The object in object with posterior$forecast$loglik
added, a mcmc object with one row per draw and one column
per scored period, and with the levels it was scored against in
data$test$y.
bvartools_model describes the object this returns, element by element.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e6") e6 <- e6 * 100 train <- window(e6, end = c(1997, 4)) # Create model model <- create_bvecmodel(train, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 0.0001)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) # Forecast the periods that were held back and score them model <- add_forecast_input(model, n_ahead = 4) model <- add_posterior_forecasts(model) model <- add_predictive_loglik(model, test_sample = e6) dim(model[["posterior"]][["forecast"]][["loglik"]])# Load data data("e6") e6 <- e6 * 100 train <- window(e6, end = c(1997, 4)) # Create model model <- create_bvecmodel(train, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 0.0001)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) # Forecast the periods that were held back and score them model <- add_forecast_input(model, n_ahead = 4) model <- add_posterior_forecasts(model) model <- add_predictive_loglik(model, test_sample = e6) dim(model[["posterior"]][["forecast"]][["loglik"]])
Adds the options of the prior that act on top of the one
add_priors sets: hyperparameters estimated from the data, a
restriction of the coefficients to a stationary model, a prior on the
unconditional mean in place of one on the intercept, and the prior of the
error of soft constraints.
add_prior_options( object, shrinkage = "none", stationary = FALSE, steady_state = NULL, constraints = NULL )add_prior_options( object, shrinkage = "none", stationary = FALSE, steady_state = NULL, constraints = NULL )
object |
an object of class 'bvarmodel' or 'modellist', usually the
result of |
shrinkage |
a character, |
stationary |
logical. If |
steady_state |
an optional list with elements |
constraints |
an optional list with elements |
Argument shrinkage lets the data decide how tightly the prior
of add_priors shrinks the coefficients of the lagged endogenous
variables. Their prior variances are multiplied by scales that are drawn with
the coefficients:
"minnesota": one scale per group of coefficients with an inverse
gamma prior of shape and rate, the hierarchical Minnesota prior
of Chan (2021). By default own lags form group 1 and the lags of the other
variables group 2, with shape = 3 and rate = 2, a prior mean of
one: the prior of add_priors is the centre of the one estimated.
"horseshoe": the horseshoe prior of Carvalho, Polson and Scott
(2010), a half-Cauchy scale per group and one per coefficient, drawn as in
Makalic and Schmidt (2016). By default all lags form one group.
"normal_gamma": the normal-gamma prior of Griffin and Brown
(2010) as Huber and Feldkircher (2019) put it on a VAR. Each coefficient's
scale has a gamma prior of shape theta and rate
, and each group's a gamma
prior of shape and rate. By default the lags of order
form group , with theta = 0.1 and
shape = rate = 0.01. theta is held fixed; the smaller it is,
the more the prior pushes small coefficients to zero while leaving large
ones alone. Give theta_rate instead to draw under an
exponential prior of that rate, by a Metropolis-Hastings step tuned during
the burn-in, as Huber and Feldkircher (2019) do; the draws come back as
posterior$a$theta, and the chain needs a burn-in to tune the step.
Coefficients in group 0 – by default the deterministic terms and the
exogenous variables – keep the prior of add_priors. A group of
one's own has one element per coefficient, in the order of the columns of
data$train$z. The prior must be diagonal wherever it shrinks.
Argument stationary redraws a draw of the coefficients that is not
stationary up to 100 times, and keeps the previous draw if none of them is,
which leaves the posterior restricted to the stationary region invariant.
Argument steady_state puts the prior on the unconditional mean
of the endogenous variables rather than on the intercept, which is
in every draw, following Villani (2009). A prior
belief about the level a series returns to is more often available than one
about an intercept. The model must have lags and an intercept and nothing
else, and cannot be combined with shrinkage. The draws of
come back as posterior$mu.
The three are available for models with constant coefficients and
error = "wishart", "gamma", "gamma+covar", "sv" or
"sv+covar", without variable selection or a structural form.
The object in object with model$shrinkage,
model$stationary and model$steady_state set where they apply, and
the priors in priors$a$shrinkage, priors$mu and
priors$constraints.
Carvalho, C. M., Polson, N. G., & Scott, J. G. (2010). The horseshoe estimator for sparse signals. Biometrika, 97(2), 465–480. doi:10.1093/biomet/asq017
Griffin, J. E., & Brown, P. J. (2010). Inference with normal-gamma prior distributions in regression problems. Bayesian Analysis, 5(1), 171–188. doi:10.1214/10-BA507
Huber, F., & Feldkircher, M. (2019). Adaptive shrinkage in Bayesian vector autoregressive models. Journal of Business & Economic Statistics, 37(1), 27–39. doi:10.1080/07350015.2016.1256217
Chan, J. C. C. (2021). Minnesota-type adaptive hierarchical priors for large Bayesian VARs. International Journal of Forecasting, 37(3), 1212–1226. doi:10.1016/j.ijforecast.2021.01.002
Makalic, E., & Schmidt, D. F. (2016). A simple sampler for the horseshoe estimator. IEEE Signal Processing Letters, 23(1), 179–182. doi:10.1109/LSP.2015.2503725
Villani, M. (2009). Steady-state priors for vector autoregressions. Journal of Applied Econometrics, 24(4), 630–650. doi:10.1002/jae.1065
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, iterations = 20, burnin = 10) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_prior_options(model, shrinkage = "minnesota", stationary = TRUE) model <- add_initial_values(model) model <- add_posterior_coefficients(model)data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, iterations = 20, burnin = 10) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_prior_options(model, shrinkage = "minnesota", stationary = TRUE) model <- add_initial_values(model) model <- add_posterior_coefficients(model)
A generic function used to generate prior vectors and matrices. The function invokes particular methods which depend on the class of the first argument.
add_priors(object, ...)add_priors(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_priors.bvarmodel,
add_priors.bvecmodel, add_priors.expandingwindow,
add_priors.externalforecast, add_priors.modellist.
Adds prior specifications to a BVAR model, which was produced by
function create_bvarmodel.
## S3 method for class 'bvarmodel' add_priors(object, coef, sigma, varsel = NULL, ...)## S3 method for class 'bvarmodel' add_priors(object, coef, sigma, varsel = NULL, ...)
object |
a list of class 'bvarmodel'. |
coef |
a named list of prior specifications for the coefficients. It has
no default and must contain at least |
sigma |
a named list of prior specifications for the error term. It has
no default, and the elements it must contain depend on argument |
varsel |
a named list of prior specifications for the variable
selection algorithm. Required if the model was created with
|
... |
further arguments passed to or from other methods. |
None of the arguments coef, sigma and varsel
provides default hyperparameters: every value that a model needs must be given
in the list it belongs to. A missing required element raises an error, as does
an element that is not listed below.
Argument coef can contain the following elements:
v_ia non-negative numeric specifying the prior precision of the coefficients,
where 0 gives an uninformative prior. Required unless minnesota is given. It is also
required together with minnesota if error is "gamma+covar" or
"sv+covar", where it sets the prior precision of the error covariance coefficients.
The precisions of the other coefficients are taken from minnesota if it is given,
and from varsel for SSVS.
v_i_deta numeric specifying the prior precision of coefficients
corresponding to deterministic terms. If it is not given, v_i is used.
Not used if minnesota is given or SSVS is applied.
coint_vara logical specifying whether the prior mean of the first own lag of an
endogenous variable should be set to 1, which is commonly used for cointegrated
VAR models. Default is FALSE. Ignored, with a warning, under SSVS, which centres the
prior of every coefficient it selects at zero; BVS keeps the prior mean.
consta numeric or character specifying the prior mean of coefficients, which correspond
to the intercept. If a numeric is provided, all prior means are set to this value.
If coef$const = "mean", the mean of the respective endogenous variable is used as prior mean.
If coef$const = "first", the first values of the respective endogenous variable is used as prior mean.
This can be useful for trend estimation when using a TVP model.
minnesotaa named list containing the parameters for the calculation of
the Minnesota prior. It must contain kappa1, kappa2 and kappa4, and
kappa3 if the model has exogenous variables.
For the endogenous variable the prior variance of the th lag of regressor is obtained as
where is the residual standard deviation of variable of an unrestricted
LS estimate. For exogenous variables is the sample standard deviation.
If the model does not contain exogenous variables, kappa3 will be ignored.
max_vara positive numeric specifying the maximum prior variance of the
coefficients of non-deterministic variables in the Minnesota prior. Larger prior variances
are set to this value. Only used if minnesota is given.
shapea numeric specifying the shape of the gamma prior on the precisions, the
inverse error variances, of the state equation, whose mean is shape / rate. Required for
models with time varying parameters unless omega_v is given, and not used otherwise.
ratea numeric specifying the rate of the gamma prior on the precisions of the
state equation. Required together with shape.
rate_deta numeric specifying the prior rate parameter of the error variances of the
state equation for coefficients, which correspond to deterministic terms. If it is not given,
rate is used. Only used for models with time varying parameters.
omega_va positive numeric, in place of shape and rate: the
variance of a normal prior on the signed standard deviation of the state
innovations, , which is also the prior mean of the state
variance . This is the non-centred parameterisation of
Frühwirth-Schnatter and Wagner (2010), which makes a constant coefficient an interior point
of the prior and lets the posterior carry the Savage-Dickey test for time variation of
Chan (2018); see Details. It applies to the covariance coefficients as well. Only for
models with time varying parameters, tvp = TRUE, whatever their error.
Argument sigma must contain the elements that belong to the
error of the model:
"wishart": df and scale. Not available for structural models.
"gamma" and "gamma+covar": shape and rate.
"sv" and "sv+covar": mu, v_i, shape, rate,
state_variance and offset; with tvp = TRUE, omega_v may take the
place of shape and rate.
"ald": shape and rate.
The elements are
dfa positive integer, or a character expression in k, the number of
endogenous variables, such as "k" or "k + 3", specifying the prior degrees of
freedom of the inverse Wishart prior.
scalea positive numeric specifying the prior error variance of the endogenous variables in the inverse Wishart prior.
shapefor "gamma" and "gamma+covar" a non-negative numeric, or a
character expression in k as for df, specifying the shape of the gamma prior on
the error precisions, the inverse error variances, whose mean is shape / rate. For
"ald" a positive numeric specifying the shape of the inverse gamma prior on the scale of
the asymmetric Laplace distribution. For both either one value or one per endogenous variable.
For models with stochastic volatility a numeric specifying the shape of the gamma prior on the
precision of the state equation of the log-volatilities.
ratea positive numeric specifying the rate that corresponds to shape,
for "gamma", "gamma+covar" and "ald" either one value or one per
endogenous variable.
munumeric of the prior mean of the initial state of the log-volatilities. Only used for models with time varying volatility.
v_inumeric of the prior precision of the initial state of the log-volatilities. Only used for models with time varying volatility.
state_variancenumeric of the initial draw for the variance of the log-volatilities. Only used for models with time varying volatility.
offsetnumeric of the constant, which is added before taking the log of the squared errors. Only used for models with time varying volatility.
omega_va positive numeric, in place of shape and rate: the variance
of a normal prior on the signed standard deviation of the log-volatility innovations, as
coef$omega_v is for the coefficients. Only for models with time varying parameters and
stochastic volatility.
Under omega_v a random walk , ,
is estimated as with a standard random
walk. The hypothesis that does not move is then , a point inside the
prior, and its Bayes factor is the Savage-Dickey density ratio
, which a single run of the time varying model estimates
(Chan 2018). Each block of the posterior estimated this way holds, beside sigma, the
draws of in omega, and the log density at zero of its conditional
posterior, per state in omega_log_zero and for the whole block in
omega_log_zero_joint. The log Bayes factor in favour of time variation in state
is less the log of the average over the draws of
exp(omega_log_zero[, i]). The joint one compares "every state of the block moves" with
"none does" rather than "at least one moves". Each block chooses its prior for itself, so the
volatilities can be tested while the coefficients keep shape and rate.
For structural models only a gamma prior or stochastic volatility specification is allowed.
Argument varsel can contain the following elements:
inpriora numeric between 0 and 1 specifying the prior probability of a variable to be included in the model.
covarlogical indicating if the variable selection algorithm should also be applied to the error covariance matrix.
exclude_detlogical indicating if deterministic terms should be excluded from the variable selection algorithm.
minnesotaa numeric vector of length 4 containing parameters for the calculation of the Minnesota-like inclusion priors. See below.
taua numeric vector of two elements containing the prior standard errors
of restricted variables () as its first element and unrestricted variables ()
as its second. Only used for SSVS.
semiautomatican numeric vector of two elements containing the
factors by which the standard errors associated with an unconstrained least squares
estimate of the model are multiplied to obtain the prior standard errors
of restricted () and unrestricted () variables, respectively.
This is the semiautomatic approach described in George et al. (2008). Only used for SSVS.
In the case of SSVS, either tau or semiautomatic must be specified.
If varsel$minnesota is specified, prior
inclusion probabilities are calculated in a Minnesota-like fashion as
|
for own lags of endogenous variables, |
|
for other endogenous variables, |
|
for exogenous variables, |
|
for contemporaneous endogenous variables of a structural model, |
|
for deterministic variables, |
for lag with , , ,
as the first, second, third and forth element in
varsel$minnesota, respectively.
The object in object with the element priors added, a list with
athe prior of the coefficients: type, the
prior means mu and the prior precision matrix
v_inv, where is the number of coefficients. With variable selection
also inprior and include, for SSVS tau0 and tau1, and
for TVP models shape and rate of the state variances, or omega_v.
psifor error = "gamma+covar" or "sv+covar", the prior of
the error covariance coefficients with type, mu, v_inv and
varsel, and the variable selection and state variance elements as for
a.
u_sigmathe prior of the error variances with its type:
"wishart" with df and scale, "gamma" with shape
and rate, or "sv" with mu, v_inv, shape,
rate (or omega_v), sigma and offset. With a Minnesota prior it also holds
u_sigma_inv, the inverse error covariance matrix the prior was scaled with.
Not present for error = "ald".
u_scalefor error = "ald", the prior of the scales of the
asymmetric Laplace distribution with type, shape and rate.
Chan, J. C. C. (2018). Specification tests for time-varying parameter models with stochastic volatility. Econometric Reviews, 37(8), 807–823. doi:10.1080/07474938.2016.1167948
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
Frühwirth-Schnatter, S., & Wagner, H. (2010). Stochastic model specification search for Gaussian and partial non-Gaussian state space models. Journal of Econometrics, 154(1), 85–100. doi:10.1016/j.jeconom.2009.07.003
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burn-in should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1))# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burn-in should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1))
Adds prior specifications to a list of models, which was produced by
function create_bvecmodel.
## S3 method for class 'bvecmodel' add_priors(object, coef, coint = NULL, sigma, varsel = NULL, ...)## S3 method for class 'bvecmodel' add_priors(object, coef, coint = NULL, sigma, varsel = NULL, ...)
object |
a list of class 'bvecmodel'. |
coef |
a named list of prior specifications for coefficients that do not
determine the cointegration space. It has no default and must contain at least
|
coint |
a named list of prior specifications for coefficients determining the cointegration space of VEC models. It has no default and is required for a positive cointegration rank. A model of rank zero has no cointegration space and needs none; one that is given is checked and ignored, so that a list of models over several ranks can share the same arguments. See 'Details'. |
sigma |
a named list of prior specifications for the error term. It has
no default, and the elements it must contain depend on argument |
varsel |
a named list of prior specifications for the variable
selection algorithm. Required if the model was created with
|
... |
further arguments passed to or from other methods. |
None of the arguments coef, coint, sigma and
varsel provides default hyperparameters: every value that a model needs
must be given in the list it belongs to. A missing required element raises an
error, as does an element that is not listed below.
Argument coef can contain the following elements:
v_ia non-negative numeric specifying the prior precision of the coefficients,
where 0 gives an uninformative prior. Required unless minnesota is given. It is also
required together with minnesota if error is "gamma+covar" or
"sv+covar". The precisions of the other coefficients are taken from minnesota
if it is given, and from varsel for SSVS.
v_i_deta numeric specifying the prior precision of coefficients
corresponding to deterministic terms. If it is not given, v_i is used.
Not used if minnesota is given or SSVS is applied.
consta numeric or character specifying the prior mean of coefficients, which correspond
to the intercept. If a numeric is provided, all prior means are set to this value.
If coef$const = "mean", the mean of the respective endogenous variable is used as prior mean.
If coef$const = "first", the first values of the respective endogenous variable is used as prior mean.
minnesotaa named list containing the parameters for the calculation of
the Minnesota prior. It must contain kappa1, kappa2 and kappa4, and
kappa3 if the model has exogenous variables.
For the endogenous variable the prior variance of the th lag of regressor is obtained as
where is the residual standard deviation of variable of an unrestricted
LS estimate. For exogenous variables is the sample standard deviation.
If the model does not contain exogenous variables, kappa3 will be ignored.
The function only provides priors for the non-cointegration part of the model. However,
the residual standard errors are based on an unrestricted LS regression of the
endogenous variables on the error correction term and the non-cointegration regressors.
max_vara positive numeric specifying the maximum prior variance of the
coefficients of non-deterministic variables in the Minnesota prior. Larger prior variances
are set to this value. Only used if minnesota is given.
shapea numeric specifying the shape of the gamma prior on the precisions, the
inverse error variances, of the state equation, whose mean is shape / rate. Required for
models with time varying parameters and not used otherwise.
ratea numeric specifying the rate of the gamma prior on the precisions of the state equation. Required for models with time varying parameters and not used otherwise.
rate_deta numeric specifying the prior rate parameter of the error variances of the
state equation for coefficients, which correspond to deterministic terms. If it is not given,
rate is used. Only used for models with time varying parameters.
rate_alphaa numeric specifying the rate of the gamma prior on the precisions of
the state equation of the loadings. If it is not given, rate is used. Only used for
models with time varying parameters and a positive rank. The loadings multiply the levels in
the error correction term, so a drift that is negligible for a coefficient on a differenced
regressor moves the fitted value by much more; a rate several orders of magnitude below
rate keeps their drift from absorbing the residuals while the other coefficients vary.
It does not reach the steps of the cointegration vectors, which can absorb the residuals as
well; see section 'Prior on the cointegration space'.
omega_va positive numeric, in place of shape, rate,
rate_det and rate_alpha: the variance of a normal prior on the signed standard
deviation of the state innovations of the coefficients, loadings included unless
omega_v_alpha is given, and of the
covariance coefficients – the non-centred parameterisation that lets the posterior carry
the test for time variation of time_variation_test; see
add_priors.bvarmodel for the model and the draws it adds. The cointegration
space keeps its state equation. Only for models with time varying parameters,
tvp = TRUE, whatever their error.
omega_v_alphaa positive numeric, the omega_v of the loadings, as
rate_alpha is their rate under the centred prior. If it is not given,
omega_v is used. The loadings multiply the levels in the error correction term, so
a standard deviation of their innovations that is small for a coefficient on a differenced
regressor moves the fitted value by much more, and the test for time variation of
time_variation_test compares each loading's posterior at zero with its own
prior: a prior on the wrong scale makes the Bayes factor of a loading say more about the
prior than about the loading. Only used with omega_v and a positive rank.
Argument coint specifies the prior on the cointegration space. Its
elements, and the priors they give, are described in section 'Prior on the
cointegration space' below, which is shared with cointspace_prior.
Argument sigma must contain the elements that belong to the
error of the model:
"wishart": df and scale. Not available for structural models.
"gamma" and "gamma+covar": shape and rate.
"sv" and "sv+covar": mu, v_i, shape, rate,
state_variance and offset; with tvp = TRUE, omega_v may take the
place of shape and rate, as coef$omega_v does for the coefficients.
The elements are
dfa positive integer, or a character expression in k, the number of
endogenous variables, such as "k" or "k + 3", specifying the prior degrees of
freedom of the inverse Wishart prior. The samplers add the rank of the cointegration
matrix to the posterior degrees of freedom, as the prior of the loadings requires.
scalea positive numeric specifying the prior error variance of the endogenous variables in the inverse Wishart prior.
shapefor "gamma" and "gamma+covar" a non-negative numeric, or a
character expression in k as for df, specifying the shape of the gamma prior on
the error precisions, the inverse error variances, whose mean is shape / rate, either one
value or one per endogenous variable. For models with stochastic volatility a numeric
specifying the shape of the gamma prior on the precision of the state equation of the
log-volatilities.
ratea positive numeric specifying the rate that corresponds to shape,
for "gamma" and "gamma+covar" either one value or one per endogenous variable.
munumeric of the prior mean of the initial state of the log-volatilities. Only used for models with time varying volatility.
v_inumeric of the prior precision of the initial state of the log-volatilities. Only used for models with time varying volatility.
state_variancenumeric of the initial draw for the variance of the log-volatilities. Only used for models with time varying volatility.
offsetnumeric of the constant, which is added before taking the log of the squared errors. Only used for models with time varying volatility.
For structural models only a gamma prior or stochastic volatility specification is allowed.
Argument varsel can contain the following elements:
inpriora numeric between 0 and 1 specifying the prior probability of a variable to be included in the model.
covarlogical indicating if the variable selection algorithm should also be applied to the error covariance matrix.
exclude_detlogical indicating if deterministic terms should be excluded from the variable selection algorithm.
minnesotaa numeric vector of length 4 containing parameters for the calculation of the Minnesota-like inclusion priors. See below.
taua numeric vector of two elements containing the prior standard errors
of restricted variables () as its first element and unrestricted variables ()
as its second. Only used for SSVS.
semiautomatican numeric vector of two elements containing the
factors by which the standard errors associated with an unconstrained least squares
estimate of the model are multiplied to obtain the prior standard errors
of restricted () and unrestricted () variables, respectively.
This is the semiautomatic approach described in George et al. (2008). Only used for SSVS.
In the case of SSVS, either tau or semiautomatic must be specified.
If varsel$minnesota is specified, prior
inclusion probabilities are calculated in a Minnesota-like fashion as
|
for own lags of endogenous variables, |
|
for other endogenous variables, |
|
for exogenous variables, |
|
for contemporaneous endogenous variables of a structural model, |
|
for deterministic variables, |
for lag with , , ,
as the first, second, third and forth element in
varsel$minnesota, respectively.
The object in object with the element priors added, a list with
betathe prior of the cointegration space with type
"cointspace": v_inv and p_tau_inv for constant cointegration
parameters, with g_inv if coint$g_i was given, or rho, mu and v_inv of the state equation for time
varying ones, together with the elements added by p_tau_i = "ml" or a
uniform prior on .
athe prior of the loadings and the remaining coefficients, with the
same elements as for a VAR model in add_priors.bvarmodel.
psi, u_sigma
the priors of the error covariance coefficients and error variances, as for a VAR model.
Argument coint can contain the following elements. Which of them are
required depends on whether the cointegration vectors are constant or time
varying, since the two are given different kinds of prior: a matric-variate
prior on the cointegration space in the first case, and a state equation in
the second. Any other element raises an error.
v_inon-negative numeric specifying the shrinkage of the cointegration space prior,
or "ml". See below. Required for models with constant cointegration parameters and not
used otherwise.
p_tau_ithe inverse of the matrix , which determines the
central location of the cointegration space . Either a numeric of
its diagonal elements, a full symmetric matrix, or "ml", with one row and
column per series in the error correction term data$train$w. See below.
Required for models with constant cointegration parameters. For models with time
varying cointegration parameters only "ml" is used.
weightpositive numeric specifying the weight of a prior centred on the
maximum likelihood estimate in units of the information of the sample. Default is 1.
Only used if p_tau_i = "ml".
rhoa numeric specifying the autocorrelation coefficient
of the state equation of . It must be smaller than 1.
Required for models with time varying cointegration parameters and not used otherwise.
If rho_min and rho_max are given as well, this is the value the
chain starts at rather than the value it keeps, and it must lie
between them.
rho_min, rho_max
numerics specifying the support of a
uniform prior on , which makes it a drawn parameter rather than a
fixed hyperparameter. Optional, and either both or neither; they must
satisfy rho_minrho_max.
Koop et al. (2011) use .
Only used for models with time varying cointegration parameters.
g_ithe inverse of the matrix that scales the prior of the
loadings, for models with constant cointegration parameters and stochastic volatility,
error = "sv" or "sv+covar", and refused for every other model. Either a
numeric of its diagonal elements, a full symmetric positive definite matrix with one row
and column per endogenous variable, or "ml" for the inverse of the maximum
likelihood estimate of the error covariance. Optional. See below.
For a model with constant cointegration parameters the prior is that of
Koop et al. (2010). The sampler uses v_i and p_tau_i only through
their product, so with v_i = 0 the prior on the cointegration space is
uniform whatever p_tau_i is. An informative prior on the space
therefore needs a positive v_i, which also shrinks the loadings: for
close to the centre of the space they have prior
.
In Koop et al. (2010) the loadings' prior is scaled by a matrix , which
may be the error covariance or any fixed, known matrix. The models
with a constant error covariance take . With stochastic
volatility the covariance differs from period to period, so is fixed
for the whole run instead: is g_i if it is given, and
otherwise the error precision implied by the starting values of the
log-volatilities, averaged over the sample once before the first draw. That
fallback depends on add_initial_values, so giving g_i
makes the prior independent of how the chain is started. g_i = "ml"
uses Johansen's (1995) estimate of the error covariance, the same one
v_i = "ml" is based on.
With p_tau_i = "ml" the prior is centred on the space spanned by
Johansen's (1995) maximum likelihood estimate , computed from
the error correction term as it is stored in the model – so call
scale_error_correction first if the series should be scaled;
scaling is refused afterwards.
Let be an orthonormal basis of that space, one of its
orthogonal complement and . The matrix
where is the cross product of the residuals of a regression of the
error correction term on the short-run regressors and is weight,
makes the prior of given
.
This is the asymptotic distribution of the maximum likelihood estimator
with its precision multiplied by : weight = 1 adds as much
information about the space as the sample itself holds. Since the centre is
estimated from the same sample, the posterior then overstates the precision
of . Eigenvalues of are capped at one, which is the
uniform prior.
With v_i = "ml" the shrinkage is chosen so that the prior mean of
is 100 times its maximum
likelihood estimate. It can be combined with a numeric p_tau_i.
For a model with time varying cointegration parameters the state equation is
with , and
the prior on the state before the sample is that equation's own stationary
distribution, . This is what makes the prior
proper, so a close to one is intended and one further from it draws
a warning. add_priors gives the loadings the compensating scale:
only the product is identified, so their prior
variance is shrunk by , leaving the product on the scale
coef$v_i asks for.
When is drawn, those last two are computed from coint$rho
once and do not follow the draw: the state before the sample keeps the normal
prior built here, and the loadings keep the shrinkage of
add_priors. This is a deliberate departure from Koop et al.
(2011), in whom the state before the sample is the stationary distribution of
whatever currently is. It is also what makes the draw an exact
Gibbs block rather than their Metropolis-within-Gibbs step: with the state
before the sample free of , the conditional posterior of
is a normal truncated to the prior's support. Draws of are
returned in object$posterior$beta$rho.
How far the space moves is not set by the prior on any variance. The steps
have unit variance whatever coef$rate and
coef$rate_alpha are, and how far a step moves
depends on the scale of .
Only the product is identified, so the posterior can pair small loadings with
large cointegration vectors, which a unit step barely turns, or large loadings
with small ones, which it turns a lot. Two things decide which. One is the
prior precision of the loadings, coef$v_i , which
restrains the drift only if it is tight relative to the scale of the
data call for, and that scale depends on the units of the data. The other is
the series in the error correction term: a step moves
by , which grows with the
levels of the series and not only with their variation. For log levels far
from zero the shift is of the order of the levels themselves, and the sampler
either lets it act as a random walk intercept, which no prior on the
deterministic terms controls and which can absorb the residuals of an
equation, or draws loadings close to zero, which switches the error
correction term off.
Both have been seen. In the US sub-model of the bgvars data set
gvar2023, with the oil price among its endogenous variables and a rank
of one, a prior that pinned the state variances of all coefficients, the
loadings and the constant included, at 1e-14 still left the residual standard
deviation of one equation as low as 0.1 to 0.5 of the maximum likelihood one
in some chains, with which equation and how low depending on the chain, and a
saved chain reported a posterior mean log-likelihood several hundred above the
maximum of the constant coefficient model. The chains do not move between
these outcomes within a few thousand draws, so a single chain can report any
of them. The Austrian sub-model under the same prior lost fit that the
constant coefficient model has, and the chains that were inspected drew
loadings close to zero. On data simulated from a constant coefficient VEC
model, whose posterior under such a prior should reproduce the maximum
likelihood fit, single chains did so only with the series centred and
coef$v_i = 10, or around zero and coef$v_i = 100. Around 12,
where log levels usually are, a chain drew loadings close to zero, and around
zero with coef$v_i = 1 one fitted part of the residuals.
The same mechanism makes scale_error_correction risky in a model
whose coefficients vary over time. It divides the series by the standard
deviation of their differences, which makes them, and with them both a drift
in a loading and a step of , larger by the same
factor. The coefficient paths can then absorb the residuals of an equation
almost entirely: its residual variance – or, under stochastic volatility, its
volatility path – is reported far below that of a least squares fit of the
same regressors and nearly constant over the sample. In the model of the
vignette on time varying parameters and stochastic volatility in error
correction models, vignette("tvp-sv-vec", package = "bvartools"), a
scaled error correction term did that to one equation in each of four chains
with different seeds, and the unscaled one with a small coef$rate in
none.
It is safer to leave the series unscaled, to set coef$v_i with the
scale of in mind as well as choosing small rates, and to compare the
residual variances with those of a least squares fit of the same regressors,
in chains with different seeds, for a model that is to be used. Small rates
alone do not guarantee that a model passes that check, and passing it is what
says that neither the coefficients nor the cointegration vectors fit the
residuals. scale_error_correction(object, scale = FALSE, centre = TRUE)
centres the series before posterior simulation, which removes the part of a
step of that comes from the levels of the series
rather than from their variation, and rescale_error_correction
writes the draws back in terms of the series as they are, so that
vec_to_var and the forecasts can use them. It does not reach the
other channel, the scale of the loadings, and it is not a full remedy: in the
US sub-model above, centring alone roughly halved how far the error correction
term and the constant moved over the sample and still left the oil price
equation at about 0.8 of the maximum likelihood residual standard deviation in
two chains. Whether a centred model is right is again what the comparison with
least squares shows.
For a model with time varying cointegration parameters
p_tau_i = "ml" centres the marginal prior of the
cointegration space on Johansen's estimate as well, using the informative
marginal prior of Koop et al. (2011, working paper version). The state
equation becomes
with
: the part of
along keeps , the part off it decays
faster, and the mode of the marginal distribution of is
in every period. is chosen so that the prior spread of the
tilt of away from in a period, approximately
, is the sampling variance of
Johansen's estimator with its precision multiplied by weight. The
state before the sample is given the stationary distribution the transition
implies. The transition is stored as element p_tau.
limits how informative this prior can be: even leaves
the tilt a spread of per period, and a weight asking
for more is floored there with a warning.
A larger weight does not always give a tighter posterior. It narrows
the prior spread of the tilt in each period by lowering , but
is also how much of the tilt carries over from one period to the next. As
approaches zero the tilt of each period becomes independent of the
last, the data of neighbouring periods stop informing it, and the posterior
spread of can widen again. On data set E6 with
, for example, weight = 1, which gives
, produced a tighter posterior than weight = 100,
which reaches . The useful range of weight is the one that
keeps clearly above zero, and a closer to one widens it.
A weight so small that
would be the identity in every direction leaves the noninformative
prior unchanged. Both and the prior on the state before the
sample are computed at coint$rho, and do not follow the draw if
is drawn. coint$v_i has no counterpart for these models.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
Johansen, S. (1995). Likelihood-based inference in cointegrated vector autoregressive models. Oxford: Oxford University Press.
Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior simulation for cointegrated models with priors on the cointegration space. Econometric Reviews, 29(2), 224–242. doi:10.1080/07474930903382208
Koop, G., León-González, R., & Strachan R. W. (2011). Bayesian inference in a time varying cointegration model. Journal of Econometrics, 165(2), 210–220. doi:10.1016/j.jeconom.2011.07.007
Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # The same model with time varying parameters. The cointegration vectors are # then a state path rather than a draw from a cointegration space prior, so # 'coint' takes the autocorrelation of that path instead of its shrinkage and # central location, and 'coef' takes the prior of the state error variances. model <- create_bvecmodel(e6, p = 4, r = 1, tvp = TRUE, const = "unrestricted", seasonal = "unrestricted", iterations = 10, burnin = 10) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10, shape = 3, rate = 0.0001), coint = list(rho = 0.999), sigma = list(df = "k", scale = 1))# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # The same model with time varying parameters. The cointegration vectors are # then a state path rather than a draw from a cointegration space prior, so # 'coint' takes the autocorrelation of that path instead of its shrinkage and # central location, and 'coef' takes the prior of the state error variances. model <- create_bvecmodel(e6, p = 4, r = 1, tvp = TRUE, const = "unrestricted", seasonal = "unrestricted", iterations = 10, burnin = 10) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10, shape = 3, rate = 0.0001), coint = list(rho = 0.999), sigma = list(df = "k", scale = 1))
Adds prior specifications to a list of models by passing each element to the respective method.
## S3 method for class 'expandingwindow' add_priors(object, ...)## S3 method for class 'expandingwindow' add_priors(object, ...)
object |
a list of class 'expandingwindow', usually, the output of a call
to |
... |
further arguments passed to or from other methods. |
The object in object with priors added to each of its models, as
described in add_priors.bvarmodel.
data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # AR(1) models as benchmark model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 10) # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = start_period) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1))data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # AR(1) models as benchmark model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 10) # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = start_period) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1))
Adds prior specifications to a list of models by passing each element to the respective method.
## S3 method for class 'modellist' add_priors(object, ...)## S3 method for class 'modellist' add_priors(object, ...)
object |
a list of class 'modellist', usually, the output of a call
to |
... |
further arguments passed to or from other methods. |
The object in object with priors added to each of its models, as
described in add_priors.bvarmodel.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1))# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1))
Sets the seed with which the posterior of a model is simulated.
add_seed(object, seed, ...) ## S3 method for class 'bvarmodel' add_seed(object, seed, ...) ## S3 method for class 'bvecmodel' add_seed(object, seed, ...) ## S3 method for class 'modellist' add_seed(object, seed, ...) ## S3 method for class 'expandingwindow' add_seed(object, seed, ...)add_seed(object, seed, ...) ## S3 method for class 'bvarmodel' add_seed(object, seed, ...) ## S3 method for class 'bvecmodel' add_seed(object, seed, ...) ## S3 method for class 'modellist' add_seed(object, seed, ...) ## S3 method for class 'expandingwindow' add_seed(object, seed, ...)
object |
a model, at any point before the posterior is simulated: an
object of class 'bvarmodel' or 'bvecmodel', a model of another package that
provides an |
seed |
a non-negative whole number no larger than
|
... |
further arguments passed to or from other methods. |
Calling this function is optional. add_initial_values already
stores a seed, drawn from R's random number generator, in element seed
of object$model, unless the model has one. add_seed sets that
element, for example to give a model a seed that depends neither on the state
of R's generator nor on the worker of a cluster that happens to simulate it.
It can be called before add_initial_values, which then keeps the seed
it is given, or after it, which replaces the drawn one.
The seed is part of the model. write_to_hdf5 writes it as
attribute seed of group /model, where the BayesTS executable
reads it, and read_model_from_hdf5 reads it back. The internal
samplers of add_posterior_coefficients draw with it too, so a
model with a given seed gives the same draws however R's generator stands.
BayesTS and this package use different generators, so the same seed gives
different draws in the two.
A list of models gets the seeds seed, seed + 1, ..., one per
model in the order of its elements, counting through nested lists, so that no
two of its models draw the same numbers. A model is any element with an
add_seed method of its own, so the models of other packages that
provide one, such as the dynamic factor models of dfmtools, are
counted with the rest. Elements that are not estimated, such as external
forecasts, and elements without a method are left as they are and are not
counted.
object with the seed set.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(data = e1, p = 2, iterations = 100, burnin = 50) # Set the seed of the posterior simulation model <- add_seed(model, 20260916) model[["model"]][["seed"]]# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(data = e1, p = 2, iterations = 100, burnin = 50) # Set the seed of the posterior simulation model <- add_seed(model, 20260916) model[["model"]][["seed"]]
A generic function used to identify the shocks of a model by the signs of the impulse responses they produce.
add_sign_restrictions(object, ...)add_sign_restrictions(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_sign_restrictions.bvarmodel,
add_sign_restrictions.expandingwindow,
add_sign_restrictions.modellist.
Identifies the shocks of an object of class 'bvarmodel' by the signs of the impulse responses they produce.
## S3 method for class 'bvarmodel' add_sign_restrictions( object, restrictions, max_tries = 1000, period = NULL, ... ) ## S3 method for class 'expandingwindow' add_sign_restrictions(object, ...) ## S3 method for class 'modellist' add_sign_restrictions(object, ...)## S3 method for class 'bvarmodel' add_sign_restrictions( object, restrictions, max_tries = 1000, period = NULL, ... ) ## S3 method for class 'expandingwindow' add_sign_restrictions(object, ...) ## S3 method for class 'modellist' add_sign_restrictions(object, ...)
object |
an object of class 'bvarmodel', containing posterior draws of the coefficients and the error covariance. |
restrictions |
a data frame of the restrictions, with one row per restriction. See 'Details'. |
max_tries |
the number of rotations that are tried per posterior draw before the draw is given up on. Defaults to 1000. |
period |
integer. Index of the period, whose draws should be identified.
Only used for TVP or SV models. Default is |
... |
further arguments passed to or from other methods. |
The function identifies the structural shocks of the VAR model
with , by searching for rotations of its Choleski
factor whose impulse responses carry the signs that argument
restrictions asks for.
Write for the lower triangular Choleski factor of and
for an orthogonal matrix. Then for
every such , so a model rotated by fits the data exactly as
well as the one the posterior draw describes. The likelihood is therefore
silent about which rotation is the right one, and the restrictions choose
among the models it cannot tell apart. The identification is in consequence
set valued: what is obtained is not one impulse response per posterior
draw but the collection of those that the restrictions admit.
For every posterior draw the function draws rotations uniformly over the
orthogonal group and keeps the first one whose responses satisfy every
restriction. Since a sign restriction cannot distinguish a shock from its own
negative, a column that fails is retried with its sign flipped before the
rotation is discarded. A draw for which no admissible rotation is found
within max_tries attempts is dropped from the identified sample, and
summary reports how many were. A low acceptance rate is a
statement about the restrictions, not a technicality: it says the model
rarely produces the pattern that was asked of it.
Argument restrictions is a data frame with the columns
impulsename of the endogenous variable the shock is named after.
responsename of the endogenous variable whose response is restricted.
signeither 1 for a response that must be positive or
-1 for one that must be negative.
horizonoptional integer of the horizon the restriction
applies to, counted from zero for the impact period. Defaults to 0.
Restrictions on several shocks may be combined in one data frame. A shock that no row mentions is left as it is drawn, since nothing in the restrictions distinguishes one rotation of it from another; only the restricted shocks should be interpreted.
Only sign restrictions are supported. A zero restriction cannot be imposed by
rejection, because the set of rotations that satisfies one has probability
zero, so no number of tries finds a member of it. Use
add_sign_zero_restrictions, which draws rotations that satisfy
the zero restrictions by construction and reweights them.
The accepted rotations are added to the object as element q of its
posterior draws, from where irf, fevd and
spillover use them under type = "sign".
The result depends on the state of the random number generator, so
set.seed is needed to reproduce it.
The object of class 'bvarmodel' with the accepted rotations in
element q of its posterior, one row per posterior draw, and the
specification of the restrictions in element sign_restrictions of its
model. Draws for which no admissible rotation was found are recorded
as NA.
Arias, J. E., Rubio-Ramirez, J. F., Waggoner, D. F. (2018). Inference based on structural vector autoregressions identified with sign and zero restrictions: Theory and applications. Econometrica, 86(2), 685-720. doi:10.3982/ECTA14468
Rubio-Ramirez, J. F., Waggoner, D. F., Zha, T. (2010). Structural vector autoregressions: Theory of identification and algorithms for inference. The Review of Economic Studies, 77(2), 665-696. doi:10.1111/j.1467-937X.2009.00578.x
Uhlig, H. (2005). What are the effects of monetary policy on output? Results from an agnostic identification procedure. Journal of Monetary Economics, 52(2), 381-419. doi:10.1016/j.jmoneco.2004.05.007
Other post-estimation analysis:
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # A demand shock raises investment and consumption on impact restrictions <- data.frame(impulse = "invest", response = c("invest", "cons"), sign = c(1, 1), horizon = 0) set.seed(1234) model <- add_sign_restrictions(model, restrictions) # Obtain the identified impulse response ir <- irf(model, impulse = "invest", response = "cons", type = "sign")# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # A demand shock raises investment and consumption on impact restrictions <- data.frame(impulse = "invest", response = c("invest", "cons"), sign = c(1, 1), horizon = 0) set.seed(1234) model <- add_sign_restrictions(model, restrictions) # Obtain the identified impulse response ir <- irf(model, impulse = "invest", response = "cons", type = "sign")
A generic function used to identify the shocks of a model by the signs of the impulse responses they produce and by responses that are restricted to be zero.
add_sign_zero_restrictions(object, ...)add_sign_zero_restrictions(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: add_sign_zero_restrictions.bvarmodel,
add_sign_zero_restrictions.expandingwindow,
add_sign_zero_restrictions.modellist.
Identifies the shocks of an object of class 'bvarmodel' by the signs of the impulse responses they produce together with responses that are restricted to be exactly zero.
## S3 method for class 'bvarmodel' add_sign_zero_restrictions( object, restrictions, draws = NULL, one_sided = FALSE, smooth = TRUE, period = NULL, max_tries = 1, ... ) ## S3 method for class 'expandingwindow' add_sign_zero_restrictions(object, ...) ## S3 method for class 'modellist' add_sign_zero_restrictions(object, ...)## S3 method for class 'bvarmodel' add_sign_zero_restrictions( object, restrictions, draws = NULL, one_sided = FALSE, smooth = TRUE, period = NULL, max_tries = 1, ... ) ## S3 method for class 'expandingwindow' add_sign_zero_restrictions(object, ...) ## S3 method for class 'modellist' add_sign_zero_restrictions(object, ...)
object |
an object of class 'bvarmodel', containing posterior draws of the coefficients and the error covariance. |
restrictions |
a data frame of the restrictions, with one row per restriction. See 'Details'. |
draws |
integer. The number of draws to resample. Defaults to
|
one_sided |
logical. Should the numerical derivative behind the
importance weights be taken on one side only? It is about forty percent
faster and correspondingly less accurate. Defaults to |
smooth |
logical. Should the importance weights be Pareto smoothed?
Defaults to |
period |
integer. Index of the period, whose draws should be identified.
Only used for TVP or SV models. Default is |
max_tries |
integer. The largest number of rotations drawn for each posterior draw. Defaults to 1, the algorithm of the paper. More tries find rotations where the sign restrictions leave a region too small for a single try to hit, and the importance weights account for them. See 'Details'. |
... |
further arguments passed to or from other methods. |
A sign restriction can be imposed by trying rotations until one of
them carries the signs that were asked for, which is what
add_sign_restrictions does. A zero restriction cannot: the
rotations that satisfy one form a set of probability zero, so no number of
tries finds a single member of it. This function uses the algorithms of
Arias, Rubio-Ramirez and Waggoner (2018) instead, and needs at least one zero
restriction to be worth using – with only signs, add_sign_restrictions
produces the same draws more cheaply, and this function says so rather than
running.
The restrictions are imposed on , the responses stacked over
the horizons the restrictions mention. That function satisfies
for every orthogonal , so a zero
restriction on the response to the th shock is a linear
restriction on the th column of once the reduced form is
fixed. The columns are therefore built one at a time, each drawn uniformly
from the sphere in the subspace that the zero restrictions and the columns
already placed leave over. Every rotation the function draws satisfies the
zero restrictions exactly rather than approximately.
That construction does not draw from the posterior conditional on the zero restrictions but from a distribution that differs from it by a volume element, which the function computes numerically and divides out. The result is an importance sample: each draw carries a weight, and the draws are resampled with replacement according to those weights so that what the function returns is an ordinary, equally weighted sample. A draw whose rotation fails the sign restrictions is given weight zero and so never resampled, and a shock is not retried with its sign flipped, since the sphere its column is drawn from already covers both of its signs.
By default each posterior draw gets one rotation, as in the paper.
With many sign restrictions that can leave nothing: when one rotation in
tens of thousands satisfies them all, a few thousand posterior draws produce
no admissible rotation, and the function stops. max_tries draws more
rotations per draw, but not the way add_sign_restrictions
does. Stopping at the first rotation that satisfies the signs would bias an
importance sampler: the single try is what weights each posterior draw by the
probability that its rotations satisfy the signs, and a draw whose
admissible set is tiny would count as much as one whose set is large.
Instead the rotations are drawn until two of them satisfy the signs, or
until max_tries have been drawn. The first of them is kept, and its
weight is multiplied by an unbiased estimate of from the tries
(Girshick, Mosteller and Savage, 1946): when the second
came at try , and when only one came in all
tries. The rotation kept does not depend on how many tries it took, so the
weight stays an unbiased estimate of the paper's and the sample stays exact.
The price is variance: an estimated spreads the weights, and the
effective sample size says by how much. Looking for the second success
also means drawing about twice the rotations a first success needs.
With more than one try a column whose sign restrictions all hold with the
opposite sign is also flipped rather than rejected. That is exact too: the
proposal does not change when a column changes sign, so the rotation kept
has the same distribution, and the probability that a try succeeds grows by
, the number of shocks carrying sign restrictions – the same
factor for every draw, which cancels when the weights are normalised. It
cuts the tries needed by that factor, 64 for six sign restricted shocks.
max_tries = 1 flips nothing: it is the paper's algorithm and draws
exactly what the function drew before the argument existed.
The draws that come back are a resample and no longer a chain.
Their order carries no information, several of them may be copies of the same
original draw, and convergence diagnostics computed on them mean nothing. How
much independent information they carry is the effective sample size, which
summary reports.
Argument restrictions is a data frame with the columns
impulsename of the endogenous variable the shock is named after.
responsename of the endogenous variable whose response is restricted.
sign1 for a response that must be positive, -1
for one that must be negative, and 0 for one restricted to be exactly
zero.
horizonoptional horizon the restriction applies to, counted
from zero for the impact period. Inf restricts the long-run response.
Defaults to 0.
The order of the endogenous variables matters here in a way it does
not for sign restrictions alone. Columns of are built in the order
the variables appear, and the th column has to keep at least one
dimension after the columns before it and its own zero
restrictions have been taken out. A shock carrying many zero restrictions
therefore has to be named early. The function refuses an ordering that leaves
a column with nothing to draw and says which shock it was.
The result depends on the state of the random number generator, so
set.seed is needed to reproduce it. It depends on it in two
places rather than one: the rotations are drawn at random, and so are the
matrices that complete each shock's constraints to a square system. Appendix
A.3 of the paper says any draw of the latter defines a valid algorithm, and
that is true – but not that any draw defines an equally efficient one.
Holding a model, its posterior draws and every rotation fixed, different
completions have moved the effective sample size by a factor of four. A run
reporting a poor effective sample size is therefore worth repeating under a
different seed before the restrictions themselves are blamed.
The weights are Pareto smoothed before they are used. Nothing in
the algorithm bounds the ratio of two volume elements, so a draw landing
where the proposal put almost no probability and the target a great deal
carries an enormous weight, the effective sample size collapses, and the
resample is a few copies of that one draw. Pareto smoothing, of Vehtari
et al. (2024), fits a generalised Pareto distribution to the largest few
weights and replaces them by its quantiles. On a model where the raw weights
gave an effective sample size of 4 out of 487 accepted draws, with one of
them holding 46 percent of the total weight, smoothing returned 138 and the
largest share fell to 6 percent; on the same model under three other seeds,
where nothing was wrong, it changed the effective sample size by less than
three percent either way. It buys that at the cost of a small bias, which is
the trade the paper argues for. smooth = FALSE takes the raw weights
of Algorithm 3 instead.
The shape of the fitted distribution is worth more than the
smoothing. It estimates how heavy the tail of the weights is, and so says
when the sample cannot be trusted rather than leaving that to be guessed
from an effective sample size: the estimator has a finite variance only for
below one half, and above about 0.7 neither it nor its effective
sample size means much. It is reported by summary and kept in
element pareto_k of sign_zero_restrictions.
The function warns when the importance sample is not fit to
summarise: when is 0.7 or above, when the effective sample size is
below twenty, so that the draws returned have no percentiles worth reading,
or when it keeps less than a quarter of the information in the draws that
satisfied the signs. The warning says which repair applies. A well-behaved
tail with a small effective sample size is an efficiency problem that more
candidate draws fix, since the effective sample size grows roughly in
proportion to them. A heavy tail is not fixed that way, because the trouble
is where the proposal put its probability rather than how much of it was
drawn; a different seed, a different variable ordering or weaker
restrictions are the things worth trying.
Applied to a 'modellist' or an 'expandingwindow' the function identifies
each member on its own and returns the collection. Each therefore gets its
own effective sample size, and unless draws is given the members come
back with different numbers of draws – which is what it means for one model,
or one window of the sample, to support the restrictions less well than
another. Pass draws to give them all the same number.
The object of class 'bvarmodel' with its posterior draws resampled,
the accepted rotations in element q of its posterior, one row
per resampled draw, and the specification of the restrictions in element
sign_zero_restrictions of its model, together with
max_tries, the number of rotations drawn in all (tries), the
number of draws that satisfied the sign restrictions, the effective sample size
of the importance sampler and the share of the total weight held by its
single largest draw, the shape pareto_k of the distribution fitted to
the tail of the weights and whether they were smoothed. Element
sign_restrictions is set alongside
it, so that irf, fevd and spillover
read the rotations under type = "sign" as they do for
add_sign_restrictions.
Arias, J. E., Rubio-Ramirez, J. F., Waggoner, D. F. (2018). Inference based on structural vector autoregressions identified with sign and zero restrictions: Theory and applications. Econometrica, 86(2), 685-720. doi:10.3982/ECTA14468
Girshick, M. A., Mosteller, F., Savage, L. J. (1946). Unbiased estimates for certain binomial sampling problems with applications. The Annals of Mathematical Statistics, 17(1), 13-23.
Rubio-Ramirez, J. F., Waggoner, D. F., Zha, T. (2010). Structural vector autoregressions: Theory of identification and algorithms for inference. The Review of Economic Studies, 77(2), 665-696. doi:10.1111/j.1467-937X.2009.00578.x
Vehtari, A., Simpson, D., Gelman, A., Yao, Y., Gabry, J. (2024). Pareto smoothed importance sampling. Journal of Machine Learning Research, 25(72), 1-58.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Consumption does not respond to the investment shock on impact, and income # rises. Investment is the first variable of the data set, which is what # leaves its shock a column to draw: see 'Details' on the ordering. restrictions <- data.frame(impulse = "invest", response = c("cons", "income"), sign = c(0, 1), horizon = 0) set.seed(1234) model <- add_sign_zero_restrictions(model, restrictions) # Obtain the identified impulse response ir <- irf(model, impulse = "invest", response = "income", type = "sign")# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Consumption does not respond to the investment shock on impact, and income # rises. Investment is the first variable of the data set, which is what # leaves its shock a column to draw: see 'Details' on the ordering. restrictions <- data.frame(impulse = "invest", response = c("cons", "income"), sign = c(0, 1), horizon = 0) set.seed(1234) model <- add_sign_zero_restrictions(model, restrictions) # Obtain the identified impulse response ir <- irf(model, impulse = "invest", response = "income", type = "sign")
Turns the forecast draws of models estimated on quarterly or monthly data into draws of the annual figures they imply, so that the models can be compared with annual forecasts, such as the projections of international institutions, on the same annual basis.
aggregate_forecasts(object, code, target = "average", levels = NULL, scale = 1)aggregate_forecasts(object, code, target = "average", levels = NULL, scale = 1)
object |
an object of class 'bvarmodel', 'bvecmodel', 'expandingwindow' or
'modellist', whose models contain forecasts, i.e. |
code |
a named integer vector of the transformation codes of FRED-MD and
FRED-QD, |
target |
either |
levels |
an optional time-series object with the untransformed series, to
which |
scale |
the factor, by which the transformed series of codes 4 to 7 were
multiplied before they were passed to the models, such as 100 for log
differences in percent. The default of 1 corresponds to the result of
|
Every draw of a forecast is turned back into a path of the untransformed series by reversing the transformation of its code, and continued from the periods, which were observed at the end of the training sample. The periods of a year, which were already observed, are thus taken from the data and the remaining periods from the draw, so that every draw of the forecast becomes a draw of the annual figure.
The codes determine the annual figure. The multiplicative codes 4 to 7 –
logarithms, their differences and differences of growth rates – describe a
series such as GDP or a price index, whose annual figure is a growth rate in
percent. The additive codes 1 to 3 describe a series such as an unemployment
rate or an interest rate, whose annual figure is a level. Argument
target determines, which growth rate and which level:
"average"the growth of the annual average of the levels over the annual average of the year before for codes 4 to 7, and the annual average for codes 1 to 3. This is the convention of, e.g., the World Economic Outlook of the IMF. The growth of the annual average is also the growth of the annual sum, since both years have the same number of periods, so it serves flows such as GDP and averages such as prices alike.
"q4q4"the growth of the level of the last period of the year over the last period of the year before, i.e. the fourth quarter over the fourth quarter or December over December, for codes 4 to 7, and the level of the last period of the year for codes 1 to 3. This is the convention of, e.g., the Summary of Economic Projections of the Federal Reserve.
Reversing a difference requires the level, from which it starts. For codes 2,
3, 6 and 7 it is taken from argument levels, which is therefore
required for them. Codes 1, 4 and 5 can be reversed from the data of the
models, because the unknown level of a logarithm cancels from a growth rate.
If levels is provided, it must reproduce the data of the models under
code and scale, which guards against a wrong scale, and
it also provides the realised annual figures.
Horizon 1 is the year of the forecast origin, i.e. the year of the first
period after the training sample, and horizon 2 the year after it. The number
of annual horizons is the number of years that the forecast horizon covers
from every origin, floor(n_ahead / frequency), so that a quarterly
model, which forecasts eight quarters, provides the current and the next year.
The realised annual figures, against which the aggregated forecasts are
scored, are obtained from levels or, without it, from the data of the
models in the same way, and are put in data$test$y.
add_forecast_errors uses them, if its argument
test_sample is omitted. Otherwise, test_sample must be an annual
time series, for example of official annual figures.
The result can be passed as argument object to
create_external_forecast, which then reads the periods of the
external forecasts as years, but matches their publications to the training
samples of the models at the frequency of the data. The external forecasts are
scored against the same realised annual figures as the models.
The aggregated models only contain the forecasts and the data, which are
required to evaluate them. Therefore, aggregation is the last step before
add_forecast_errors and selection_criteria, which
only provides out-of-sample statistics for them. Aggregated VEC models become
objects of class 'bvarmodel', because their forecasts are those of the levels.
An object of the same class as object, whose models contain the
draws of the annual forecasts in posterior$forecast$forecasts.
McCracken, M. W., & Ng, S. (2021). FRED-QD: A quarterly database for macroeconomic research. Federal Reserve Bank of St. Louis Review, 103(1), 1–44.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("us_macrodata") # Inflation and the interest rate enter the model as they are model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "const", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. model <- use_expanding_window(model, start = 2005) model <- add_priors(model, coef = list(v_i = 0.1, v_i_det = 0.01), sigma = list(df = "k", scale = 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) model <- add_forecast_input(model, n_ahead = 8) model <- add_posterior_forecasts(model) # Annual averages of inflation and the interest rate annual <- aggregate_forecasts(model, code = c(Dp = 1, r = 1)) # Artificial annual forecasts of the current and the next year, published in # the middle of each quarter fcst <- expand.grid(origin = 2005 + (0:7) / 4 + 0.1, year = 0:1, variable = c("Dp", "r"), stringsAsFactors = FALSE) fcst[["period"]] <- floor(fcst[["origin"]]) + fcst[["year"]] fcst[["value"]] <- 2 ext <- create_external_forecast(fcst, annual, data_lag = 1) # Both are scored against the annual averages of the data models <- add_forecast_errors(combine_models(annual, ext)) selection_criteria(models)data("us_macrodata") # Inflation and the interest rate enter the model as they are model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "const", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. model <- use_expanding_window(model, start = 2005) model <- add_priors(model, coef = list(v_i = 0.1, v_i_det = 0.01), sigma = list(df = "k", scale = 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) model <- add_forecast_input(model, n_ahead = 8) model <- add_posterior_forecasts(model) # Annual averages of inflation and the interest rate annual <- aggregate_forecasts(model, code = c(Dp = 1, r = 1)) # Artificial annual forecasts of the current and the next year, published in # the middle of each quarter fcst <- expand.grid(origin = 2005 + (0:7) / 4 + 0.1, year = 0:1, variable = c("Dp", "r"), stringsAsFactors = FALSE) fcst[["period"]] <- floor(fcst[["origin"]]) + fcst[["year"]] fcst[["value"]] <- 2 ext <- create_external_forecast(fcst, annual, data_lag = 1) # Both are scored against the annual averages of the data models <- add_forecast_errors(combine_models(annual, ext)) selection_criteria(models)
The weights with which a series observed at a lower frequency aggregates the
high-frequency periods of a model, for argument aggregate of
create_bvarmodel.
aggregation_weights(type = c("average", "sum", "growth"), n = 3)aggregation_weights(type = c("average", "sum", "growth"), n = 3)
type |
a character naming the aggregation: |
n |
an integer, the number of high-frequency periods one low-frequency period covers: 3 for quarters of months, 12 for years of months, 4 for years of quarters. |
An observation of the low-frequency series in period is
where is the high-frequency series the model contains and
are the weights returned, oldest first.
For "average" they are weights of , and for
"sum" weights of one. For "growth" the high-frequency
series is the growth rate – the log difference – of a series whose average
the low-frequency series is the growth rate of. Approximating the log of an
average by the average of the logs, that growth rate is a triangular
combination of high-frequency growth rates, which for quarters
of months is .
A numeric vector of weights, oldest period first.
Mariano, R. S., & Murasawa, Y. (2003). A new coincident index of business cycles based on monthly and quarterly series. Journal of Applied Econometrics, 18(4), 427–443. doi:10.1002/jae.695
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
aggregation_weights("growth", 3)aggregation_weights("growth", 3)
Generic function used to restrict each model in a list to the set of observations common to all models, ensuring that comparisons are computed on the same underlying sample.
align_model_obs(object, ...)align_model_obs(object, ...)
object |
a list of models. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: align_model_obs.modellist.
Restricts each model in an object of class 'modellist' to the set of observations common to all models, ensuring that comparisons are computed on the same underlying sample.
## S3 method for class 'modellist' align_model_obs(object, ...)## S3 method for class 'modellist' align_model_obs(object, ...)
object |
an object of class 'modellist'. |
... |
further arguments passed to or from other methods. |
An object of class 'modellist'.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data(e6) # Create multiple VAR models model_1 <- create_bvarmodel(diff(e6), p = 0:2, deterministic = "const") # Create multiple VEC models model_2 <- create_bvecmodel(e6, p = 1, r = 0:1, const = "unrestricted") # Combine the models in one object model <- combine_models(model_1, model_2) model <- align_model_obs(model)# Load data data(e6) # Create multiple VAR models model_1 <- create_bvarmodel(diff(e6), p = 0:2, deterministic = "const") # Create multiple VEC models model_2 <- create_bvecmodel(e6, p = 1, r = 0:1, const = "unrestricted") # Combine the models in one object model <- combine_models(model_1, model_2) model <- align_model_obs(model)
Impulse response functions and forecast error variance decompositions of a model in an HDF5 file, computed a piece of the chain at a time.
## S3 method for class 'bvarfile' irf(x, ..., chunk = 100) ## S3 method for class 'bvarfile' fevd(x, ..., chunk = 100)## S3 method for class 'bvarfile' irf(x, ..., chunk = 100) ## S3 method for class 'bvarfile' fevd(x, ..., chunk = 100)
x |
an object of class 'bvarfile', from |
... |
arguments of |
chunk |
how many draws are read at a time. Defaults to 100. |
Both quantities are sums over the draws: an impulse response is a set of
quantiles of the responses of the draws, a variance decomposition their mean.
Neither needs the draws together, so the chain is read in pieces of
chunk, each piece contributes what it has, and the pieces are put
together at the end. What comes out is what the same call on the model in
memory gives.
For a variance decomposition the pieces are combined before the shares are
normalised and before groups are collapsed, so normalise_gir and
max_groups describe the whole chain rather than the piece they were
applied to.
What irf.bvarmodel and fevd.bvarmodel
return: an object of class 'bvarirf' or 'bvarfevd'.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) file <- file.path(tempdir(), "bvartools-example-irf.h5") unlink(file) write_to_hdf5(model, filename = file) stored <- open_model(file) ir <- irf(stored, impulse = "invest", response = "income", n_ahead = 5, chunk = 25) shares <- fevd(stored, response = "income", n_ahead = 5, chunk = 25)data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) file <- file.path(tempdir(), "bvartools-example-irf.h5") unlink(file) write_to_hdf5(model, filename = file) stored <- open_model(file) ir <- irf(stored, impulse = "invest", response = "income", n_ahead = 5, chunk = 25) shares <- fevd(stored, response = "income", n_ahead = 5, chunk = 25)
The identification step of add_sign_zero_restrictions on its
own: rotations of the reduced-form draws of a VAR that satisfy sign and zero
restrictions on the impulse responses, with the importance weights of Arias,
Rubio-Ramirez and Waggoner (2018). It is exported for packages that estimate
a VAR as part of something larger – the state equation of a factor
augmented VAR, for example – and want to identify it the same way.
arias_rubio_ramirez_waggoner_2018( draws, restrictions, variables, lags, max_tries = 1, smooth = TRUE, one_sided = FALSE )arias_rubio_ramirez_waggoner_2018( draws, restrictions, variables, lags, max_tries = 1, smooth = TRUE, one_sided = FALSE )
draws |
a list with one element per posterior draw, each a list with
elements |
restrictions |
a data frame of the restrictions, as in
|
variables |
the names of the |
lags |
the lag order |
max_tries |
integer. The largest number of rotations drawn for each
posterior draw. See 'Details' of |
smooth |
logical. Should the importance weights be Pareto smoothed? |
one_sided |
logical. Should the numerical derivative behind the importance weights be taken on one side only? |
The rotation of a draw maps into the impact matrix
, with the lower Cholesky factor of Sigma: the
response of the variables to the shocks on impact.
The function draws from the random number generator in the order
add_sign_zero_restrictions does, so the same seed gives the
same rotations through either. It warns when the importance sample is not
fit to summarise, and stops when no draw has an admissible rotation.
A list with
q |
a matrix with one row per draw holding its rotation, by column, and
|
weights |
the normalised importance weights, zero for such a draw; |
restrictions |
the restrictions, with positions in place of names; |
tries |
the number of rotations drawn in all; |
accepted |
the number of draws with an admissible rotation; |
effective_sample_size, max_weight_share, pareto_k
|
the diagnostics of
the importance sample, as |
Arias, J. E., Rubio-Ramirez, J. F., Waggoner, D. F. (2018). Inference based on structural vector autoregressions identified with sign and zero restrictions: Theory and applications. Econometrica, 86(2), 685-720. doi:10.3982/ECTA14468
add_sign_zero_restrictions, which applies it to a
'bvarmodel' and resamples the draws.
The data set contains quarterly time series for Austria, the corresponding foreign
(star) variables and global commodity prices from 1979Q2 to 2023Q3. It was produced
from data set gvar2023 of package bgvars, which contains the GVAR database
of Mohaddes and Raissi (2024), as the Austrian sub-model of a global VAR model
of all 33 countries of the database.
data("at_macrodata")data("at_macrodata")
A named list with two elements, which are quarterly time-series objects from 1979Q2 to 2023Q3 with 178 rows each:
domestica time-series object with 6 columns, the domestic (endogenous) variables:
ylog real GDP.
Dprate of inflation, the quarterly change in the log CPI.
eqlog real equity prices.
eplog exchange rate against the US dollar, deflated by the CPI.
rshort-term interest rate,
, where
is the annual short-term rate in percent.
lrlong-term interest rate,
, where
is the annual long-term rate in percent.
foreigna time-series object with 9 columns, the foreign and global (weakly exogenous) variables:
y.s, Dp.s, eq.s, ep.s, r.s, lr.s
foreign counterparts of the domestic variables.
poillog oil prices.
pmatlog agricultural raw material prices.
pmetallog metals prices.
The foreign variables are trade weighted averages of the series of the other countries of the database for which the respective variable is available. The weights are constant over the whole sample and equal the shares of the countries in Austria's trade summed over the years 2014 to 2016.
In a sub-model of a global VAR the domestic variables are endogenous, and the foreign
and global variables are weakly exogenous. The two elements of the list can therefore be
passed to arguments data and exogen of create_bvarmodel or
create_bvecmodel, e.g.
create_bvarmodel(data = at_macrodata$domestic, exogen = at_macrodata$foreign).
Dees, S., di Mauro, F., Pesaran, M. H., & Smith, L. V. (2007). Exploring the international linkages of the euro area: A global VAR analysis. Journal of Applied Econometrics, 22(1), 1–38. doi:10.1002/jae.932
Mohaddes, K., & Raissi, M. (2024). Compilation, revision and updating of the global VAR (GVAR) database, 1979Q2–2023Q3 (mimeo). University of Cambridge: Judge Business School.
Returns a function that runs the standalone BayesTS executable on model files or on directories of them, several at a time, leaving the results in the files.
bayests_files(executable = NULL, library_path = NULL)bayests_files(executable = NULL, library_path = NULL)
executable |
the path to the BayesTS executable. If |
library_path |
a character vector of directories the executable needs on
its search path for its runtime libraries, put in front of |
bayests_posterior draws one model that is in the session: it
writes the model to a scratch file, runs BayesTS on it and reads the draws
back. For models that are already stored – a folder written with
write_to_hdf5, which is how a model too large to hold is worked
on – that is three copies of the draws per model and a session holding them,
for no purpose. The function returned here runs BayesTS on the stored files
themselves and leaves what it produces where it wrote it, so the draws never
pass through R.
The returned function takes paths, which are model files or directories of them, the name of a BayesTS command, and how many to run at once:
"posterior"draws the posterior, and with it the pointwise
log-likelihood unless --no-loglik is passed in args.
"loglik"the log-likelihood of a model that has draws.
"forecasts"the forecasts of a model that has draws.
"check"reads and validates the models without running them, which is what to call before an estimation that will take hours.
A model is drawn with the seed in its file, so it does not matter whether it
is run on its own, as one of a directory, or through
bayests_posterior: the draws are the same.
A function of paths, a command, further arguments for the executable and the number of processes to run at once. It returns the paths invisibly and fails with the end of BayesTS's output if any of the runs does.
The executable works through a directory one model at a time and gains
nothing from OMP_NUM_THREADS on models of the size a country model of
a global VAR has, so the way to use a machine is to give it several paths and
a jobs above one.
They are run as processes of the operating system rather than on a cluster of R workers, because an idle R worker is not cheap: on Windows a fresh one commits about 2 GB before it does anything and about 4 GB once it has loaded a package of this kind, which for six workers is more memory than the six BayesTS processes they would be waiting for. Here one R session starts the processes, each writing its output to a log of its own, and waits for them.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
## Not run: run <- bayests_files(executable = "/opt/bayests/bin/bayests") # One directory of models, drawn in place run("models/gvar/submodels/US") # Every country, six processes at a time run(list.dirs("models/gvar/submodels", recursive = FALSE), jobs = 6) # Validate first, draw without the log-likelihood run("models/gvar/submodels/US", command = "check") run("models/gvar/submodels/US", args = "--no-loglik") ## End(Not run)## Not run: run <- bayests_files(executable = "/opt/bayests/bin/bayests") # One directory of models, drawn in place run("models/gvar/submodels/US") # Every country, six processes at a time run(list.dirs("models/gvar/submodels", recursive = FALSE), jobs = 6) # Validate first, draw without the log-likelihood run("models/gvar/submodels/US", command = "check") run("models/gvar/submodels/US", args = "--no-loglik") ## End(Not run)
Returns a function that simulates the posterior of a model with the standalone BayesTS executable rather than with the samplers compiled into this package.
bayests_posterior(executable = NULL, library_path = NULL, scratch = tempdir())bayests_posterior(executable = NULL, library_path = NULL, scratch = tempdir())
executable |
the path to the BayesTS executable. If |
library_path |
a character vector of directories the executable needs on
its search path for its runtime libraries, put in front of |
scratch |
the directory where the model files are written while BayesTS draws into them. They are removed afterwards. |
The result is meant for argument posterior_function of
add_posterior_coefficients:
model <- add_posterior_coefficients(model, posterior_function = bayests_posterior())
It writes the model with write_to_hdf5, runs
bayests posterior on the file without its log-likelihood and forecast
steps, reads the draws back with read_model_from_hdf5 and adds
them to the model as element posterior. Nothing else about the model is
changed. The draws have the elements, dimensions and thinning of those of the
internal samplers, whose C++ code BayesTS shares; a BayesTS build linked
against an optimised BLAS draws faster.
BayesTS draws with the seed in object$model$seed, which
add_initial_values sets and add_seed replaces. A
model without one is given a seed drawn from R's random number generator,
since BayesTS would otherwise start every model from the same state of its
own generator. The seed used is kept in the returned model.
The executable runs single threaded unless OMP_NUM_THREADS says
otherwise, which suits simulating one model per worker of a cluster.
A function of one argument, a model of class 'bvarmodel' or 'bvecmodel', that returns that model with its posterior draws.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bvar(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
bvar collects the posterior draws of a vector autoregressive model in
an object of class 'bvarmodel'.
bvar( data = NULL, exogen = NULL, y, x = NULL, z = NULL, A0 = NULL, A = NULL, B = NULL, C = NULL, Sigma = NULL, error = NULL, varsel = NULL, iterations = NULL, burnin = 0 )bvar( data = NULL, exogen = NULL, y, x = NULL, z = NULL, A0 = NULL, A = NULL, B = NULL, C = NULL, Sigma = NULL, error = NULL, varsel = NULL, iterations = NULL, burnin = 0 )
data |
the original time-series object of endogenous variables. If
|
exogen |
the original time-series object of unmodelled variables. If
|
y |
a time-series object of endogenous variables with |
x |
a time-series object of |
z |
a |
A0 |
either a |
A |
either a |
B |
either a |
C |
either a |
Sigma |
a |
error |
a character specifying the model that was used for the estimation
of the covariance matrix of the error term. If |
varsel |
a character specifying the variable selection algorithm that was
employed. If |
iterations |
an integer of the number of MCMC draws in the provided
coefficient matrices. If |
burnin |
an integer of the number of MCMC draws that were used to initialise the sampler. Defaults to zero, since the draws provided to the function are assumed to exclude them already. |
For the VARX model
the function collects the S draws of a Gibbs sampler (after the burn-in phase) in a standardised object,
where is a K-dimensional vector of endogenous variables,
is a matrix of structural coefficients.
is a coefficient matrix of lagged endogenous variabels.
is an M-dimensional vector of unmodelled, non-deterministic variables
and its corresponding coefficient matrix.
is an N-dimensional vector of deterministic terms
and its corresponding coefficient matrix.
is an error term with .
For time varying parameter and stochastic volatility models the respective coefficients and error covariance matrix of the above model are assumed to be time varying, respectively.
The draws of the different coefficient matrices provided in A0, A,
B, C and Sigma have to correspond to the same MCMC iterations.
The result is the same kind of object as the output of
create_bvarmodel in combination with
add_posterior_coefficients, so it can be used with the methods of class
'bvarmodel' such as irf.bvarmodel,
predict.bvarmodel or summary.bvarmodel.
Accordingly, the draws are stored in the parameterisation those methods
expect: the coefficients of the conditional mean are collected in a single
matrix a in the order in which their regressors enter the data matrix
and the draws of the error term are stored as draws of the inverse of
. Draws of are reduced to the free elements below its
diagonal, which are the elements that are estimated.
Since a model that is constructed from posterior draws does not contain the
specification of its priors, the elements priors and initial of
the resulting object are empty. Use add_priors and
add_initial_values if the model should be re-estimated.
An object of class "bvarmodel" containing the following components:
model |
a list containing information on the model specification. |
data |
a list of data objects. Element |
posterior |
a list of posterior draws. Element |
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvec(),
chain_diagnostics(),
predict.bvecmodel()
# Get data data("e1") e1 <- diff(log(e1)) e1 <- window(e1, end = c(1978, 4)) # Generate model data data <- create_bvarmodel(e1, p = 2, deterministic = "const") # Add priors model <- add_priors(data, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .00001)) # Set RNG seed for reproducibility set.seed(1234567) iterations <- 400 # Number of iterations of the Gibbs sampler # Chosen number of iterations and burnin should be much higher. burnin <- 100 # Number of burn-in draws draws <- iterations + burnin # Total number of MCMC draws y <- t(model$data$train$y) x <- t(model$data$train$x) tt <- ncol(y) # Number of observations k <- nrow(y) # Number of endogenous variables m <- k * nrow(x) # Number of estimated coefficients # Priors a_mu_prior <- model$priors$a$mu # Vector of prior parameter means a_v_i_prior <- model$priors$a$v_inv # Inverse of the prior covariance matrix u_sigma_df_prior <- model$priors$u_sigma$df # Prior degrees of freedom u_sigma_scale_prior <- model$priors$u_sigma$scale # Prior covariance matrix u_sigma_df_post <- tt + u_sigma_df_prior # Posterior degrees of freedom # Initial values u_sigma_i <- diag(1 / .00001, k) # Data containers for posterior draws draws_a <- matrix(NA, m, iterations) draws_sigma <- matrix(NA, k^2, iterations) # Start Gibbs sampler for (draw in 1:draws) { # Draw conditional mean parameters a <- post_normal(y, x, u_sigma_i, a_mu_prior, a_v_i_prior) # Draw variance-covariance matrix u <- y - matrix(a, k) %*% x # Obtain residuals u_sigma_scale_post <- solve(u_sigma_scale_prior + tcrossprod(u)) u_sigma_i <- matrix(rWishart(1, u_sigma_df_post, u_sigma_scale_post)[,, 1], k) # Store draws if (draw > burnin) { draws_a[, draw - burnin] <- a draws_sigma[, draw - burnin] <- solve(u_sigma_i) } } # Generate bvarmodel object bvar_est <- bvar(data = e1, y = model$data$train$y, x = model$data$train$x, A = draws_a[1:18,], C = draws_a[19:21, ], Sigma = draws_sigma)# Get data data("e1") e1 <- diff(log(e1)) e1 <- window(e1, end = c(1978, 4)) # Generate model data data <- create_bvarmodel(e1, p = 2, deterministic = "const") # Add priors model <- add_priors(data, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .00001)) # Set RNG seed for reproducibility set.seed(1234567) iterations <- 400 # Number of iterations of the Gibbs sampler # Chosen number of iterations and burnin should be much higher. burnin <- 100 # Number of burn-in draws draws <- iterations + burnin # Total number of MCMC draws y <- t(model$data$train$y) x <- t(model$data$train$x) tt <- ncol(y) # Number of observations k <- nrow(y) # Number of endogenous variables m <- k * nrow(x) # Number of estimated coefficients # Priors a_mu_prior <- model$priors$a$mu # Vector of prior parameter means a_v_i_prior <- model$priors$a$v_inv # Inverse of the prior covariance matrix u_sigma_df_prior <- model$priors$u_sigma$df # Prior degrees of freedom u_sigma_scale_prior <- model$priors$u_sigma$scale # Prior covariance matrix u_sigma_df_post <- tt + u_sigma_df_prior # Posterior degrees of freedom # Initial values u_sigma_i <- diag(1 / .00001, k) # Data containers for posterior draws draws_a <- matrix(NA, m, iterations) draws_sigma <- matrix(NA, k^2, iterations) # Start Gibbs sampler for (draw in 1:draws) { # Draw conditional mean parameters a <- post_normal(y, x, u_sigma_i, a_mu_prior, a_v_i_prior) # Draw variance-covariance matrix u <- y - matrix(a, k) %*% x # Obtain residuals u_sigma_scale_post <- solve(u_sigma_scale_prior + tcrossprod(u)) u_sigma_i <- matrix(rWishart(1, u_sigma_df_post, u_sigma_scale_post)[,, 1], k) # Store draws if (draw > burnin) { draws_a[, draw - burnin] <- a draws_sigma[, draw - burnin] <- solve(u_sigma_i) } } # Generate bvarmodel object bvar_est <- bvar(data = e1, y = model$data$train$y, x = model$data$train$x, A = draws_a[1:18,], C = draws_a[19:21, ], Sigma = draws_sigma)
What the object every step of an analysis passes along is made of, where each part comes from and how the numbers in it are laid out.
create_bvarmodel and create_bvecmodel return a
list of class 'bvarmodel' or 'bvecmodel', and every later step
returns that list with something added. Each call therefore has to be assigned
back: model <- add_priors(model, ...).
The object is an ordinary list, so anything in it can be reached with
$ or [[, and anything the package does not do can be done to it
directly. The layout below is the contract that makes that safe.
modelThe specification. k endogenous variables,
p lags of them, m unmodelled variables with s lags,
n deterministic terms, and the names in endogen,
exogen and deterministic. error names the error
distribution, varsel the variable selection scheme, tvp
whether the coefficients drift and structural whether the model is
identified. iterations and burnin size the chain, thin
is present only above one, and algorithm names the sampler that will
draw it. A VEC model adds rank, k_beta and the deterministic
terms restricted to the cointegration space; a quantile VAR adds
quantile, or quantiles for a grid of them, and
add_posterior_forecasts a grid's forecast_quantile.
add_dummy_variables adds
dummy_variables, the rule each of its dummies is continued by in a
forecast. add_seed adds seed,
add_forecast_input adds h and
forecast_states.
data$originalThe series as given, before any lag was taken:
endogen, and exogen and deterministic where there are
any. What the model is rebuilt from when a window of it is taken.
data$trainThe estimation sample. y is one row per
period and one column per variable; x is the regressors in the same
compact layout, one row per period; z is the same regressors in SUR
form, kron(x, I_k), which is what the samplers of a VAR read. A VEC
model adds w, the lagged levels the cointegration term is formed
from. A VAR estimated from a panel not observed whole adds
constraints, what was observed of it: value and group
with one element per observation, and row, period,
variable and weight with one per entry of the linear
combination each observation is, counted from one. See
create_bvarmodel.
data$forecastAdded by add_forecast_input: the
regressors of the forecast periods, x in the compact layout, one row
per horizon. A VEC model's are in the layout of its VAR representation,
which is the form it is forecast in.
data$test$yAdded by add_forecast_errors: what
the horizon realised, one row per period and one column per variable, the
periods of the horizon and nothing else. The only thing under data
that no sampler reads – it is what a forecast is scored against, not
anything it is estimated from – and what lets a model that was written to
a file be scored again from the file alone.
priorsAdded by add_priors: the prior
hyperparameters, one block per parameter block of the posterior. Prior
variances are given as precisions. Which elements are needed depends on
error; the method's own help page, add_priors.bvarmodel
or add_priors.bvecmodel, lists them. a$shrinkage,
mu and constraints are added by
add_prior_options.
initialAdded by add_initial_values: the
starting values the sampler begins from.
posteriorAdded by
add_posterior_coefficients and the later
add_posterior_* functions. The draws; see below.
posterior holds one named block per group of parameters, and each
block is a list whose coeffs carries the draws:
aThe coefficients. coeffs has columns, or
with tvp = TRUE, the whole path of a draw stacked by period.
lambda holds the inclusion indicators where variable selection is on
and sigma the variances of the random walk where the coefficients
drift.
u_sigma_invThe error precision matrix, columns per
period, vectorised. sigma holds the variance of the log-volatility
innovations under stochastic volatility, which is what a forecast steps the
volatility forward by.
u_omega_invThe diagonal of that precision, columns
per period, for every error but "wishart".
psiThe triangular matrix of the covariance block,
columns – the whole matrix, not only its free elements – with
lambda and sigma as above.
u_scaleThe scale of the asymmetric Laplace, columns,
for a quantile VAR, and per level for a grid of quantiles, whose
a is stacked the same way and which keeps no u_sigma_inv
or u_omega_inv.
yThe completed panel of a VAR estimated from one not
observed whole, columns stacked by period, and
constraints_inv the error precisions of its soft constraints, one
column per group.
muThe unconditional means under a steady-state prior,
columns. Under an adaptive prior a adds shrinkage,
the scales of its groups, and for the horseshoe and the normal-gamma prior
local, one scale per coefficient, and theta where the
normal-gamma prior draws it.
betaThe cointegration vectors of a VEC model,
columns, and rho where a time-varying cointegration
space put a prior on its state autoregression.
qThe rotations of a sign-restricted identification, added by
add_sign_restrictions.
loglikThe pointwise log-likelihood of the estimation sample,
one column per period, added by add_posterior_loglik. A matrix
of draws rather than a block with coeffs, since there is only one
thing to hold.
forecastEverything the forecast periods produce:
forecasts, the simulated paths from
add_posterior_forecasts, and errors, what
add_forecast_errors took against data$test$y. Both have
columns, stacked by period. The members are named after what they
hold rather than one of them being draws, because all of them are
draws.
Draws are rows. Every matrix of draws is a
mcmc object with one row per draw and one column per
parameter, carrying the start, end and thin of the chain.
A posterior mean is colMeans() and a credible interval a column
quantile; transposing to "fix" the shape gives a summary of the wrong thing.
bvar and bvec, which collect the draws of a
sampler written by hand, are the exception and take the transpose.
A period is a block of columns. Where a quantity moves with time, the
path of one draw is stacked by period along that draw's row, so period
of a wide block is columns to
. The same holds of a forecast: the variables of the first
horizon come first, then those of the second.
Passing a vector to an argument such as p, r or quantile
gives one model per specification in a list of class 'modellist', and
use_expanding_window a list of class 'expandingwindow',
one model per window. Every step of the workflow has a method for both and
applies to each model in turn, so the structure above is what is inside either
of them. open_models is the same idea for a folder too large to
hold: a handle to the files rather than the models.
write_to_hdf5 writes the object to an HDF5 file with the paths
the elements above are named by – /data/train/y, /data/test/y,
/posterior/a/coeffs, /posterior/forecast/forecasts – and
read_model_from_hdf5 reads it back. It is the format the BayesTS
command line runs on, which is what makes a model estimated here and a model
estimated there the same object.
In the file every dataset is one row per quantity and one column per draw. R's readers reverse the dimension order, so a session sees the transpose of that, which is the draws-in-rows layout above.
bvartools for the workflow the steps are taken in, and
summary.bvarmodel for the summaries the package takes of the
draws itself.
data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) # The specification and the sample model[["model"]][["k"]] dim(model[["data"]][["train"]][["y"]]) # The draws, one row per draw and one column per parameter draws <- model[["posterior"]][["a"]][["coeffs"]] dim(draws) colMeans(draws)data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) # The specification and the sample model[["model"]][["k"]] dim(model[["data"]][["train"]][["y"]]) # The draws, one row per draw and one column per parameter draws <- model[["posterior"]][["a"]][["coeffs"]] dim(draws) colMeans(draws)
bvec collects the posterior draws of a vector error correction model
in an object of class 'bvecmodel'.
bvec( y, alpha = NULL, beta = NULL, beta_x = NULL, beta_d = NULL, r = NULL, w = NULL, w_x = NULL, w_d = NULL, Gamma = NULL, Upsilon = NULL, C = NULL, x = NULL, x_x = NULL, x_d = NULL, A0 = NULL, Sigma = NULL, data = NULL, exogen = NULL, z = NULL, error = NULL, varsel = NULL, iterations = NULL, burnin = 0 )bvec( y, alpha = NULL, beta = NULL, beta_x = NULL, beta_d = NULL, r = NULL, w = NULL, w_x = NULL, w_d = NULL, Gamma = NULL, Upsilon = NULL, C = NULL, x = NULL, x_x = NULL, x_d = NULL, A0 = NULL, Sigma = NULL, data = NULL, exogen = NULL, z = NULL, error = NULL, varsel = NULL, iterations = NULL, burnin = 0 )
y |
a time-series object of differenced endogenous variables,
usually, a result of a call to |
alpha |
a |
beta |
a |
beta_x |
a |
beta_d |
a |
r |
an integer of the rank of the cointegration matrix. If |
w |
a time-series object of lagged endogenous variables in levels, which enter the
cointegration term, usually, a result of a call to |
w_x |
a time-series object of lagged unmodelled, non-deterministic variables in levels, which enter the
cointegration term, usually, a result of a call to |
w_d |
a time-series object of deterministic terms, which enter the
cointegration term, usually, a result of a call to |
Gamma |
a |
Upsilon |
an |
C |
an |
x |
a time-series object of |
x_x |
a time-series object of |
x_d |
a time-series object of |
A0 |
either a |
Sigma |
a |
data |
the original time-series object of endogenous variables in levels.
If |
exogen |
the original time-series object of unmodelled variables in levels.
If |
z |
a |
error |
a character specifying the model that was used for the estimation
of the covariance matrix of the error term. If |
varsel |
a character specifying the variable selection algorithm that was
employed. If |
iterations |
an integer of the number of MCMC draws in the provided
coefficient matrices. If |
burnin |
an integer of the number of MCMC draws that were used to initialise the sampler. Defaults to zero, since the draws provided to the function are assumed to exclude them already. |
For the vector error correction model with unmodelled exogenous variables (VECX)
the function collects the draws of a Gibbs sampler in a standardised object,
where is a K-dimensional vector of differenced endogenous variables
and is a matrix of structural coefficients.
is the loading matrix and the
cointegration matrix of the error correction term,
where , and are the first lags of endogenous,
exogenous variables in levels and restricted deterministic terms, respectively.
is a coefficient matrix of lagged differenced endogenous variabels.
is an M-dimensional vector of unmodelled, non-deterministic variables
and its corresponding coefficient matrix. is an
-dimensional vector of unrestricted deterministics and
the corresponding coefficient matrix.
is an error term with .
For time varying parameter and stochastic volatility models the respective coefficients and error covariance matrix of the above model are assumed to be time varying, respectively.
The draws of the different coefficient matrices provided in alpha, beta,
beta_x, beta_d, A0, Gamma, Upsilon,
C and Sigma have to correspond to the same MCMC iteration.
The result is the same kind of object as the output of
create_bvecmodel in combination with
add_posterior_coefficients, so it can be used with the methods of class
'bvecmodel' such as vec_to_var.bvecmodel or
summary.bvecmodel. Accordingly, the draws are stored in the
parameterisation those methods expect. The error correction term is described
by and and not by ,
since the latter cannot be decomposed into the former. The draws of
are collected in the same matrix as the coefficients of the
remaining regressors and the draws of of all cointegration
relations are collected in a matrix of their own. Draws of the error term are
stored as draws of the inverse of and draws of are
reduced to the free elements below its diagonal, which are the elements that
are estimated.
Since a model that is constructed from posterior draws does not contain the
specification of its priors, the elements priors and initial of
the resulting object are empty. Use add_priors and
add_initial_values if the model should be re-estimated.
An object of class "bvecmodel" containing the following components:
model |
a list containing information on the model specification. |
data |
a list of data objects. Element |
posterior |
a list of posterior draws. Element |
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
chain_diagnostics(),
predict.bvecmodel()
# Load data data("e6") # Generate model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted") # Obtain data matrices y <- t(model$data$train$y) w <- t(model$data$train$w) x <- t(model$data$train$x) # Reset random number generator for reproducibility set.seed(1234567) iterations <- 400 # Number of iterations of the Gibbs sampler # Chosen number of iterations should be much higher, e.g. 30000. burnin <- 100 # Number of burn-in draws draws <- iterations + burnin r <- 1 # Set rank tt <- ncol(y) # Number of observations k <- nrow(y) # Number of endogenous variables k_w <- nrow(w) # Number of regressors in error correction term k_x <- nrow(x) # Number of differenced regressors and unrestrictec deterministic terms k_alpha <- k * r # Number of elements in alpha k_beta <- k_w * r # Number of elements in beta k_gamma <- k * k_x # Set uninformative priors a_mu_prior <- matrix(0, k_alpha + k_gamma) # Vector of prior parameter means a_v_i_prior <- diag(0, k_alpha + k_gamma) # Inverse of the prior covariance matrix v_i <- 0 p_tau_i <- diag(1, k_w) u_sigma_df_prior <- r # Prior degrees of freedom u_sigma_scale_prior <- diag(0.01, k) # Prior covariance matrix u_sigma_df_post <- tt + u_sigma_df_prior # Posterior degrees of freedom # Initial values beta <- matrix(c(1, -4), k_w, r) u_sigma_i <- diag(1 / .0001, k) g_i <- u_sigma_i # Data containers draws_alpha <- matrix(NA, k_alpha, iterations) draws_beta <- matrix(NA, k_beta, iterations) draws_gamma <- matrix(NA, k_gamma, iterations) draws_sigma <- matrix(NA, k^2, iterations) # Start Gibbs sampler for (draw in 1:draws) { # Draw conditional mean parameters temp <- post_coint_kls(y = y, beta = beta, w = w, sigma_i = u_sigma_i, v_i = v_i, p_tau_i = p_tau_i, g_i = g_i, x = x, gamma_mu_prior = a_mu_prior, gamma_v_i_prior = a_v_i_prior) alpha <- temp$alpha beta <- temp$beta Pi <- temp$Pi gamma <- temp$Gamma # Draw variance-covariance matrix u <- y - Pi %*% w - matrix(gamma, k) %*% x u_sigma_scale_post <- solve(tcrossprod(u) + v_i * alpha %*% tcrossprod(crossprod(beta, p_tau_i) %*% beta, alpha)) u_sigma_i <- matrix(rWishart(1, u_sigma_df_post, u_sigma_scale_post)[,, 1], k) u_sigma <- solve(u_sigma_i) # Update g_i g_i <- u_sigma_i # Store draws if (draw > burnin) { draws_alpha[, draw - burnin] <- alpha draws_beta[, draw - burnin] <- beta draws_gamma[, draw - burnin] <- gamma draws_sigma[, draw - burnin] <- u_sigma } } # Number of non-deterministic coefficients k_nondet <- (k_x - 4) * k # Generate bvecmodel object bvec_est <- bvec(y = model$data$train$y, w = model$data$train$w, x = model$data$train$x[, 1:6], x_d = model$data$train$x[, 7:10], r = r, alpha = draws_alpha, beta = draws_beta, Gamma = draws_gamma[1:k_nondet,], C = draws_gamma[(k_nondet + 1):nrow(draws_gamma),], Sigma = draws_sigma)# Load data data("e6") # Generate model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted") # Obtain data matrices y <- t(model$data$train$y) w <- t(model$data$train$w) x <- t(model$data$train$x) # Reset random number generator for reproducibility set.seed(1234567) iterations <- 400 # Number of iterations of the Gibbs sampler # Chosen number of iterations should be much higher, e.g. 30000. burnin <- 100 # Number of burn-in draws draws <- iterations + burnin r <- 1 # Set rank tt <- ncol(y) # Number of observations k <- nrow(y) # Number of endogenous variables k_w <- nrow(w) # Number of regressors in error correction term k_x <- nrow(x) # Number of differenced regressors and unrestrictec deterministic terms k_alpha <- k * r # Number of elements in alpha k_beta <- k_w * r # Number of elements in beta k_gamma <- k * k_x # Set uninformative priors a_mu_prior <- matrix(0, k_alpha + k_gamma) # Vector of prior parameter means a_v_i_prior <- diag(0, k_alpha + k_gamma) # Inverse of the prior covariance matrix v_i <- 0 p_tau_i <- diag(1, k_w) u_sigma_df_prior <- r # Prior degrees of freedom u_sigma_scale_prior <- diag(0.01, k) # Prior covariance matrix u_sigma_df_post <- tt + u_sigma_df_prior # Posterior degrees of freedom # Initial values beta <- matrix(c(1, -4), k_w, r) u_sigma_i <- diag(1 / .0001, k) g_i <- u_sigma_i # Data containers draws_alpha <- matrix(NA, k_alpha, iterations) draws_beta <- matrix(NA, k_beta, iterations) draws_gamma <- matrix(NA, k_gamma, iterations) draws_sigma <- matrix(NA, k^2, iterations) # Start Gibbs sampler for (draw in 1:draws) { # Draw conditional mean parameters temp <- post_coint_kls(y = y, beta = beta, w = w, sigma_i = u_sigma_i, v_i = v_i, p_tau_i = p_tau_i, g_i = g_i, x = x, gamma_mu_prior = a_mu_prior, gamma_v_i_prior = a_v_i_prior) alpha <- temp$alpha beta <- temp$beta Pi <- temp$Pi gamma <- temp$Gamma # Draw variance-covariance matrix u <- y - Pi %*% w - matrix(gamma, k) %*% x u_sigma_scale_post <- solve(tcrossprod(u) + v_i * alpha %*% tcrossprod(crossprod(beta, p_tau_i) %*% beta, alpha)) u_sigma_i <- matrix(rWishart(1, u_sigma_df_post, u_sigma_scale_post)[,, 1], k) u_sigma <- solve(u_sigma_i) # Update g_i g_i <- u_sigma_i # Store draws if (draw > burnin) { draws_alpha[, draw - burnin] <- alpha draws_beta[, draw - burnin] <- beta draws_gamma[, draw - burnin] <- gamma draws_sigma[, draw - burnin] <- u_sigma } } # Number of non-deterministic coefficients k_nondet <- (k_x - 4) * k # Generate bvecmodel object bvec_est <- bvec(y = model$data$train$y, w = model$data$train$w, x = model$data$train$x[, 1:6], x_d = model$data$train$x[, 7:10], r = r, alpha = draws_alpha, beta = draws_beta, Gamma = draws_gamma[1:k_nondet,], C = draws_gamma[(k_nondet + 1):nrow(draws_gamma),], Sigma = draws_sigma)
Compares the chains of a model estimated with chains above one in
add_posterior_coefficients and reports, for every parameter, the
potential scale reduction factor and two effective sample sizes.
chain_diagnostics(object, ...)chain_diagnostics(object, ...)
object |
an object of class 'bvarmodel' or 'bvecmodel', whose posterior was
simulated with |
... |
further arguments passed to or from other methods. |
A single chain can look converged and not be: its autocorrelations and its effective sample size describe how well it explores the region it is in, not whether that region is the posterior. Chains started from the same values but drawing different random numbers settle in different places if the posterior has several modes or the sampler has not left the neighbourhood of its start, and comparing them is the check a single chain cannot provide.
The statistic is the rank-normalised split of Vehtari et al.
(2021). Every chain is cut into two halves, the pooled draws are replaced by
their ranks and put back on a normal scale, and the variance between the means
of the halves is compared with the variance within them,
where is the length of a half, the average variance within the
halves and times the variance of their means. Splitting the chains
catches a chain that is still drifting.
The rank normalisation is what makes the number mean the same thing
whatever scale the parameter is on. The plain version of this statistic is
built on variances, so it is undefined for a posterior heavy-tailed enough to
have none and it moves when the same draws are transformed monotonically –
which is awkward for a package whose parameters are freely rescaled and whose
variance blocks are reported both as omega and as its square. What is
reported is the larger of the rank-normalised and the one computed
on the draws folded around their median, so that chains agreeing about the
centre but not about the spread are caught as well.
Values close to one indicate that the chains describe the same distribution;
above 1.01, Vehtari et al. (2021) recommend running the chains longer or
reconsidering the model. A parameter that does not vary in any chain, such as a
coefficient that variable selection excluded throughout or an equation that
iid left without coefficients, has no and is reported as
NA.
The signed standard deviations omega of a block estimated under the
non-centred prior omega_v are symmetric around zero by construction –
the sampler switches their sign at random – so their is close to
one whether or not the chains agree. Their squares, sigma, which are in
the posterior beside them, are the ones to read.
Two effective sample sizes are reported, and for this package the
second is usually the one that matters. ess_bulk is computed on the
rank-normalised draws and says how much independent information the sample
carries about the centre of the posterior. ess_tail is the smaller of
the effective sample sizes at the 5th and 95th percentiles and says the same
about the extremes. Almost nothing this package reports is a point:
irf, fevd and the forecasts all come back as
quantiles, and it is ess_tail that says whether those quantiles have
settled. A sample can carry a comfortable ess_bulk and still have a
band that moves from one run to the next.
Neither is a convergence diagnostic: chains stuck in different modes can each have a large one.
The chains start from the same initial values, those of
add_initial_values, and differ in their random numbers. Dispersed
starting values would make the comparison more demanding.
A data frame with one row per parameter of every block of posterior draws,
other than the forecasts and the log-likelihood, and the columns block,
parameter, rhat, ess_bulk and ess_tail.
Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian data analysis (3rd ed.). Boca Raton: CRC Press.
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Bürkner, P.-C. (2021).
Rank-normalization, folding, and localization: An improved for
assessing convergence of MCMC. Bayesian Analysis, 16(2), 667–718.
doi:10.1214/20-BA1221
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
predict.bvecmodel()
data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 1, deterministic = "const", iterations = 200, burnin = 100) model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = "k", scale = 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model, chains = 2) diag <- chain_diagnostics(model) max(diag$rhat, na.rm = TRUE)data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 1, deterministic = "const", iterations = 200, burnin = 100) model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = "k", scale = 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model, chains = 2) diag <- chain_diagnostics(model) max(diag$rhat, na.rm = TRUE)
A generic function that applies model selection criteria to find the best model.
choose_best_model(object, ...)choose_best_model(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: choose_best_model.selcritlist.
Chooses the best model according the selection criteria in an object of class 'selcritlist'.
## S3 method for class 'selcritlist' choose_best_model(object, criterion = "WAIC", ...)## S3 method for class 'selcritlist' choose_best_model(object, criterion = "WAIC", ...)
object |
object of class 'selcritlist', usually, a result of a call
to |
criterion |
the selection criterion that should be used. Available choices
are |
... |
further arguments passed to or from other methods. |
If argument criterion is "LL", "LPL" or "LML", the model with the
maximum value is chosen, otherwise, the model with the minimum value.
Which criterion to use depends on the models that are compared. See
selection_criteria, whose details set out what each of them
penalises and when a count of parameters ceases to describe a model. The
default is "WAIC", because it is the criterion that stays defined
across the models this package estimates: it penalises by the flexibility
the fit used rather than by a count of parameters, which describes neither a
model whose coefficients or variances follow a state equation nor one whose
prior shrinks them. "AIC", "BIC" and "HQ" remain the
criteria for the lag order of a model with constant coefficients and a weak
prior, which is the case they are derived for. "LPL", the log
predictive likelihood of an expanding window exercise with
add_predictive_loglik, is the criterion for the rank of a VEC
model whose coefficients or variances follow a state equation.
"LML" is the one criterion of the discounted models and the only one
they carry. It is the exact log marginal likelihood of the sample, read off
the file rather than estimated, so a grid over the rank, the cointegration
matrix, the lag order or the two discounts is compared by it directly. It is
not comparable with "LL", which conditions on the parameters where
this integrates them out.
An integer giving the position of the best model in the list provided
in argument object. Where several models attain the best value
exactly, the positions of all of them, in increasing order.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 1:3, deterministic = "const", iterations = 50, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Obtain posterior log-likelihoods model <- add_posterior_loglik(model) # Calculate selection criteria sel <- selection_criteria(model) # View results sel # Choose best model according to WAIC, the default choose_best_model(sel) # Choose best model according to AIC choose_best_model(sel, criterion = "AIC")# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 1:3, deterministic = "const", iterations = 50, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Obtain posterior log-likelihoods model <- add_posterior_loglik(model) # Calculate selection criteria sel <- selection_criteria(model) # View results sel # Choose best model according to WAIC, the default choose_best_model(sel) # Choose best model according to AIC choose_best_model(sel, criterion = "AIC")
Performs the second transformation of the loading and cointegration matrix as proposed in Koop et al. (2010).
coint_kls2010_reparameterise_two(alpha, beta)coint_kls2010_reparameterise_two(alpha, beta)
alpha |
a |
beta |
an |
The function performs two transformations:
A list of two matrices:
alpha |
Loading matrix |
beta |
Cointegration matrix |
Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior simulation for cointegrated models with priors on the cointegration space. Econometric Reviews, 29(2), 224-242. doi:10.1080/07474930903382208
# Generate input data alpha <- matrix(c(-0.07, 0.17), 2) beta <- matrix(c(1, -4), 2) # Reparameterise coint_kls2010_reparameterise_two(alpha, beta)# Generate input data alpha <- matrix(c(-0.07, 0.17), 2) beta <- matrix(c(1, -4), 2) # Reparameterise coint_kls2010_reparameterise_two(alpha, beta)
Generates the input matrix for the simulation of the cointegration matrix .
coint_prepare_sur_data(w, alpha, k, r, reparameterise, tvp)coint_prepare_sur_data(w, alpha, k, r, reparameterise, tvp)
w |
a |
alpha |
a |
k |
integer of the number of endogenous variables in the model. |
r |
integer with the rank of the cointegration matrix |
reparameterise |
logical indicating if the reparameterisation described in Koop et al. (2010) should be performed. |
tvp |
logical indicating if the SUR matrix with the values of regressors should be prepared for the estimation of constant or time varying parameters. |
A sparse block matrix.
data("e6") # Load data # Generate model input mod <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted") # Obtain input data alpha <- matrix(c(-0.1, 0.16, -0.04, -0.02), 2) w <- mod$data$train$w # Constant coefficients coint_prepare_sur_data(w, alpha, 2, 1, TRUE, FALSE) # Time varying coefficients coint_prepare_sur_data(w, alpha, 2, 1, FALSE, TRUE)data("e6") # Load data # Generate model input mod <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted") # Obtain input data alpha <- matrix(c(-0.1, 0.16, -0.04, -0.02), 2) w <- mod$data$train$w # Constant coefficients coint_prepare_sur_data(w, alpha, 2, 1, TRUE, FALSE) # Time varying coefficients coint_prepare_sur_data(w, alpha, 2, 1, FALSE, TRUE)
Checks the specification of the prior on the cointegration space of a VEC
model and builds it, in the form in which add_priors stores it
as element priors$beta.
cointspace_prior(object, coint)cointspace_prior(object, coint)
object |
a list of class 'bvecmodel', or any model with the same layout:
elements |
coint |
a named list of prior specifications for the coefficients determining the cointegration space. It has no default. See section 'Prior on the cointegration space'. |
add_priors calls this function for VEC models, so it rarely
needs to be called directly. It is exported for packages that build VEC
models of their own layout, such as the sub-models of a global VEC model,
whose error correction term also holds weakly exogenous and global
variables. Calling it gives them the same checks and the same prior.
All dimensions are taken from the regressors, not from the model
specification: the prior has one row and column for each series in the error
correction term data$train$w, and one block for each of the
model$rank cointegration vectors.
NULL for a model without cointegration, model$rank = 0,
whose coint is checked all the same. Otherwise a list with
type = "cointspace" and, for constant cointegration parameters,
v_inv and p_tau_inv, and g_inv if g_i was given,
or, for time varying ones, rho,
mu and v_inv of the state equation, together with
rho_min and rho_max for a uniform prior on and the
transition p_tau added by p_tau_i = "ml".
Argument coint can contain the following elements. Which of them are
required depends on whether the cointegration vectors are constant or time
varying, since the two are given different kinds of prior: a matric-variate
prior on the cointegration space in the first case, and a state equation in
the second. Any other element raises an error.
v_inon-negative numeric specifying the shrinkage of the cointegration space prior,
or "ml". See below. Required for models with constant cointegration parameters and not
used otherwise.
p_tau_ithe inverse of the matrix , which determines the
central location of the cointegration space . Either a numeric of
its diagonal elements, a full symmetric matrix, or "ml", with one row and
column per series in the error correction term data$train$w. See below.
Required for models with constant cointegration parameters. For models with time
varying cointegration parameters only "ml" is used.
weightpositive numeric specifying the weight of a prior centred on the
maximum likelihood estimate in units of the information of the sample. Default is 1.
Only used if p_tau_i = "ml".
rhoa numeric specifying the autocorrelation coefficient
of the state equation of . It must be smaller than 1.
Required for models with time varying cointegration parameters and not used otherwise.
If rho_min and rho_max are given as well, this is the value the
chain starts at rather than the value it keeps, and it must lie
between them.
rho_min, rho_max
numerics specifying the support of a
uniform prior on , which makes it a drawn parameter rather than a
fixed hyperparameter. Optional, and either both or neither; they must
satisfy rho_minrho_max.
Koop et al. (2011) use .
Only used for models with time varying cointegration parameters.
g_ithe inverse of the matrix that scales the prior of the
loadings, for models with constant cointegration parameters and stochastic volatility,
error = "sv" or "sv+covar", and refused for every other model. Either a
numeric of its diagonal elements, a full symmetric positive definite matrix with one row
and column per endogenous variable, or "ml" for the inverse of the maximum
likelihood estimate of the error covariance. Optional. See below.
For a model with constant cointegration parameters the prior is that of
Koop et al. (2010). The sampler uses v_i and p_tau_i only through
their product, so with v_i = 0 the prior on the cointegration space is
uniform whatever p_tau_i is. An informative prior on the space
therefore needs a positive v_i, which also shrinks the loadings: for
close to the centre of the space they have prior
.
In Koop et al. (2010) the loadings' prior is scaled by a matrix , which
may be the error covariance or any fixed, known matrix. The models
with a constant error covariance take . With stochastic
volatility the covariance differs from period to period, so is fixed
for the whole run instead: is g_i if it is given, and
otherwise the error precision implied by the starting values of the
log-volatilities, averaged over the sample once before the first draw. That
fallback depends on add_initial_values, so giving g_i
makes the prior independent of how the chain is started. g_i = "ml"
uses Johansen's (1995) estimate of the error covariance, the same one
v_i = "ml" is based on.
With p_tau_i = "ml" the prior is centred on the space spanned by
Johansen's (1995) maximum likelihood estimate , computed from
the error correction term as it is stored in the model – so call
scale_error_correction first if the series should be scaled;
scaling is refused afterwards.
Let be an orthonormal basis of that space, one of its
orthogonal complement and . The matrix
where is the cross product of the residuals of a regression of the
error correction term on the short-run regressors and is weight,
makes the prior of given
.
This is the asymptotic distribution of the maximum likelihood estimator
with its precision multiplied by : weight = 1 adds as much
information about the space as the sample itself holds. Since the centre is
estimated from the same sample, the posterior then overstates the precision
of . Eigenvalues of are capped at one, which is the
uniform prior.
With v_i = "ml" the shrinkage is chosen so that the prior mean of
is 100 times its maximum
likelihood estimate. It can be combined with a numeric p_tau_i.
For a model with time varying cointegration parameters the state equation is
with , and
the prior on the state before the sample is that equation's own stationary
distribution, . This is what makes the prior
proper, so a close to one is intended and one further from it draws
a warning. add_priors gives the loadings the compensating scale:
only the product is identified, so their prior
variance is shrunk by , leaving the product on the scale
coef$v_i asks for.
When is drawn, those last two are computed from coint$rho
once and do not follow the draw: the state before the sample keeps the normal
prior built here, and the loadings keep the shrinkage of
add_priors. This is a deliberate departure from Koop et al.
(2011), in whom the state before the sample is the stationary distribution of
whatever currently is. It is also what makes the draw an exact
Gibbs block rather than their Metropolis-within-Gibbs step: with the state
before the sample free of , the conditional posterior of
is a normal truncated to the prior's support. Draws of are
returned in object$posterior$beta$rho.
How far the space moves is not set by the prior on any variance. The steps
have unit variance whatever coef$rate and
coef$rate_alpha are, and how far a step moves
depends on the scale of .
Only the product is identified, so the posterior can pair small loadings with
large cointegration vectors, which a unit step barely turns, or large loadings
with small ones, which it turns a lot. Two things decide which. One is the
prior precision of the loadings, coef$v_i , which
restrains the drift only if it is tight relative to the scale of the
data call for, and that scale depends on the units of the data. The other is
the series in the error correction term: a step moves
by , which grows with the
levels of the series and not only with their variation. For log levels far
from zero the shift is of the order of the levels themselves, and the sampler
either lets it act as a random walk intercept, which no prior on the
deterministic terms controls and which can absorb the residuals of an
equation, or draws loadings close to zero, which switches the error
correction term off.
Both have been seen. In the US sub-model of the bgvars data set
gvar2023, with the oil price among its endogenous variables and a rank
of one, a prior that pinned the state variances of all coefficients, the
loadings and the constant included, at 1e-14 still left the residual standard
deviation of one equation as low as 0.1 to 0.5 of the maximum likelihood one
in some chains, with which equation and how low depending on the chain, and a
saved chain reported a posterior mean log-likelihood several hundred above the
maximum of the constant coefficient model. The chains do not move between
these outcomes within a few thousand draws, so a single chain can report any
of them. The Austrian sub-model under the same prior lost fit that the
constant coefficient model has, and the chains that were inspected drew
loadings close to zero. On data simulated from a constant coefficient VEC
model, whose posterior under such a prior should reproduce the maximum
likelihood fit, single chains did so only with the series centred and
coef$v_i = 10, or around zero and coef$v_i = 100. Around 12,
where log levels usually are, a chain drew loadings close to zero, and around
zero with coef$v_i = 1 one fitted part of the residuals.
The same mechanism makes scale_error_correction risky in a model
whose coefficients vary over time. It divides the series by the standard
deviation of their differences, which makes them, and with them both a drift
in a loading and a step of , larger by the same
factor. The coefficient paths can then absorb the residuals of an equation
almost entirely: its residual variance – or, under stochastic volatility, its
volatility path – is reported far below that of a least squares fit of the
same regressors and nearly constant over the sample. In the model of the
vignette on time varying parameters and stochastic volatility in error
correction models, vignette("tvp-sv-vec", package = "bvartools"), a
scaled error correction term did that to one equation in each of four chains
with different seeds, and the unscaled one with a small coef$rate in
none.
It is safer to leave the series unscaled, to set coef$v_i with the
scale of in mind as well as choosing small rates, and to compare the
residual variances with those of a least squares fit of the same regressors,
in chains with different seeds, for a model that is to be used. Small rates
alone do not guarantee that a model passes that check, and passing it is what
says that neither the coefficients nor the cointegration vectors fit the
residuals. scale_error_correction(object, scale = FALSE, centre = TRUE)
centres the series before posterior simulation, which removes the part of a
step of that comes from the levels of the series
rather than from their variation, and rescale_error_correction
writes the draws back in terms of the series as they are, so that
vec_to_var and the forecasts can use them. It does not reach the
other channel, the scale of the loadings, and it is not a full remedy: in the
US sub-model above, centring alone roughly halved how far the error correction
term and the constant moved over the sample and still left the oil price
equation at about 0.8 of the maximum likelihood residual standard deviation in
two chains. Whether a centred model is right is again what the comparison with
least squares shows.
For a model with time varying cointegration parameters
p_tau_i = "ml" centres the marginal prior of the
cointegration space on Johansen's estimate as well, using the informative
marginal prior of Koop et al. (2011, working paper version). The state
equation becomes
with
: the part of
along keeps , the part off it decays
faster, and the mode of the marginal distribution of is
in every period. is chosen so that the prior spread of the
tilt of away from in a period, approximately
, is the sampling variance of
Johansen's estimator with its precision multiplied by weight. The
state before the sample is given the stationary distribution the transition
implies. The transition is stored as element p_tau.
limits how informative this prior can be: even leaves
the tilt a spread of per period, and a weight asking
for more is floored there with a warning.
A larger weight does not always give a tighter posterior. It narrows
the prior spread of the tilt in each period by lowering , but
is also how much of the tilt carries over from one period to the next. As
approaches zero the tilt of each period becomes independent of the
last, the data of neighbouring periods stop informing it, and the posterior
spread of can widen again. On data set E6 with
, for example, weight = 1, which gives
, produced a tighter posterior than weight = 100,
which reaches . The useful range of weight is the one that
keeps clearly above zero, and a closer to one widens it.
A weight so small that
would be the identity in every direction leaves the noninformative
prior unchanged. Both and the prior on the state before the
sample are computed at coint$rho, and do not follow the draw if
is drawn. coint$v_i has no counterpart for these models.
Johansen, S. (1995). Likelihood-based inference in cointegrated vector autoregressive models. Oxford: Oxford University Press.
Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior simulation for cointegrated models with priors on the cointegration space. Econometric Reviews, 29(2), 224–242. doi:10.1080/07474930903382208
Koop, G., León-González, R., & Strachan R. W. (2011). Bayesian inference in a time varying cointegration model. Journal of Econometrics, 165(2), 210–220. doi:10.1016/j.jeconom.2011.07.007
# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 10, burnin = 10) # A prior centred on the maximum likelihood estimate of the space prior <- cointspace_prior(model, coint = list(v_i = 0.01, p_tau_i = "ml")) prior$p_tau_inv# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 10, burnin = 10) # A prior centred on the maximum likelihood estimate of the space prior <- cointspace_prior(model, coint = list(v_i = 0.01, p_tau_i = "ml")) prior$p_tau_inv
Convenience function that combines multiple models into one object.
combine_models(...)combine_models(...)
... |
One or multiple lists that contain either model objects or posterior objects. |
A list of class 'modellist' that holds the models of all arguments in one flat list, in the order in which they were given.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data(e6) # Create multiple VAR models model_1 <- create_bvarmodel(diff(e6), p = 0:2, deterministic = "const") # Create multiple VEC models model_2 <- create_bvecmodel(e6, p = 1, r = 0:1, const = "unrestricted") # Combine the models in one object model <- combine_models(model_1, model_2)# Load data data(e6) # Create multiple VAR models model_1 <- create_bvarmodel(diff(e6), p = 0:2, deterministic = "const") # Create multiple VEC models model_2 <- create_bvecmodel(e6, p = 1, r = 0:1, const = "unrestricted") # Combine the models in one object model <- combine_models(model_1, model_2)
Convenience function, which generates the input data for posterior simulation of covariance parameters.
covar_prepare_data(y, omega_i, k, tt, tvp)covar_prepare_data(y, omega_i, k, tt, tvp)
y |
a |
omega_i |
a |
k |
an integer of the number of endogenous variables. |
tt |
an integer of the number of observations. |
tvp |
logical indicating if the SUR matrix with the values of regressors should be prepared for the estimation of constant or time varying parameters. |
For the model
with and
as a diagonal matrix of error variances, the function produces
the input data for the posterior simulation of the lower triangular covariance coefficients
of as presented in Primiceri (2005).
A list with three elements:
y |
The prepared vector of endogenous variables. |
z |
The prepared matrix of regressors. |
omega_i |
The prepared diagonal matrix of measurement error variances. |
All matrices are returned as sparse matrices.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
Primiceri, G. E. (2005). Time varying structural vector autoregressions and monetary policy. The Review of Economic Studies 72(3), 821–852. doi:10.1111/j.1467-937X.2005.00353.x
k <- 3 tt <- 4 u <- matrix(1:(k * tt)) # Generate simple variance matrix omega_i <- Matrix::Matrix(diag(1:k, k)) # Generate block diagonal variance matrix tv_omega_i <- Matrix::Matrix(0, k * tt, k * tt) for (i in 1:tt) { tv_omega_i[(i - 1) * k + 1:k, (i - 1) * k + 1:k] <- omega_i } # Constant error variances # Constant coefficients covar_prepare_data(u, omega_i, k, tt, FALSE) # Time varying coefficients covar_prepare_data(u, omega_i, k, tt, TRUE) # Time varying error variances # Constant coefficients covar_prepare_data(u, tv_omega_i, k, tt, FALSE) # Time varying coefficients covar_prepare_data(u, tv_omega_i, k, tt, TRUE)k <- 3 tt <- 4 u <- matrix(1:(k * tt)) # Generate simple variance matrix omega_i <- Matrix::Matrix(diag(1:k, k)) # Generate block diagonal variance matrix tv_omega_i <- Matrix::Matrix(0, k * tt, k * tt) for (i in 1:tt) { tv_omega_i[(i - 1) * k + 1:k, (i - 1) * k + 1:k] <- omega_i } # Constant error variances # Constant coefficients covar_prepare_data(u, omega_i, k, tt, FALSE) # Time varying coefficients covar_prepare_data(u, omega_i, k, tt, TRUE) # Time varying error variances # Constant coefficients covar_prepare_data(u, tv_omega_i, k, tt, FALSE) # Time varying coefficients covar_prepare_data(u, tv_omega_i, k, tt, TRUE)
Convenience function, which takes the vector of draws of lower triangular covariance coefficients and transforms it into a matrix with ones on the main diagonal. In case of time varying parameters the resulting matrix will be block diagonal.
covar_vector_to_matrix(psi, k, tt)covar_vector_to_matrix(psi, k, tt)
psi |
a |
k |
the number |
tt |
the number |
A sparse, block diagonal matrix.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
Primiceri, G. E. (2005). Time varying structural vector autoregressions and monetary policy. The Review of Economic Studies 72(3), 821–852. doi:10.1111/j.1467-937X.2005.00353.x
# Create artificial data k <- 5 tt <- 4 n_covar <- (k - 1) * k / 2 # Constant parameters psi <- matrix(1:(n_covar)) covar_vector_to_matrix(psi, k, tt) # Time varying parameters psi <- matrix(1:(n_covar * tt)) covar_vector_to_matrix(psi, k, tt)# Create artificial data k <- 5 tt <- 4 n_covar <- (k - 1) * k / 2 # Constant parameters psi <- matrix(1:(n_covar)) covar_vector_to_matrix(psi, k, tt) # Time varying parameters psi <- matrix(1:(n_covar * tt)) covar_vector_to_matrix(psi, k, tt)
Produces the input for the estimation of a vector autoregressive (VAR) model.
create_bvarmodel( data, p = 2, exogen = NULL, s = 2, deterministic = "const", seasonal = FALSE, iid = NULL, structural = FALSE, error = "wishart", quantile = 0.5, tvp = FALSE, varsel = "none", algorithm = NULL, delta_beta = 1, delta_sigma = 1, iterations = 20000, burnin = 2000, thin = 1, missing = "omit", aggregate = NULL, soft = NULL, quantile_grid = FALSE )create_bvarmodel( data, p = 2, exogen = NULL, s = 2, deterministic = "const", seasonal = FALSE, iid = NULL, structural = FALSE, error = "wishart", quantile = 0.5, tvp = FALSE, varsel = "none", algorithm = NULL, delta_beta = 1, delta_sigma = 1, iterations = 20000, burnin = 2000, thin = 1, missing = "omit", aggregate = NULL, soft = NULL, quantile_grid = FALSE )
data |
a time-series object of endogenous variables. |
p |
an integer vector of the lag order (default is |
exogen |
an optional time-series object of external regressors. |
s |
an integer vector of the lag order of the external regressors (default is |
deterministic |
a character specifying which deterministic terms should
be included. Available values are |
seasonal |
logical. If |
iid |
an optional character vector naming endogenous variables whose
equations carry no coefficients at all – no lags, no deterministic terms,
nothing. They are white noise, and reach the rest of the model only through
the error covariance. They must be the first columns of |
structural |
logical indicating whether data should be prepared for the estimation of a
structural VAR model. Defaults to |
error |
character specifying the model that should be used for the estimation
of the covariance matrix of the error term. Default is |
quantile |
a numeric vector of quantiles in the interval |
tvp |
logical indicating whether the model parameters are time varying.
Defaults to |
varsel |
character specifying the type of variable selection algorithm
that should be employed. Default is |
algorithm |
algorithm that should be used for posterior simulation. If
|
delta_beta, delta_sigma
|
numeric discount factors in |
iterations |
an integer of MCMC draws excluding burn-in draws (defaults to 20000). |
burnin |
an integer of MCMC draws used to initialize the sampler (defaults to 2000). These draws do not enter the computation of posterior moments, forecasts etc. |
thin |
an integer thinning interval of the sampler (defaults to 1). After
the burn-in the sampler keeps the last of every |
missing |
a character, what to do with periods in which a series of
|
aggregate |
an optional named list, one element per series of
|
soft |
an optional character vector of series of |
quantile_grid |
logical. If |
The function produces the data matrices for vector autoregressive (VAR) models, which can also include unmodelled, non-deterministic variables:
where
is a K-dimensional vector of endogenous variables,
is a coefficient matrix of contemporaneous endogenous variables,
is a coefficient matrix of endogenous variables,
is an M-dimensional vector of exogenous regressors and
its corresponding coefficient matrix.
is an N-dimensional vector of deterministic terms and
its corresponding coefficient matrix.
is the lag order of endogenous variables, is the lag
order of exogenous variables, and is an error term.
The model can be rewritten as
where is a data matrix and
the corresponding coefficient vector. Unless structural models are
be estimated, is assumed to be an identity matrix.
If a vector is provided as argument p or s, the function will
produce a distinct model for all possible combinations of those specifications.
If structural = TRUE, the data matrix is augmented by negative
contemporaneous observations of endogenous variables, which correspond to
the coefficients in the lower triangular of .
If tvp is TRUE, the respective coefficients
of the above model are assumed to be time varying. If error is "sv" or "sv+covar",
the error covariance matrix is assumed to be time varying.
Argument error specifies the structure of the covariance matrix of
the error term and how it is estimated. Possible specifications are:
"wishart": The covariance is estimated using a Wishart prior.
"gamma": Only the diagonal elements of the covariance matrix are estimated using a gamma prior.
Off-diagonal elements are not estimated and set to zero.
"gamma+covar": The diagonal elements of the covariance matrix are estimated using a gamma prior.
Covariances are estimated based on a triangular decomposition.
"sv": Only the diagonal elements of the covariance matrix are estimated using a stochastic volatility
algorithm. Off-diagonal elements are not estimated and set to zero.
"sv+covar": Only the diagonal elements of the covariance matrix are estimated using a stochastic volatility
algorithm. Covariances are estimated based on a triangular decomposition.
"ald": The errors are assumed to follow an asymmetric Laplace distribution, which
turns the model into a Bayesian quantile regression: the coefficients describe the conditional
quantile specified in argument quantile instead of the conditional mean. Off-diagonal
elements of the covariance matrix are not estimated and set to zero. See 'Details'.
Models with error = "ald" estimate a conditional quantile after Kozumi and Kobayashi (2011).
Minimising the quantile loss at corresponds to maximising the likelihood of an asymmetric
Laplace distribution, which is a scale mixture of normal distributions. Conditional on the latent
scales of that mixture every equation is a weighted normal regression, which is what makes the
model a Gibbs sampler like the others.
Three properties of these models differ from the rest of the package. Covariances are not
estimated, since rotating the equations into each other leaves a residual whose quantile is not
the one that was asked for. A single quantile does not forecast, since the step ahead quantile is
not the quantile of the iterated one step ahead quantiles. And the asymmetric Laplace is a working
likelihood rather than a claim about the data, so the posterior locates the quantile, but the
spread of the draws is not a calibrated credible interval without the adjustment of Yang et al.
(2016), which is not applied. Variable selection is available as "bvs", not as
"ssvs".
With quantile_grid = TRUE the quantiles in quantile, at least two, form one
model rather than one model each: the structural quantile VAR of Chavleishvili and Manganelli
(2019). Every level is estimated – each is the chain its single-quantile model would have
drawn – and the draws of posterior$a and posterior$u_scale are stacked level by
level, the block of the first quantile first. With structural = TRUE, or a single
variable, the grid describes the whole distribution of each variable given the ones ordered
before it: the estimated quantiles are sorted (Chernozhukov et al., 2010), interpolated linearly
between the levels and continued by exponential tails. That distribution is what
add_posterior_forecasts simulates from, variable by variable, so a grid does
forecast. A scenario given there pins variables in forecast periods, and a
forecast_quantile takes every draw at one level, which gives the quantile paths the
impulse responses of the model are differences of. add_posterior_loglik scores
the density the grid describes. Only models with constant coefficients take a grid. Summaries,
plots and impulse responses work on the single levels, which
split_quantile_grid returns.
Available specifications for argument varsel are:
"none": No variable selection algorithm is used.
"bvs": Bayesian variable selection as proposed in Korobilis (2013).
"ssvs": Stochastic search variable selection as proposed in George et al. (2008).
The one specification for argument algorithm is "discount", the
discounted time varying parameter model of West & Harrison (1997, ch. 16)
with the discounted Wishart of Uhlig (1997), estimated by
VarTvpDiscount. It is not a sampler: its posterior is closed form –
one pass over the sample, no chain – so burnin must be 0 and
thin 1, and iterations says only how many i.i.d. draws a
forecast takes from the answer. Its error covariance is the inverse Wishart
whole, so error must be "wishart" and neither variable
selection nor a structural model is available. What it buys is speed and an
exact marginal likelihood: the sum of /posterior/loglik is the log
marginal likelihood of the sample given the two discounts, so a grid over
them can be compared without a chain being run for any of it.
add_posterior_coefficients estimates it like any other
algorithm, the filter being part of the vendored BayesTS core. It consumes no
random numbers, so two runs agree to the bit and a model estimated here and
the same model estimated by the bayests command line over a file
written with write_to_hdf5 give the same numbers rather than
merely the same distribution. What comes back is a posterior rather than a
chain: one row per period under posterior$a$mean,
posterior$a$cov, posterior$u_sigma$scale and
posterior$df, and no coeffs anywhere, because joining one
draw per period would look like a sampled path and is not one.
Argument iid restricts the equations of the variables it names to
carry no coefficients at all. Such a variable is white noise: nothing
forecasts it, it forecasts nothing, and what the model is estimated for is
its contemporaneous correlation with the errors of the equations that do have
dynamics. That is how a high-frequency surprise becomes a variable of a
monthly VAR rather than an instrument beside one, following Jarocinski and
Karadi (2020).
The restriction is exact rather than a tight prior on those coefficients: the
sampler never draws them, so they are zero in every draw. Everything else
treats the model as an ordinary VAR – the restricted variables are still
regressors in the other equations, the error covariance still covers them,
and irf and fevd read the draws unchanged.
The variables named in iid have to be the first columns of
data, in any order among themselves. The restriction is carried by a
variable's position rather than by a list of positions, which is what lets
the sampler apply it without being told again which coefficients it owns. A
data set in another order is refused with a message naming the columns that
are there instead. It is available for models with constant coefficients and
cannot be combined with structural or varsel.
With missing = "estimate" the panel does not have to be observed
whole. Every observation becomes one linear constraint on the panel, stored
in data$train$constraints, and every sweep of the sampler draws the
periods that were not observed from their distribution given the
constraints, the coefficients and the error covariance before it draws those
(Chan, Poon and Zhu 2023). A series observed at a lower frequency is a
constraint on several periods, the weights of which aggregate gives,
so that a quarterly series enters a monthly model as the average, sum or
growth rate of three months (Schorfheide and Song 2015). Which periods a
constraint reaches is decided by the dates of data, and one that
reaches before the estimation sample is left out with a message. The periods
before the sample that the first lags reach are taken as observed, with gaps
there filled by interpolation. What data$train$y holds where nothing
was observed is a starting value: a linear interpolation of what was.
The draws of the completed panel come back as posterior$y.
A series named in soft holds its constraints up to a normal error
whose precision is estimated with a gamma prior, which
add_prior_options sets. It suits an aggregate whose weights
are an approximation, such as the growth rate of an average.
Estimating what was not observed is available for error = "wishart",
"gamma", "gamma+covar", "sv" and "sv+covar",
with constant or time varying coefficients. It cannot be combined with
structural or the discounted model. It can be combined with
iid, for models with constant coefficients: a variable named there
that was not observed in a period – a high-frequency surprise whose series
starts after the sample does, as in Jarocinski and Karadi (2020) – is drawn
from its white noise given the errors of the other equations, and its gaps
start at zero rather than at an interpolation. Forecasts start from
each draw's completed panel. Forecasts are scored and conditioned on a
scenario in data$forecast$constraints only by models with constant
coefficients and error = "wishart" or "gamma".
An object of class 'bvarmodel' or, if a vector is given in p, s
or quantile, a list of class 'modellist' with one such object per
specification. A 'bvarmodel' is a list with the elements
dataa list with element original, which holds the time-series
objects endogen, exogen and deterministic, and element
train, which holds the estimation sample: y, a
time-series object of the endogenous variables, x, a time-series object of
the regressors, and z, the corresponding row matrix of regressors
in SUR form, which is absent for the discounted model.
modela list of the specification, including type
("VAR"), algorithm, the name of the posterior simulation algorithm,
k, p, m, s and n, the numbers of endogenous
variables, lags, exogenous variables, their lags and deterministic terms,
endogen, the names of the endogenous variables, and deterministic,
structural, error, varsel, tvp, iterations,
burnin, thin if it is above 1, and, for error = "ald",
quantile as specified.
The later steps of the workflow add the elements priors, initial and
posterior.
Chan, J. C. C., Poon, A., & Zhu, D. (2023). High-dimensional conditionally Gaussian state space models with missing data. Journal of Econometrics, 236(1), 105468. doi:10.1016/j.jeconom.2023.05.005
Chan, J., Koop, G., Poirier, D. J., & Tobias, J. L. (2019). Bayesian Econometric Methods (2nd ed.). Cambridge: University Press.
Chavleishvili, S., & Manganelli, S. (2019). Forecasting and stress testing with quantile vector autoregression. ECB Working Paper, 2330.
Chernozhukov, V., Fernandez-Val, I., & Galichon, A. (2010). Quantile and probability curves without crossing. Econometrica, 78(3), 1093–1125.
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271
Kozumi, H., & Kobayashi, G. (2011). Gibbs sampling methods for Bayesian quantile regression. Journal of Statistical Computation and Simulation, 81(11), 1565–1578. doi:10.1080/00949655.2010.496117
Schorfheide, F., & Song, D. (2015). Real-time forecasting with a mixed-frequency VAR. Journal of Business & Economic Statistics, 33(3), 366–380. doi:10.1080/07350015.2014.954707
Lütkepohl, H. (2006). New Introduction to Multiple Time Series Analysis (2nd ed.). Berlin: Springer.
Uhlig, H. (1997). Bayesian vector autoregressions with stochastic volatility. Econometrica, 65(1), 59–73. doi:10.2307/2171813
West, M., & Harrison, J. (1997). Bayesian forecasting and dynamic models (2nd ed.). New York: Springer.
bvartools_model describes the object this returns, element by element.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 50, burnin = 10) # Number of iterations and burnin should be much higher.# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 50, burnin = 10) # Number of iterations and burnin should be much higher.
Produces the input for the estimation of a vector error correction (VEC) model.
create_bvecmodel( data, p, exogen = NULL, s = NULL, r = NULL, const = NULL, trend = NULL, seasonal = NULL, structural = FALSE, error = "wishart", tvp = FALSE, varsel = "none", algorithm = NULL, delta_beta = 1, delta_sigma = 1, iterations = 20000, burnin = 2000, thin = 1 )create_bvecmodel( data, p, exogen = NULL, s = NULL, r = NULL, const = NULL, trend = NULL, seasonal = NULL, structural = FALSE, error = "wishart", tvp = FALSE, varsel = "none", algorithm = NULL, delta_beta = 1, delta_sigma = 1, iterations = 20000, burnin = 2000, thin = 1 )
data |
a time-series object of endogenous variables. |
p |
an integer vector of the lag order of the endogenous variables in the
corresponding VAR in levels, which must be at least 1. Following common convention,
the resulting VEC model contains |
exogen |
an optional time-series object of external regressors. |
s |
an integer vector of the lag order of the exogenous variables in the
corresponding VAR in levels, which must be at least 1. The resulting VEC model contains
the contemporaneous difference of the exogenous variables and |
r |
an integer vector of the cointegration rank. See 'Details'. |
const |
a character specifying whether a constant term enters the error correction
term ( |
trend |
a character specifying whether a trend term enters the error correction
term ( |
seasonal |
a character specifying whether seasonal dummies should be included in the error
correction term ( |
structural |
logical indicating whether data should be prepared for the estimation of a
structural VEC model, whose lower triangular matrix |
error |
character specifying the model that should be used for the estimation
of the covariance matrix of the error term. Default is |
tvp |
logical indicating whether the model parameters are time varying. |
varsel |
character specifying the type of variable selection algorithm
that should be employed. Default is |
algorithm |
algorithm that should be used for posterior simulation. If |
delta_beta, delta_sigma
|
numeric discount factors in |
iterations |
an integer of MCMC draws excluding burn-in draws (defaults to 20000). |
burnin |
an integer of MCMC draws used to initialize the sampler (defaults to 2000). These draws do not enter the computation of posterior moments, forecasts etc. |
thin |
an integer thinning interval of the sampler (defaults to 1). After
the burn-in the sampler keeps the last of every |
The function produces the variable matrices of vector error correction (VEC) models, which can also include exogenous variables:
where
is a vector of differenced endogenous variables,
is a vector of cointegration variables,
is a matrix of cointegration parameters,
is a coefficient matrix of endogenous variables,
is a vector of differenced exogenous regressors,
is a coefficient matrix of exogenous regressors,
is a vector of deterministic terms, and
is a coefficient matrix of deterministic terms
that do not enter the cointegration term.
is the lag order of endogenous variables and is the lag
order of exogenous variables of the corresponding VAR model.
is a error term.
If an integer vector is provided as argument p, s or r, the function will
produce a distinct model for all possible combinations of those specifications.
Argument error specifies the structure of the covariance matrix of
the error term and how it is estimated. Possible specifications are:
"wishart": The covariance is estimated using a Wishart prior.
"gamma": Only the diagonal elements of the covariance matrix are estimated using a gamma prior.
Off-diagonal elements are not estimated and set to zero.
"gamma+covar": The diagonal elements of the covariance matrix are estimated using a gamma prior.
Covariances are estimated based on a triangular decomposition.
"sv": Only the diagonal elements of the covariance matrix are estimated using a stochastic volatility
algorithm. Off-diagonal elements are not estimated and set to zero.
"sv+covar": Only the diagonal elements of the covariance matrix are estimated using a stochastic volatility
algorithm. Covariances are estimated based on a triangular decomposition.
Available specifications for argument varsel are:
"none": No variable selection algorithm is used.
"bvs": Bayesian variable selection as proposed in Korobilis (2013).
"ssvs": Stochastic search variable selection as proposed in George et al. (2008).
Available specifications for argument algorithm are:
"KLGS2010": Algorithm proposed in Koop, León-González & Strachan (2010).
"discount": The discounted time varying parameter model of
West & Harrison (1997, ch. 16) with the discounted Wishart of Uhlig (1997),
estimated by VecTvpDiscount.
The discounted model is not a sampler. Its posterior is closed form – one
pass over the sample, no chain – so burnin must be 0 and thin
1, and iterations says only how many i.i.d. draws a forecast takes
from the answer. Its error covariance is the inverse Wishart whole, so
error must be "wishart" and neither variable selection nor a
structural model is available. What it buys is speed and an exact marginal
likelihood: the sum of /posterior/loglik is the log marginal
likelihood of the sample given the rank, the cointegration matrix and the two
discounts, so a grid over any of them can be compared without a chain being
run for any of it.
The one assumption that separates it from the sampling VEC models is that the
cointegration space is given rather than estimated. add_initial_values
puts Johansen's maximum likelihood estimate at /initial/beta and the
model conditions on it, so what drifts is the adjustment to the long-run
relations and not the relations themselves. That is a different question from
the one "KLGS2010" answers, not a cheaper way of answering the same
one.
add_posterior_coefficients estimates it like any other
algorithm, the filter being part of the vendored BayesTS core. It consumes no
random numbers, so two runs agree to the bit and a model estimated here and
the same model estimated by the bayests command line over a file
written with write_to_hdf5 give the same numbers rather than
merely the same distribution. What comes back is a posterior rather than a
chain: one row per period under posterior$a$mean,
posterior$a$cov, posterior$u_sigma$scale and
posterior$df, and no coeffs anywhere, because joining one
draw per period would look like a sampled path and is not one.
An object of class 'bvecmodel' or, if a vector is given in p, s
or r, a list of class 'modellist' with one such object per specification. A
'bvecmodel' is a list with the elements
dataa list with element original, which holds the time-series
objects endogen, exogen and deterministic in levels, and
element train, which holds the estimation sample: y, a
time-series object of the differenced endogenous variables,
w, the lagged levels that enter the cointegration term, x, the
remaining regressors, and z, the corresponding row matrix of
regressors in SUR form, which is absent for the discounted model.
modela list of the specification with the same elements as that of
a 'bvarmodel', where type is "VEC" and p is the lag order of
the VAR in levels, and additionally rank, the cointegration rank,
k_beta, the number of variables in the cointegration term, and
n_restricted, the number of deterministic terms restricted to it.
The later steps of the workflow add the elements priors, initial and
posterior.
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior simulation for cointegrated models with priors on the cointegration space. Econometric Reviews, 29(2), 224–242. doi:10.1080/07474930903382208
Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Uhlig, H. (1997). Bayesian vector autoregressions with stochastic volatility. Econometrica, 65(1), 59–73. doi:10.2307/2171813
West, M., & Harrison, J. (1997). Bayesian forecasting and dynamic models (2nd ed.). New York: Springer.
bvartools_model describes the object this returns, element by element.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
transform_variables(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted", iterations = 10, burnin = 10) # Number of iterations and burn-in should be much higher.# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 4, r = 1, const = "unrestricted", seasonal = "unrestricted", iterations = 10, burnin = 10) # Number of iterations and burn-in should be much higher.
Turns externally produced point forecasts into an object, which can be evaluated and compared with the forecasts of Bayesian VAR and VEC models.
create_external_forecast( forecasts, object, n_ahead = NULL, period = "period", origin = "origin", variable = "variable", value = "value", by = NULL, data_lag = 1, select = "last" ) ## S3 method for class 'externalforecast' add_priors(object, ...) ## S3 method for class 'externalforecast' add_initial_values(object, ...) ## S3 method for class 'externalforecast' add_seed(object, seed, ...) ## S3 method for class 'externalforecast' add_posterior_coefficients(object, ...) ## S3 method for class 'externalforecast' add_posterior_loglik(object, ...) ## S3 method for class 'externalforecast' add_forecast_input(object, ...) ## S3 method for class 'externalforecast' add_posterior_forecasts(object, ...) ## S3 method for class 'externalforecast' minnesota_prior(object, ...) ## S3 method for class 'externalforecast' ssvs_prior(object, ...) ## S3 method for class 'externalforecast' inclusion_prior(object, ...) ## S3 method for class 'externalforecast' thin(x, thin = 10, ...) ## S3 method for class 'externalforecast' print(x, digits = max(3L, getOption("digits") - 3L), ...)create_external_forecast( forecasts, object, n_ahead = NULL, period = "period", origin = "origin", variable = "variable", value = "value", by = NULL, data_lag = 1, select = "last" ) ## S3 method for class 'externalforecast' add_priors(object, ...) ## S3 method for class 'externalforecast' add_initial_values(object, ...) ## S3 method for class 'externalforecast' add_seed(object, seed, ...) ## S3 method for class 'externalforecast' add_posterior_coefficients(object, ...) ## S3 method for class 'externalforecast' add_posterior_loglik(object, ...) ## S3 method for class 'externalforecast' add_forecast_input(object, ...) ## S3 method for class 'externalforecast' add_posterior_forecasts(object, ...) ## S3 method for class 'externalforecast' minnesota_prior(object, ...) ## S3 method for class 'externalforecast' ssvs_prior(object, ...) ## S3 method for class 'externalforecast' inclusion_prior(object, ...) ## S3 method for class 'externalforecast' thin(x, thin = 10, ...) ## S3 method for class 'externalforecast' print(x, digits = max(3L, getOption("digits") - 3L), ...)
forecasts |
a data frame in long format, which contains the external point forecasts. See 'Details' for the required columns. |
object |
for |
n_ahead |
the maximum forecast horizon that is considered. If |
period |
name of the column of |
origin |
name of the column of |
variable |
name of the column of |
value |
name of the column of |
by |
name of an optional column of |
data_lag |
an integer specifying the number of periods, by which the publication of the data of the endogenous variables lags behind. See 'Details'. |
select |
either |
... |
arguments passed forward to method. |
seed |
not used, since external forecasts are not simulated. |
x |
an object of class 'externalforecast'. |
thin |
an integer specifying the thinning interval between successive draws. |
digits |
the number of significant digits. |
Argument forecasts must be a data frame in long format, where each row
contains a single point forecast. The names of the required columns can be
specified in the arguments period, origin, variable and
value. Periods can be provided either as objects of class 'Date' or as
numerics, which follow the convention of time, i.e. 2007.25
for the second quarter of 2007. The periods, for which a forecast was made, are
rounded to the frequency of the data of the models in object.
Rounding places a forecast in the period of the data it falls into; it does not convert between frequencies. Forecasts made at a frequency other than that of the data are therefore refused: annual forecasts of a quarterly model, whose periods such as 2020 and 2021 would otherwise be read as the first quarters of those years and an annual growth rate scored as a quarterly one, or monthly forecasts of a quarterly model, of which three would fall into the same quarter. The frequency of the forecasts is read off the spacing of the periods within a publication and, where every publication forecasts a single period, off the position of the periods within the year.
Annual forecasts are compared with models estimated on quarterly or monthly
data by aggregating the forecasts of the models to annual figures with
aggregate_forecasts first and passing the result as argument
object. The periods of the forecasts are then read as years, while
publications are still matched to the training samples at the frequency of the
data, and data_lag still counts periods of the data. Horizon 1 is the
year of the first period after the training sample, so that a forecast for the
year of its publication is a forecast of horizon 1 and one for the year after
it of horizon 2, whichever quarter it was published in. The realised values,
against which the forecasts are scored, are the annual figures of the data of
the models, which the aggregated forecasts of the models are scored against,
too, so that add_forecast_errors does not need argument
test_sample.
In contrast to a model, an external forecast does not have a training sample.
Therefore, each publication is matched to the training sample, which ends closest
before the publication of the forecast, so that a model and an external forecaster
are evaluated on comparable information sets. Since the data of the endogenous
variables are usually published with a delay, argument data_lag can be used
to specify the number of periods, by which the last available observation lags
behind the publication of a forecast. Thus, a publication is matched to the last
training sample, which does not end after origin - data_lag periods. With
the default of one period an annual forecast, which was published in the course of
2021, is matched to a training sample that ends in 2020, so that the forecast for
2021 is a one-step ahead forecast.
If multiple publications are matched to the same training sample, only one of them
is used, because otherwise a forecaster would enter the comparison multiple times
for the same period. Argument select controls whether the latest
("last") or the earliest ("first") of those publications is used.
The resulting object mimics the structure of a model, which was estimated with the
expanding window approach of use_expanding_window, where each
publication corresponds to one estimation window. It can be added to a list of
models with combine_models and the functions, which are applied to
obtain posterior draws, are without effect for it. Since external forecasts are
point forecasts, their forecast errors consist of a single draw. Accordingly, the
credible bands of the out-of-sample statistics in selection_criteria
are degenerate and in-sample criteria are not available.
External forecasts do not have to be estimated, so the functions, which add priors, initial values or posterior draws to a model are without effect for objects of class 'externalforecast'. This allows to combine them with model objects in a list of class 'modellist' and to apply the usual workflow to all elements of that list.
A list of class 'externalforecast' or, if argument by is specified,
a list of class 'modellist', which contains one object of class 'externalforecast'
per forecaster.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("us_macrodata") # Create model model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. model <- use_expanding_window(model, start = 2007) # Artificial external forecasts of two forecasters fcst <- expand.grid(origin = c(2007, 2007.25), h = 1:2, variable = c("Dp", "r"), forecaster = c("A", "B"), stringsAsFactors = FALSE) fcst[["period"]] <- fcst[["origin"]] + fcst[["h"]] / 4 fcst[["value"]] <- 0 # Create objects of the external forecasts, where the data of the endogenous # variables are assumed to be published with a delay of one quarter ext <- create_external_forecast(fcst, model, n_ahead = 4, by = "forecaster", data_lag = 1) # Calculate forecast errors ext <- add_forecast_errors(ext, test_sample = us_macrodata) # Compare the forecast performance selection_criteria(ext)data("us_macrodata") # Create model model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. model <- use_expanding_window(model, start = 2007) # Artificial external forecasts of two forecasters fcst <- expand.grid(origin = c(2007, 2007.25), h = 1:2, variable = c("Dp", "r"), forecaster = c("A", "B"), stringsAsFactors = FALSE) fcst[["period"]] <- fcst[["origin"]] + fcst[["h"]] / 4 fcst[["value"]] <- 0 # Create objects of the external forecasts, where the data of the endogenous # variables are assumed to be published with a delay of one quarter ext <- create_external_forecast(fcst, model, n_ahead = 4, by = "forecaster", data_lag = 1) # Calculate forecast errors ext <- add_forecast_errors(ext, test_sample = us_macrodata) # Compare the forecast performance selection_criteria(ext)
Whether a model is one of the two discounted models, and what a discounted model cannot be. Both are exported for the packages that build a model of their own on this one and have to make the same distinction.
is_discount_model(x) check_discount_specification( k, error = "wishart", varsel = "none", structural = FALSE, burnin = 0, thin = 1, delta_beta = 1, delta_sigma = 1 )is_discount_model(x) check_discount_specification( k, error = "wishart", varsel = "none", structural = FALSE, burnin = 0, thin = 1, delta_beta = 1, delta_sigma = 1 )
x |
a model, a specification list – the |
k |
the number of endogenous variables. |
error, varsel, structural, burnin, thin
|
the corresponding arguments of
|
delta_beta, delta_sigma
|
the two discount factors. |
VarTvpDiscount and VecTvpDiscount are the matrix normal
dynamic linear model of West & Harrison (1997, ch. 16) with the discounted
Wishart of Uhlig (1997). Their posterior is closed form – one pass over the
sample, no chain, no random numbers consumed – which is what every refusal
below follows from. See create_bvecmodel for what they are and
how they are set up.
check_discount_specification raises an error for a specification a
discounted model cannot carry and returns nothing otherwise. Each refusal is
one BayesTS would raise as well, against a file that had already been
written; raising it here means one error for a grid of models rather than one
per file.
is_discount_model returns a single logical.
check_discount_specification returns NULL invisibly.
Uhlig, H. (1997). Bayesian vector autoregressions with stochastic volatility. Econometrica, 65(1), 59–73. doi:10.2307/2171813
West, M., & Harrison, J. (1997). Bayesian forecasting and dynamic models (2nd ed.). New York: Springer.
data("e6") model <- create_bvecmodel(e6 * 100, p = 2, r = 1, const = "unrestricted", algorithm = "discount", delta_beta = 0.98, iterations = 10, burnin = 0, thin = 1) is_discount_model(model) is_discount_model("VecNormalWishart")data("e6") model <- create_bvecmodel(e6 * 100, p = 2, r = 1, const = "unrestricted", algorithm = "discount", delta_beta = 0.98, iterations = 10, burnin = 0, thin = 1) is_discount_model(model) is_discount_model("VecNormalWishart")
The data set contains quarterly, seasonally adjusted time series for West German fixed investment, disposable income, and consumption expenditures in billions of DM from 1960Q1 to 1982Q4. It was produced from file E1 of the data sets associated with Lütkepohl (2006). Raw data are available at http://www.jmulti.de/download/datasets/e1.dat and were originally obtained from Deutsche Bundesbank.
data("e1")data("e1")
A named time-series object with 92 rows and 3 variables:
fixed investment.
disposable income.
consumption expenditures.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
The data set contains quarterly, seasonally unadjusted time series for German long-term interest and inflation rates from 1972Q2 to 1998Q4. It was produced from file E6 of the data sets associated with Lütkepohl (2006). Raw data are available at http://www.jmulti.de/download/datasets/e6.dat and were originally obtained from Deutsche Bundesbank and Deutsches Institut für Wirtschaftsforschung.
data("e6")data("e6")
A named time-series object with 107 rows and 2 variables:
nominal long-term interest rate (Umlaufsrendite).
log of GDP deflator.
The data cover West Germany until 1990Q2 and all of Germany aferwards. The values refer to the last month of a quarter.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
A generic function that calculates how much memory a model will take once its posterior draws are complete, and so roughly how much disk space it will take when written to a file.
expected_model_size(object, ...)expected_model_size(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
The functions that draw or write a model warn before they start when
the result would exceed the limit set by options(bvartools.size_warning),
in bytes, which is 1e9, one gigabyte, unless set otherwise, and Inf
turns the warnings off. add_posterior_coefficients checks the
size expected_model_size() predicts for the draws it is about to simulate,
and write_to_hdf5 checks the size of the object it is about to
write. A package that adds a model class gets both warnings by adding a method
to this generic.
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: expected_model_size.bvarmodel,
expected_model_size.bvecmodel,
expected_model_size.expandingwindow,
expected_model_size.modellist.
Calculates how much memory a model will take once its posterior draws are complete, block by block, from its specification alone, so that it can be called before a long estimation is started.
## S3 method for class 'bvarmodel' expected_model_size(object, chains = NULL, ...) ## S3 method for class 'bvecmodel' expected_model_size(object, chains = NULL, ...) ## S3 method for class 'expandingwindow' expected_model_size(object, ...) ## S3 method for class 'modellist' expected_model_size(object, ...)## S3 method for class 'bvarmodel' expected_model_size(object, chains = NULL, ...) ## S3 method for class 'bvecmodel' expected_model_size(object, chains = NULL, ...) ## S3 method for class 'expandingwindow' expected_model_size(object, ...) ## S3 method for class 'modellist' expected_model_size(object, ...)
object |
an object of class 'bvarmodel' or 'bvecmodel', usually a result
of a call to |
chains |
the number of chains that will be simulated. If |
... |
further arguments passed to or from other methods. |
Every block of posterior draws is a matrix of numbers with one row per
kept draw, and each number takes eight bytes. How many draws are kept is set by
iterations, how many columns each block has by the specification: the
number of coefficients, whether they vary over time, the error distribution,
variable selection and the rank of a VEC model. Time-varying parameters
and stochastic volatility multiply the size of a block by the number of
periods in the sample, which is how a model that is small as a constant
coefficient model can need gigabytes.
A few blocks depend on the priors: the inclusion indicators of the covariance
block, the draws of a non-centred prior (omega_v) and a drawn
autocorrelation of the cointegration space (rho_min). They are counted
once add_priors has added the priors. Forecast draws are counted
once add_forecast_input has set a horizon.
The numbers are what the object will hold in memory. R may briefly hold a
second copy while a step modifies it, so the memory a session needs can be up
to twice as large. write_to_hdf5 compresses what it writes, but
posterior draws compress poorly, so the size of the file is usually a little
below the size in memory.
A data frame of class 'modelsize' with one row per block of the object and the columns
modelfor a list of models, the name or position of the model.
elementwhere the block will be in the object, such as
posterior$a$coeffs. The first row of each model is everything that is
there already, the data, the priors and the initial values.
stepthe function that adds the block, empty for the first row.
The warning of add_posterior_coefficients counts the first row
and the blocks that function adds itself.
draws, columns
the dimensions of the block.
bytesthe size of the block in bytes.
sum(result$bytes) is the expected size of the whole object, and the
print method shows it by step.
expected_model_size for the warnings that are based on it, and
bvartools_model for the blocks of the object.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # A model with constant coefficients and one with time-varying parameters # and stochastic volatility model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 5000, burnin = 1000) expected_model_size(model) model <- create_bvarmodel(e1, p = 2, deterministic = "const", tvp = TRUE, error = "sv", iterations = 5000, burnin = 1000) expected_model_size(model) # The total in bytes sum(expected_model_size(model)$bytes)# Load data data("e1") e1 <- diff(log(e1)) * 100 # A model with constant coefficients and one with time-varying parameters # and stochastic volatility model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 5000, burnin = 1000) expected_model_size(model) model <- create_bvarmodel(e1, p = 2, deterministic = "const", tvp = TRUE, error = "sv", iterations = 5000, burnin = 1000) expected_model_size(model) # The total in bytes sum(expected_model_size(model)$bytes)
A generic function used to calculate forecast error variance decompositions.
fevd(x, ...)fevd(x, ...)
x |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of x,
as described on the pages of the methods.
Methods: fevd.bvarmodel.
Produces the forecast error variance decomposition for an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' fevd( x, response = NULL, n_ahead = 5, type = "oir", normalise_gir = FALSE, period = NULL, max_groups = NULL, impact = NULL, statistic = "mean", ci = NULL, ... )## S3 method for class 'bvarmodel' fevd( x, response = NULL, n_ahead = 5, type = "oir", normalise_gir = FALSE, period = NULL, max_groups = NULL, impact = NULL, statistic = "mean", ci = NULL, ... )
x |
an object of class 'bvarmodel'. |
response |
name of the response variable. |
n_ahead |
number of steps ahead. Zero is allowed and returns the decomposition on impact alone. |
type |
type of the impulse responses used to calculate forecast error variable decompositions.
Possible choices are orthogonalised |
normalise_gir |
logical. Should the GIR-based FEVD be normalised? |
period |
integer. Index of the period, for which the variance decomposition should be generated.
Only used for TVP or SV models. Default is |
max_groups |
integer. Maximum number of variables the decomposition should contain.
The |
impact |
the impact matrix of a |
statistic |
the posterior summary of each share, |
ci |
an optional probability, the coverage of a credible interval returned
alongside, such as |
... |
further arguments passed to or from other methods. |
The function produces forecast error variance decompositions (FEVD) for the VAR model
with . For non-structural models matrix is set to the identiy matrix
and can therefore be omitted, where not relevant.
For a structural model the posterior draws describe the structural form, so only "sir" and
"sgir", which invert , recover the reduced form the recursion for
needs. The other types are therefore not available for a structural model, and the two structural
types not for any other.
If the FEVD is based on the orthogonalised impulse resonse (OIR), the FEVD will be calculated as
where is the forecast error impulse response for the th period,
is the lower triangular Choleski decomposition of the variance-covariance
matrix , is a selection vector for the response variable and
a selection vector for the impulse variable.
If type = "sign", the decomposition uses , with the rotation that
add_sign_restrictions accepted for that draw, and is otherwise the orthogonalised
case. A rotation of the Choleski factor still factorises , so the shares add up as
they do there. Draws that no admissible rotation was found for are left out.
If type = "custom", the decomposition uses the matrix supplied in argument
impact in place of the Choleski factor, while the denominator stays the one of the
orthogonalised case: an impact matrix relabels the shocks but says nothing about the model,
so the forecast error variance being decomposed is still that of . The shares
therefore add up to one across shocks exactly when , which holds
for a rotation of the Choleski factor and need not hold for an arbitrary matrix. This is not
enforced: a decomposition that does not sum to one is the honest report of an impact matrix
that does not factorise .
If type = "sir", the structural FEVD will be
calculated as
where is the lower triangular Choleski decomposition of . Since
is the covariance matrix of the structural errors, the decomposition weighs each structural
shock by its own variance.
If type = "gir", the generalised FEVD of Pesaran and Shin (1998) will be
calculated as
where is the variance of the error of the impulse variable , the
diagonal element of that belongs to the shock. This is the decomposition that
spillover is built on.
If type = "sgir", the structural generalised FEVD will be
calculated as
where is the covariance matrix of the structural errors and the
variance of the structural shock .
Since GIR-based FEVDs do not add up to unity, they can be normalised by setting normalise_gir = TRUE,
which divides each row by its sum after the decomposition has been averaged over the posterior
draws. spillover normalises each draw before averaging, so its shares differ from
these by the difference between a ratio of means and a mean of ratios.
The row of period sums the impulse responses of periods 0 to , so it is the
decomposition of the step forecast error variance. Period 0 is the decomposition
on impact.
A time-series object of class 'bvarfevd' running from period 0 to n_ahead,
with one column per variable holding the share of the forecast error variance of
response that is due to its shocks. For type = "oir" the rows sum to
one; for type = "gir" they do so only with normalise_gir = TRUE.
With ci, attributes lower and upper hold the bounds of the credible
interval of each share in the same shape. With statistic = "median" or ci, a
GIR-based decomposition is normalised draw by draw rather than after averaging, and the
medians need not sum to one. ci cannot be combined with max_groups, since the
bounds of a pooled column are not the pooled bounds.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Pesaran, H. H., & Shin, Y. (1998). Generalized impulse response analysis in linear multivariate models. Economics Letters, 58, 17-29.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Obtain FEVD vd <- fevd(object, response = "cons") # Plot FEVD plot(vd)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Obtain FEVD vd <- fevd(object, response = "cons") # Plot FEVD plot(vd)
Guard method for objects of class 'bvecmodel'.
## S3 method for class 'bvecmodel' fevd(x, ...)## S3 method for class 'bvecmodel' fevd(x, ...)
x |
an object of class 'bvecmodel'. |
... |
additional arguments. |
Nothing. The method raises an error, since variance decompositions of a VEC model
are obtained from its VAR representation: apply vec_to_var first and then
fevd to the resulting 'bvarmodel'.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
The steps of an estimation, applied to the models of a folder one at a time rather than to a list of models in the session. Each reads a model, changes it, writes it back and drops it, so a step costs one model per worker.
## S3 method for class 'bvarfolder' add_priors(object, ..., cores = 1) ## S3 method for class 'bvarfolder' add_initial_values(object, ..., cores = 1) ## S3 method for class 'bvarfolder' add_seed(object, seed, ..., cores = 1) ## S3 method for class 'bvarfolder' add_posterior_coefficients(object, ..., cores = 1, export = NULL) ## S3 method for class 'bvarfolder' add_posterior_loglik(object, ..., cores = 1) ## S3 method for class 'bvarfolder' thin(x, ..., cores = 1) ## S3 method for class 'bvarfolder' selection_criteria(object, ..., cores = 1) ## S3 method for class 'bvarfolder' time_variation_test(object, ..., cores = 1)## S3 method for class 'bvarfolder' add_priors(object, ..., cores = 1) ## S3 method for class 'bvarfolder' add_initial_values(object, ..., cores = 1) ## S3 method for class 'bvarfolder' add_seed(object, seed, ..., cores = 1) ## S3 method for class 'bvarfolder' add_posterior_coefficients(object, ..., cores = 1, export = NULL) ## S3 method for class 'bvarfolder' add_posterior_loglik(object, ..., cores = 1) ## S3 method for class 'bvarfolder' thin(x, ..., cores = 1) ## S3 method for class 'bvarfolder' selection_criteria(object, ..., cores = 1) ## S3 method for class 'bvarfolder' time_variation_test(object, ..., cores = 1)
object |
an object of class 'bvarfolder', from
|
... |
further arguments passed to the method for a single model. |
cores |
the number of worker processes. Defaults to one. |
seed |
an integer, the seed of the first model. The models are numbered through in the order of the manifest, as the models of a list are. |
export |
character vector of names of objects the workers need, for
instance the sampler that |
x |
an object of class 'bvarfolder'. |
The methods do what their counterparts for a 'bvarmodel' or a 'bvecmodel' do, model by model, and they take the same arguments.
Each model is drawn with a seed of its own, so the draws do not depend on how
many workers a step runs on, nor on whether the models were estimated in one
run or in several. The seeds are the ones a list of models gets from
add_seed: seed, seed + 1, and so on in the order
of the manifest.
A step takes models, which map_models understands: a
character vector of the models it is applied to, the rest of the folder being
left as it is. An estimation of many expensive models is run in parts that
way, and one that was interrupted is picked up where it stopped.
add_posterior_coefficients is the step to think twice about. It writes
the largest thing a model has, and a cluster of R workers carries every draw
into the session and out again to do it. Where the sampler is the BayesTS
executable, bayests_files runs it on the files instead:
run <- bayests_files(executable = "/opt/bayests/bin/bayests") run(model_files(stored), jobs = 6)
which gives the same draws, since a model is drawn with the seed in its file.
selection_criteria and time_variation_test are the methods that
read rather than write: they hand back a result per model and leave the folder
as it is. The first is what choose_best_model compares, so a grid
of specifications too large to hold is still chosen from; the second gives the
Bayes factors for time variation of every model of the folder, which is how a
grid of time varying models is asked whether its coefficients move at all.
The object in object, with its manifest brought up to date.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("e1") train <- diff(log(e1)) * 100 models <- create_bvarmodel(data = train, p = 1:2, deterministic = "const", iterations = 20, burnin = 10) folder <- file.path(tempdir(), "bvartools-example-steps") unlink(folder, recursive = TRUE) dir.create(folder, recursive = TRUE) write_to_hdf5(models, folder = folder) stored <- open_models(folder) stored <- add_priors(stored, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) stored <- add_initial_values(stored) stored <- add_seed(stored, 20260919) stored <- add_posterior_coefficients(stored) stored <- add_posterior_loglik(stored)data("e1") train <- diff(log(e1)) * 100 models <- create_bvarmodel(data = train, p = 1:2, deterministic = "const", iterations = 20, burnin = 10) folder <- file.path(tempdir(), "bvartools-example-steps") unlink(folder, recursive = TRUE) dir.create(folder, recursive = TRUE) write_to_hdf5(models, folder = folder) stored <- open_models(folder) stored <- add_priors(stored, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) stored <- add_initial_values(stored) stored <- add_seed(stored, 20260919) stored <- add_posterior_coefficients(stored) stored <- add_posterior_loglik(stored)
The step of read_model_from_hdf5 that turns what
read_bayests_tree reads into the object of a model package.
from_bayests_tree(tree, ...) ## Default S3 method: from_bayests_tree(tree, ...)from_bayests_tree(tree, ...) ## Default S3 method: from_bayests_tree(tree, ...)
tree |
the tree of a model file, as |
... |
further arguments passed to or from other methods. |
read_model_from_hdf5 reads the VAR and VEC models of this
package itself. For a file whose rclass names any other class it
reads the tree, gives it that class and calls this generic, so a package
that writes its models with write_bayests_tree reads them
back by registering a method for its class. The method undoes the
translation its writer made: names, orderings and shapes that BayesTS
wants and the package's object does not.
The package named in the file's /model/rpackage is loaded first,
if it is installed, so that its methods are registered whether or not it
is attached. A file of the BayesTS command line carries no such attribute;
one of a factor model is read with dfmtools loaded.
Without a method the default refuses, and names the class it found no method for.
A method keeps the attributes of /model it does not know
in element model of what it returns. write_to_hdf5
records there where a model stood in the 'modellist' it was written from,
and read_models_from_folder rebuilds the list from it.
An object of the class of tree, as its package defines it.
Generates an artificial data set from a vector autoregressive model with constant or time varying parameters and constant or stochastic volatility, for testing the algorithms of the package.
generate_artificial_var( nobs = 100, k = 3, p = 2, deterministic = "none", structural = FALSE, tvp = FALSE, sv = FALSE, range_a = c(-0.5, 0.5), a_zeros = 0.5, range_a0 = c(-0.5, 0.5), range_const = c(-0.5, 0.5), range_trend = c(-0.01, 0.01), range_variance = c(1, 1), range_psi = c(0, 0), range_variance_state = c(1e-04, 1e-04), range_variance_sv = c(0.01, 0.01), stable = TRUE, presample = 100, level = 0 )generate_artificial_var( nobs = 100, k = 3, p = 2, deterministic = "none", structural = FALSE, tvp = FALSE, sv = FALSE, range_a = c(-0.5, 0.5), a_zeros = 0.5, range_a0 = c(-0.5, 0.5), range_const = c(-0.5, 0.5), range_trend = c(-0.01, 0.01), range_variance = c(1, 1), range_psi = c(0, 0), range_variance_state = c(1e-04, 1e-04), range_variance_sv = c(0.01, 0.01), stable = TRUE, presample = 100, level = 0 )
nobs |
number of generated observations. Defaults to 100. |
k |
number of endogenous variables. Defaults to 3. |
p |
number of lags of the VAR model. Can be zero. Defaults to 2. |
deterministic |
a character specifying which deterministic terms the
model contains: |
structural |
logical specifying whether a structural VAR model with a lower
triangular matrix |
tvp |
logical specifying whether the coefficients, |
sv |
logical specifying whether the error variances follow a stochastic
volatility process. Defaults to |
range_a |
numeric vector with two elements containing the minimum and
maximum value of the coefficients of lagged endogenous variables. Defaults
to |
a_zeros |
numeric between 0 and 1 indicating the share of coefficients
of lagged endogenous variables, which should be set to zero. Default is |
range_a0 |
numeric vector with two elements containing the minimum and
maximum value of the free elements of |
range_const |
numeric vector with two elements containing the minimum and
maximum value of the intercept terms. Defaults to |
range_trend |
numeric vector with two elements containing the minimum and
maximum value of the coefficients of the linear trend. Defaults to |
range_variance |
numeric vector with two elements containing the minimum and
maximum value of the error variances. For |
range_psi |
numeric vector with two elements containing the minimum and
maximum value of the free elements of |
range_variance_state |
numeric vector with two elements containing the minimum and
maximum value of the variances of the state equations of the coefficients, of
|
range_variance_sv |
numeric vector with two elements containing the minimum and
maximum value of the variances of the state equations of the log-volatilities.
Only used if |
stable |
logical specifying whether the coefficients of lagged endogenous
variables are restricted to a stable VAR process. Defaults to |
presample |
numeric specifying the number of observations, which are generated before the first returned observation and then discarded, so that the series do not depend on their initial values. Defaults to 100. |
level |
numeric vector with one or |
The function produces artificial observations for a vector autoregressive (VAR) model:
where
is a K-dimensional vector of endogenous variables,
is a matrix of contemporaneous coefficients,
is a coefficient matrix of endogenous variables,
is a vector of deterministic terms and its coefficient
matrix. is the lag order of endogenous variables.
As in Primiceri (2005) is an error term with
and ,
where is a lower triangular matrix with ones on the main diagonal
and is a diagonal matrix with error variances
.
Unless structural = TRUE, is an identity matrix. Otherwise it
is a lower triangular matrix with ones on its main diagonal, whose free elements
are drawn from range_a0, and the errors of the structural equations are
uncorrelated, so that is an identity matrix and
. This is the model that create_bvarmodel
produces with structural = TRUE. The coefficients and
are those of the structural equations, and the reduced form of the model has the
coefficients and the error covariance matrix
.
The linear trend takes the value 1 in period of the returned series,
which is the first period that create_bvarmodel uses for estimation
with lag order . The true coefficients of the trend are therefore those
that model estimates with the same lag order refer to.
If tvp = FALSE and sv = FALSE, all parameters are constant over time.
If tvp = TRUE, the coefficients ,
the free elements of and the free elements of
follow random walks
with diagonal and , whose elements are drawn from
range_variance_state, and likewise for . Coefficients that are
zero in the first period, such as those set to zero by a_zeros, have a state
variance of zero and stay zero. With the default range_psi = c(0, 0) the
errors therefore remain uncorrelated.
If sv = TRUE, the log-volatilities follow random walks
with drawn from range_variance_sv. These are the state
equations of the models that create_bvarmodel produces with
tvp = TRUE and error = "sv" or "sv+covar".
The parameters of the first period are drawn from the ranges above. During the presample they are held at these values, so that the returned paths start at them and the presample only removes the influence of the initial values of the series.
If stable = TRUE, the coefficients of lagged endogenous variables are
drawn until the companion matrix of the reduced form of the process has no
eigenvalue on or outside the unit circle. For tvp = TRUE this holds in
every period: an innovation of the coefficients, which would make the process
unstable, is drawn again, and if no stable innovation is found in 100 attempts,
the coefficients keep the values of the previous period. This restricts the
random walks to the stable region as in Cogley and Sargent (2005). Set
stable = FALSE to generate integrated or explosive series, usually together
with presample = 0. Cointegrated series are generated by
generate_artificial_vec.
Argument level shifts the generated series by a vector , which gives
them high levels without changing their dynamics. The model becomes
,
so that the intercept absorbs the shift: the returned intercept is
, where is drawn from
range_const. Without an intercept this term would not be part of the model,
so that a non-zero level requires deterministic = "const" or "both".
A list with the elements
dataa time-series object of the artificial
series, named var1, var2 etc.
paramsa list of the true parameters with the elements
a_coefthe coefficient matrix
, with the columns in the order of the regressors of
create_bvarmodel, or NULL if the model has no regressors.
For tvp = TRUE a array.
a0_coeffor structural = TRUE, the matrix
, or for tvp = TRUE a array.
psi_coefthe matrix , or for
tvp = TRUE a array. NULL if
or structural = TRUE.
u_omegathe diagonal matrix of error variances
, or for sv = TRUE a array.
u_sigmathe covariance matrix of
, or for tvp = TRUE or sv = TRUE a
array.
a_state_variancefor tvp = TRUE, the matrix
of the variances of the state equations of the coefficients.
a0_state_variancefor tvp = TRUE and structural = TRUE,
the matrix of the variances of the state equations of .
psi_state_variancefor tvp = TRUE, and
structural = FALSE, the matrix of the variances of the
state equations of .
u_state_variancefor sv = TRUE, the variances of
the state equations of the log-volatilities.
For time varying parameters, as.vector() of an array gives the parameters
period by period, which is the order of the columns of the posterior draws of TVP
models.
Cogley, T., & Sargent, T. J. (2005). Drifts and volatilities: Monetary policies and outcomes in the post WWII US. Review of Economic Dynamics, 8(2), 262–302. doi:10.1016/j.red.2004.10.009
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Primiceri, G. E. (2005). Time varying structural vector autoregressions and monetary policy. The Review of Economic Studies, 72(3), 821–852. doi:10.1111/j.1467-937X.2005.00353.x
Other artificial data:
generate_artificial_vec()
# Set seed of RNG set.seed(1) # Time series without intercept terms dt <- generate_artificial_var(nobs = 200, k = 3) # Time series with all intercept terms equal to 5 dt <- generate_artificial_var(nobs = 200, k = 3, deterministic = "const", range_const = c(5, 5)) # Time series with high levels, shifted by 100, 50 and 20 dt <- generate_artificial_var(nobs = 200, k = 3, deterministic = "const", level = c(100, 50, 20)) dt[["params"]][["a_coef"]][, "const"] # Time varying parameters and stochastic volatility with correlated errors dt <- generate_artificial_var(nobs = 200, k = 2, p = 1, deterministic = "const", tvp = TRUE, sv = TRUE, range_psi = c(-0.5, 0.5)) # Path of the error variance of the first variable plot(dt[["params"]][["u_omega"]][1, 1, ], type = "l") # Structural model dt <- generate_artificial_var(nobs = 200, k = 3, p = 1, structural = TRUE) dt[["params"]][["a0_coef"]]# Set seed of RNG set.seed(1) # Time series without intercept terms dt <- generate_artificial_var(nobs = 200, k = 3) # Time series with all intercept terms equal to 5 dt <- generate_artificial_var(nobs = 200, k = 3, deterministic = "const", range_const = c(5, 5)) # Time series with high levels, shifted by 100, 50 and 20 dt <- generate_artificial_var(nobs = 200, k = 3, deterministic = "const", level = c(100, 50, 20)) dt[["params"]][["a_coef"]][, "const"] # Time varying parameters and stochastic volatility with correlated errors dt <- generate_artificial_var(nobs = 200, k = 2, p = 1, deterministic = "const", tvp = TRUE, sv = TRUE, range_psi = c(-0.5, 0.5)) # Path of the error variance of the first variable plot(dt[["params"]][["u_omega"]][1, 1, ], type = "l") # Structural model dt <- generate_artificial_var(nobs = 200, k = 3, p = 1, structural = TRUE) dt[["params"]][["a0_coef"]]
Generates an artificial data set from a vector error correction model with constant or time varying parameters and constant or stochastic volatility, for testing the algorithms of the package.
generate_artificial_vec( nobs = 100, k = 3, p = 2, r = 1, const = NULL, trend = NULL, structural = FALSE, tvp = FALSE, sv = FALSE, range_alpha = c(-0.5, 0.5), range_beta = c(-1, 1), range_gamma = c(-0.5, 0.5), gamma_zeros = 0.5, range_a0 = c(-0.5, 0.5), range_const = c(-0.5, 0.5), range_trend = c(-0.01, 0.01), range_variance = c(1, 1), range_psi = c(0, 0), range_variance_state = c(1e-04, 1e-04), range_variance_sv = c(0.01, 0.01), stable = TRUE, presample = 100, level = 0 )generate_artificial_vec( nobs = 100, k = 3, p = 2, r = 1, const = NULL, trend = NULL, structural = FALSE, tvp = FALSE, sv = FALSE, range_alpha = c(-0.5, 0.5), range_beta = c(-1, 1), range_gamma = c(-0.5, 0.5), gamma_zeros = 0.5, range_a0 = c(-0.5, 0.5), range_const = c(-0.5, 0.5), range_trend = c(-0.01, 0.01), range_variance = c(1, 1), range_psi = c(0, 0), range_variance_state = c(1e-04, 1e-04), range_variance_sv = c(0.01, 0.01), stable = TRUE, presample = 100, level = 0 )
nobs |
number of generated observations in levels. Defaults to 100. |
k |
number of endogenous variables. Defaults to 3. |
p |
lag order of the series in the (levels) VAR, so that the VEC model has
|
r |
cointegration rank between 0 and |
const |
a character specifying whether a constant term enters the error correction
term ( |
trend |
a character specifying whether a linear trend enters the error correction
term ( |
structural |
logical specifying whether a structural VEC model with a lower
triangular matrix |
tvp |
logical specifying whether the coefficients, |
sv |
logical specifying whether the error variances follow a stochastic
volatility process. Defaults to |
range_alpha |
numeric vector with two elements containing the minimum and
maximum value of the loadings |
range_beta |
numeric vector with two elements containing the minimum and
maximum value of the free elements of the cointegration matrix |
range_gamma |
numeric vector with two elements containing the minimum and
maximum value of the coefficients of lagged differences. Defaults to |
gamma_zeros |
numeric between 0 and 1 indicating the share of coefficients
of lagged differences, which should be set to zero. Default is |
range_a0 |
numeric vector with two elements containing the minimum and
maximum value of the free elements of |
range_const |
numeric vector with two elements containing the minimum and
maximum value of the coefficients of the constant term. Defaults to |
range_trend |
numeric vector with two elements containing the minimum and
maximum value of the coefficients of the linear trend. Defaults to |
range_variance |
numeric vector with two elements containing the minimum and
maximum value of the error variances. For |
range_psi |
numeric vector with two elements containing the minimum and
maximum value of the free elements of |
range_variance_state |
numeric vector with two elements containing the minimum and
maximum value of the variances of the state equations of the coefficients, of
|
range_variance_sv |
numeric vector with two elements containing the minimum and
maximum value of the variances of the state equations of the log-volatilities.
Only used if |
stable |
logical specifying whether the coefficients are restricted to a process
that is integrated of order one with cointegration rank |
presample |
numeric specifying the number of observations, which are generated before the first returned observation and then discarded. Defaults to 100. |
level |
numeric vector with one or |
The function produces artificial observations for a vector error correction (VEC) model:
where
is a K-dimensional vector of differenced endogenous variables,
is the vector of the endogenous variables in levels and
the restricted deterministic terms,
is the matrix of loadings,
is the cointegration matrix with rows and columns,
,
is a coefficient matrix of lagged differences,
is the vector of unrestricted deterministic terms and its
coefficient matrix. The error term and are specified as
in generate_artificial_var: with
, and is an identity
matrix unless structural = TRUE, where it is lower triangular with ones on
its main diagonal and the structural errors are uncorrelated.
This is the model that create_bvecmodel produces with the same
arguments p, r, const, trend and structural.
The cointegration matrix is normalised so that its first rows are an identity
matrix. Its other rows for endogenous variables are drawn from range_beta, and
its rows for a restricted constant or trend from range_const and
range_trend. Since add_posterior_coefficients may use another
normalisation, estimates are best compared with the true parameters through
, which does not depend on it.
The linear trend takes the value 1 in period of the returned series,
which is the first period that create_bvecmodel uses for estimation
with lag order .
If tvp = TRUE, the loadings, the free elements of , the
coefficients of lagged differences and unrestricted deterministic terms, the free
elements of and the free elements of follow random walks,
whose innovation variances are drawn from range_variance_state. Coefficients
that are zero in the first period stay zero. The random walk of the normalised
differs from the state equation of the unnormalised cointegration
matrix in Koop et al. (2011), which create_bvecmodel uses for
estimation. If sv = TRUE, the log-volatilities follow random walks as in
generate_artificial_var. During the presample the parameters are held
at their values of the first period.
If stable = TRUE, the coefficients are drawn until the VAR representation of
the reduced form of the process has exactly unit roots and all other
roots inside the unit circle, so that the series are integrated of order one and
is stationary. With r = 0 the series are
integrated but not cointegrated, with r = k they are stationary. For
tvp = TRUE this holds in every period: an innovation, which violates it, is
drawn again, and if no admissible innovation is found in 100 attempts, the
coefficients keep the values of the previous period.
The series start at zero before the presample. Argument level shifts them
by a vector , which gives series with high levels that follow a stochastic
trend. The dynamics of the differences are unchanged, but the error correction
term becomes , so that the constant
term absorbs : the returned row of a restricted constant
in is and the returned
unrestricted constant is , where
and are drawn from range_const and
here denotes the rows of the endogenous variables. Without a
constant this term would not be part of the model, so that a non-zero level with
r > 0 requires const = "restricted" or "unrestricted".
A list with the elements
dataa time-series object of the artificial
series in levels, named var1, var2 etc.
paramsa list of the true parameters with the elements
alphathe matrix of loadings .
betathe cointegration matrix .
pithe matrix ,
with the columns in the order of the cointegration variables of
create_bvecmodel.
gammathe matrix .
cthe matrix of unrestricted deterministic terms.
a0_coeffor structural = TRUE, the matrix .
psi_coef, u_omega, u_sigma
the parameters of the error
term as in generate_artificial_var.
alpha_state_variance, beta_state_variance,
gamma_state_variance, c_state_variance, a0_state_variance,
psi_state_variance
for tvp = TRUE, the variances of the state
equations of the respective parameters.
u_state_variancefor sv = TRUE, the variances of
the state equations of the log-volatilities.
Parameters that are not part of the model are NULL. Time varying parameters
are arrays with one matrix per period.
Johansen, S. (1995). Likelihood-based inference in cointegrated vector autoregressive models. Oxford: Oxford University Press.
Koop, G., León-González, R., & Strachan R. W. (2011). Bayesian inference in a time varying cointegration model. Journal of Econometrics, 165(2), 210–220. doi:10.1016/j.jeconom.2011.07.007
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Other artificial data:
generate_artificial_var()
# Set seed of RNG set.seed(1) # Three series with one cointegration relationship dt <- generate_artificial_vec(nobs = 200, k = 3, p = 2, r = 1) dt[["params"]][["pi"]] # Restricted constant and time varying cointegration with stochastic volatility dt <- generate_artificial_vec(nobs = 200, k = 2, p = 1, r = 1, const = "restricted", tvp = TRUE, sv = TRUE, range_variance_state = c(0.001, 0.001)) # Path of the cointegration coefficient of the second variable plot(dt[["params"]][["beta"]][2, 1, ], type = "l") # Cointegrated series with high levels around 100, 50 and 20 dt <- generate_artificial_vec(nobs = 200, k = 3, p = 2, r = 1, const = "restricted", level = c(100, 50, 20)) dt[["params"]][["beta"]] # Structural model with an unrestricted constant dt <- generate_artificial_vec(nobs = 200, k = 3, p = 2, r = 1, const = "unrestricted", structural = TRUE)# Set seed of RNG set.seed(1) # Three series with one cointegration relationship dt <- generate_artificial_vec(nobs = 200, k = 3, p = 2, r = 1) dt[["params"]][["pi"]] # Restricted constant and time varying cointegration with stochastic volatility dt <- generate_artificial_vec(nobs = 200, k = 2, p = 1, r = 1, const = "restricted", tvp = TRUE, sv = TRUE, range_variance_state = c(0.001, 0.001)) # Path of the cointegration coefficient of the second variable plot(dt[["params"]][["beta"]][2, 1, ], type = "l") # Cointegrated series with high levels around 100, 50 and 20 dt <- generate_artificial_vec(nobs = 200, k = 3, p = 2, r = 1, const = "restricted", level = c(100, 50, 20)) dt[["params"]][["beta"]] # Structural model with an unrestricted constant dt <- generate_artificial_vec(nobs = 200, k = 3, p = 2, r = 1, const = "unrestricted", structural = TRUE)
Generates a lower triangular block matrix with ones on the main diagonal, where the off-diagonal elements are blocks.
generate_lower_block_diagonal(a, k, tt)generate_lower_block_diagonal(a, k, tt)
a |
|
k |
integer of the number of columns per block. |
tt |
integer specifying |
For the matrix A, where , with
the function constructs the
following sparse diagonal block matrix:
A sparse matrix.
a <- matrix(1:8) generate_lower_block_diagonal(a, 2, 5)a <- matrix(1:8) generate_lower_block_diagonal(a, 2, 5)
A generic function used to obtain the forecast errors from a model.
get_forecast_errors(object, ...)get_forecast_errors(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
A generic function used to obtain the model specifications of a model.
get_model_specifications(object, ...)get_model_specifications(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
A one-row data frame with the specifications of the model. Which columns
are returned depends on the class of argument object:
the type of the model.
the number of endogenous variables.
the lag order of the endogenous variables.
the number of unmodelled, non-deterministic variables.
the lag order of the unmodelled, non-deterministic variables.
the number of deterministic terms. For objects of class 'bvecmodel'
the columns n_unrestricted and n_restricted are returned instead.
the rank of the cointegration matrix. Only for objects of class 'bvecmodel'.
the number of observations used for estimation. Not for objects of class 'expandingwindow', where it differs across the estimation windows, and not for objects of class 'selcrit', which do not contain the input data.
the used variable selection algorithm.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 10, burnin = 10) # Obtain model specifications get_model_specifications(model)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 10, burnin = 10) # Obtain model specifications get_model_specifications(model)
Decomposes the path of a variable over the estimation sample into the contributions of the identified structural shocks.
historical_decomposition(x, ...)historical_decomposition(x, ...)
x |
an object of class 'bvarmodel' with posterior draws. |
... |
further arguments passed to or from other methods. |
See the method, historical_decomposition.bvarmodel.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
Decomposes the path of a variable over the estimation sample into the contributions of the identified structural shocks and a baseline.
## S3 method for class 'bvarmodel' historical_decomposition( x, response = NULL, type = "oir", impact = NULL, statistic = "mean", ci = NULL, ... )## S3 method for class 'bvarmodel' historical_decomposition( x, response = NULL, type = "oir", impact = NULL, statistic = "mean", ci = NULL, ... )
x |
an object of class 'bvarmodel' with posterior draws of the coefficients and the error covariance. |
response |
name of the variable whose path is decomposed. |
type |
the identification: |
impact |
for |
statistic |
the posterior summary of each contribution,
|
ci |
an optional probability, the coverage of the credible interval
returned alongside, such as |
... |
further arguments passed to or from other methods. |
With the reduced form errors and
the structural shocks, the model's moving average form splits
each period's value into
the contribution of each shock over the sample so far plus a
baseline : what the lags before the sample, the deterministic terms
and the exogenous variables would have produced without any shock. For every
draw the shocks are recovered from that draw's residuals and its impact
matrix, and the contributions are propagated by the draw's lag coefficients,
so that the decomposition carries the posterior uncertainty of all three.
Where the panel was not observed whole (see create_bvarmodel),
each draw is decomposed over its own completed panel, so that the periods
nobody observed are decomposed as the model filled them.
Available for models with constant coefficients, a lag order of at least one and a covariance that does not change over the sample; that excludes time-varying parameters and stochastic volatility, whose impact matrix would differ from period to period, and structural models.
A time series of class "bvarhd", one row per period of the
estimation sample and one column per shock plus a last column
baseline. With ci, attributes lower and upper
hold the bounds of the credible interval in the same shape. The response
itself is attribute data; for a completed panel it is the sum of the
columns, the posterior mean of the completed series.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, iterations = 100, burnin = 50) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_posterior_coefficients(add_initial_values(model)) hd <- historical_decomposition(model, response = "cons") plot(hd)data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, iterations = 100, burnin = 50) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_posterior_coefficients(add_initial_values(model)) hd <- historical_decomposition(model, response = "cons") plot(hd)
A generic function used to generate prior inclusion probabilities as required for stochastic search variable selection (SSVS) à la George et al. (2008) and Bayesian variable selection (BVS) à la Korobilis (2013). The function invokes particular methods which depend on the class of the first argument.
inclusion_prior(object, ...)inclusion_prior(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: inclusion_prior.bvarmodel,
inclusion_prior.bvecmodel,
inclusion_prior.externalforecast.
Prior inclusion probabilities as required for stochastic search variable selection (SSVS) à la George et al. (2008) and Bayesian variable selection (BVS) à la Korobilis (2013).
## S3 method for class 'bvarmodel' inclusion_prior( object, prob = 0.5, exclude_deterministics = TRUE, minnesota_like = FALSE, kappa1 = 0.8, kappa2 = 0.5, kappa3 = 0.5, kappa4 = 0.8, ... )## S3 method for class 'bvarmodel' inclusion_prior( object, prob = 0.5, exclude_deterministics = TRUE, minnesota_like = FALSE, kappa1 = 0.8, kappa2 = 0.5, kappa3 = 0.5, kappa4 = 0.8, ... )
object |
an object of class |
prob |
a numeric specifying the prior inclusion probability of all model parameters. |
exclude_deterministics |
logical. If |
minnesota_like |
logical. If |
kappa1 |
a numeric specifying the prior inclusion probability of
coefficients that correspond to own lags of endogenous variables.
Only used if |
kappa2 |
a numeric specifying the size of the prior inclusion probabilities
of endogenous variables, which do not correspond to own lags.
Only used if |
kappa3 |
a numeric specifying the size of the prior inclusion probabilities
of non-deterministic exogenous variables, between 0 and 1. Default is 0.5.
Only used if |
kappa4 |
a numeric specifying the size of the prior inclusion probabilities
of deterministic terms. Only used if |
... |
further arguments passed to or from other methods. |
If minnesota_like = TRUE, prior inclusion probabilities
are calculated as
|
for own lags of endogenous variables, |
|
for other endogenous variables, |
|
for unmodelled exogenous variables, |
|
for contemporaneous endogenous variables of a structural model, |
|
for deterministic variables. |
A list containing a matrix of prior inclusion probabilities and an integer vector specifying the positions of variables, which should be included in the variable selection algorithm.
# Prepare data data("e1") e1 <- diff(log(e1)) * 100 # Generate model input object <- create_bvarmodel(e1) # Obtain inclusion prior incl <- inclusion_prior(object)# Prepare data data("e1") e1 <- diff(log(e1)) * 100 # Generate model input object <- create_bvarmodel(e1) # Obtain inclusion prior incl <- inclusion_prior(object)
Prior inclusion probabilities as required for stochastic search variable selection (SSVS) à la George et al. (2008) and Bayesian variable selection (BVS) à la Korobilis (2013).
## S3 method for class 'bvecmodel' inclusion_prior( object, prob = 0.5, exclude_deterministics = TRUE, minnesota_like = FALSE, kappa1 = 0.8, kappa2 = 0.5, kappa3 = 0.5, kappa4 = 0.8, ... )## S3 method for class 'bvecmodel' inclusion_prior( object, prob = 0.5, exclude_deterministics = TRUE, minnesota_like = FALSE, kappa1 = 0.8, kappa2 = 0.5, kappa3 = 0.5, kappa4 = 0.8, ... )
object |
an object of class 'bvecmodel', usually, a result of a
call to |
prob |
a numeric specifying the prior inclusion probability of all model parameters. |
exclude_deterministics |
logical. If |
minnesota_like |
logical. If |
kappa1 |
a numeric specifying the prior inclusion probability of
coefficients that correspond to own lags of endogenous variables.
Only used if |
kappa2 |
a numeric specifying the size of the prior inclusion probabilities
of endogenous variables, which do not correspond to own lags.
Only used if |
kappa3 |
a numeric specifying the size of the prior inclusion probabilities
of non-deterministic exogenous variables, between 0 and 1. Default is 0.5.
Only used if |
kappa4 |
a numeric specifying the size of the prior inclusion probabilities
of deterministic terms. Only used if |
... |
further arguments passed to or from other methods. |
If minnesota_like = TRUE, prior inclusion probabilities
are calculated as
|
for own lags of endogenous variables, |
|
for other endogenous variables, |
|
for unmodelled exogenous variables, |
|
for contemporaneous endogenous variables of a structural model, |
|
for deterministic variables. |
A list containing a matrix of prior inclusion probabilities and an integer vector specifying the positions of variables, which should be included in the variable selection algorithm.
# Prepare data data("e6") # Generate model input object <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted") # Obtain inclusion prior priors <- inclusion_prior(object)# Prepare data data("e6") # Generate model input object <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted") # Obtain inclusion prior priors <- inclusion_prior(object)
A generic function used to calculate impulse response functions.
irf(x, ...)irf(x, ...)
x |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of x,
as described on the pages of the methods.
Methods: irf.bvarmodel.
Computes the impulse response coefficients for an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' irf( x, impulse = NULL, response = NULL, n_ahead = 5, ci = 0.95, shock = 1, type = "feir", cumulative = FALSE, keep_draws = FALSE, period = NULL, impact = NULL, ... )## S3 method for class 'bvarmodel' irf( x, impulse = NULL, response = NULL, n_ahead = 5, ci = 0.95, shock = 1, type = "feir", cumulative = FALSE, keep_draws = FALSE, period = NULL, impact = NULL, ... )
x |
an object of class 'bvarmodel'. |
impulse |
name of the impulse variable. |
response |
name of the response variable. |
n_ahead |
number of steps ahead. Zero is allowed and returns the impact response alone. |
ci |
a numeric between 0 and 1 specifying the probability mass covered by the credible intervals. Defaults to 0.95. |
shock |
size of the shock. For |
type |
type of the impulse response. Possible choices are forecast error |
cumulative |
logical specifying whether a cumulative IRF should be calculated. |
keep_draws |
logical specifying whether the function should return all draws of
the posterior impulse response function. Defaults to |
period |
integer. Index of the period, for which the IR should be generated.
Only used for TVP or SV models. Default is |
impact |
the impact matrix of a |
... |
further arguments passed to or from other methods. |
The function produces different types of impulse responses for the VAR model
with .
Forecast error impulse responses are obtained by recursions
with .
Orthogonalised impulse responses are calculated as ,
where P is the lower triangular Choleski decomposition of , so that they are the
responses to orthogonalised shocks of one standard deviation.
Structural impulse responses are calculated as .
For a structural model the posterior draws describe the structural form: the coefficients are
the of the equation above and is the covariance of the structural errors.
The recursion for needs the reduced form, i.e. and
, which only "sir" and "sgir" form. The other
types are therefore not available for a structural model, and the two structural types not for
any other.
Sign restricted impulse responses are calculated as
, where is the lower triangular Choleski decomposition of
and the rotation that add_sign_restrictions accepted for that
draw. Draws for which no admissible rotation was found are left out, so the responses cover
fewer draws than the posterior holds and the credible interval is one over the set of models the
restrictions admit rather than over a single identified model.
Custom impulse responses are calculated as , where
is the matrix supplied in argument impact. This is the route by which an
identification that the package does not derive itself reaches the recursion; shock
rescales the result but nothing normalises the columns of , so an impact matrix that
means to deliver unit shocks has to arrive that way.
(Structural) Generalised impulse responses to a shock to variable are calculated as
, where is the
th diagonal element of , the variance of the error of the impulse variable, and
is a selection vector containing one in its th element and zero otherwise. They are
therefore the responses to a shock of one standard deviation (Pesaran and Shin, 1998). If the
"bvarmodel" object does not contain draws of , it is assumed to be an identity matrix.
A time-series object of class 'bvarirf' running from period 0 to n_ahead,
with the lower bound, the median and the upper bound of the credible band of the
response in three columns named after their quantiles, e.g. "2.5%",
"50%" and "97.5%" for ci = .95. If keep_draws = TRUE, a
matrix of class 'bvarirf' with one row per draw and one column per period instead.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Pesaran, H. H., Shin, Y. (1998). Generalized impulse response analysis in linear multivariate models. Economics Letters, 58, 17-29.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Obtain IR ir <- irf(model, impulse = "invest", response = "cons")# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Obtain IR ir <- irf(model, impulse = "invest", response = "cons")
Guard method for objects of class 'bvecmodel'.
## S3 method for class 'bvecmodel' irf(x, ...)## S3 method for class 'bvecmodel' irf(x, ...)
x |
an object of class 'bvecmodel'. |
... |
additional arguments. |
Nothing. The method raises an error, since impulse responses of a VEC model are
obtained from its VAR representation: apply vec_to_var first and then
irf to the resulting 'bvarmodel'.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
An implementation of the Kalman filter and backward smoothing algorithm proposed by Durbin and Koopman (2002).
kalman_durbin_koopman_2002(y, z, sigma_u, sigma_v, B, a_init, P_init)kalman_durbin_koopman_2002(y, z, sigma_u, sigma_v, B, a_init, P_init)
y |
a |
z |
a |
sigma_u |
the constant |
sigma_v |
the constant |
B |
the constant |
a_init |
an M-dimensional vector of initial states. |
P_init |
an |
The function uses algorithm 2 from Durbin and Koopman (2002) to produce
a draw of the state vector for for a state space model
with measurement equation
and transition equation
where and .
is a K-dimensional vector of endogenous variables and
is a matrix of regressors with
as a vector of regressors.
The algorithm takes into account Jarociński (2015), where a possible missunderstanding in the implementation of the algorithm of Durbin and Koopman (2002) is pointed out. Following that note the function sets the mean of the initial state to zero in the first step of the algorithm.
This is the routine the time varying parameter samplers of the package use. It comes from the vendored BayesTS core, so there is one implementation of the smoother rather than one for R and one for the samplers.
The draw uses R's random number generator, so set.seed makes it
reproducible.
A matrix of state vector draws. Column is
the state the observation in column of y loads on, for
, so a caller wanting one state per observation takes the
first columns. The first column is not a state preceding the sample:
it is , already conditioned on every observation. The last column is
the transition applied once past the end of the sample and is informed by no
observation; it is returned because the recursions build it on the way.
Durbin, J., & Koopman, S. J. (2002). A simple and efficient simulation smoother for state space time series analysis. Biometrika, 89(3), 603–615.
Jarociński, M. (2015). A note on implementing the Durbin and Koopman simulation smoother. Computational Statistics and Data Analysis, 91, 1–3. doi:10.1016/j.csda.2015.05.001
# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data = data, p = 2, deterministic = "const", iterations = 1, burnin = 0) y <- t(temp$data$train$y) z <- temp$data$train$z k <- nrow(y) tt <- ncol(y) m <- ncol(z) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(0.1, m) a_Q <- diag(.0001, m) # Initial value of Sigma sigma <- tcrossprod(y) / tt sigma_i <- solve(sigma) # Initial values for Kalman filter y_init <- y * 0 a_filter <- matrix(0, m, tt + 1) # Initialise the Kalman filter for (i in 1:tt) { y_init[, i] <- y[, i] - z[(i - 1) * k + 1:k,] %*% a_filter[, i] } a_init <- post_normal_sur(y = y_init, z = z, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior) y_filter <- matrix(y) - z %*% a_init y_filter <- matrix(y_filter, k) # Reshape # Kalman filter and backward smoother a_filter <- kalman_durbin_koopman_2002(y = y_filter, z = z, sigma_u = sigma, sigma_v = a_Q, B = diag(1, m), a_init = matrix(0, m), P_init = a_Q) a <- a_filter + matrix(a_init, m, tt + 1)# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data = data, p = 2, deterministic = "const", iterations = 1, burnin = 0) y <- t(temp$data$train$y) z <- temp$data$train$z k <- nrow(y) tt <- ncol(y) m <- ncol(z) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(0.1, m) a_Q <- diag(.0001, m) # Initial value of Sigma sigma <- tcrossprod(y) / tt sigma_i <- solve(sigma) # Initial values for Kalman filter y_init <- y * 0 a_filter <- matrix(0, m, tt + 1) # Initialise the Kalman filter for (i in 1:tt) { y_init[, i] <- y[, i] - z[(i - 1) * k + 1:k,] %*% a_filter[, i] } a_init <- post_normal_sur(y = y_init, z = z, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior) y_filter <- matrix(y) - z %*% a_init y_filter <- matrix(y_filter, k) # Reshape # Kalman filter and backward smoother a_filter <- kalman_durbin_koopman_2002(y = y_filter, z = z, sigma_u = sigma, sigma_v = a_Q, B = diag(1, m), a_init = matrix(0, m), P_init = a_Q) a <- a_filter + matrix(a_init, m, tt + 1)
Finds the groups of an HDF5 file that hold a model.
list_models_in_hdf5(filename, group = "")list_models_in_hdf5(filename, group = "")
filename |
path to an HDF5 file. |
group |
the group to search under. Defaults to |
A model is a group with a model subgroup carrying an
algorithm attribute. The search stops at a model rather than
descending into its data, priors and posterior, which
are its own subtree and not a place further models could be.
This is the same rule the BayesTS command line applies for its
--all-groups flag, so both agree on which groups of a file are models.
A character vector of group names, sorted, empty if the file holds no
model. A model at the root of its file is reported as "", which is the
value read_model_from_hdf5 takes for it.
# Load data data("e1") train <- diff(log(e1)) * 100 # Create and store two models in one file path_to_model <- tempfile(fileext = ".h5") for (p in 1:2) { model <- create_bvarmodel(data = train, p = p, deterministic = "const", iterations = 10, burnin = 10) write_to_hdf5(model, filename = path_to_model, group = paste0("/models/", p)) } list_models_in_hdf5(path_to_model)# Load data data("e1") train <- diff(log(e1)) * 100 # Create and store two models in one file path_to_model <- tempfile(fileext = ".h5") for (p in 1:2) { model <- create_bvarmodel(data = train, p = p, deterministic = "const", iterations = 10, burnin = 10) write_to_hdf5(model, filename = path_to_model, group = paste0("/models/", p)) } list_models_in_hdf5(path_to_model)
Calculates the log-likelihood of a multivariate normal distribution.
loglik_normal(u, sigma)loglik_normal(u, sigma)
u |
a |
sigma |
a |
The log-likelihood is calculated for each vector in period as
,
where .
A numeric vector of length , the log-likelihood of each period.
Sum it for the log-likelihood of the sample.
# Load data data("e1") e1 <- diff(log(e1)) # Generate VAR model data <- create_bvarmodel(e1, p = 2, deterministic = "const") y <- t(data$data$train$y) x <- t(data$data$train$x) # LS estimate ols <- tcrossprod(y, x) %*% solve(tcrossprod(x)) # Residuals u <- y - ols %*% x # Residuals # Covariance matrix sigma <- tcrossprod(u) / ncol(u) # Log-likelihood loglik_normal(u = u, sigma = sigma)# Load data data("e1") e1 <- diff(log(e1)) # Generate VAR model data <- create_bvarmodel(e1, p = 2, deterministic = "const") y <- t(data$data$train$y) x <- t(data$data$train$x) # LS estimate ols <- tcrossprod(y, x) %*% solve(tcrossprod(x)) # Residuals u <- y - ols %*% x # Residuals # Covariance matrix sigma <- tcrossprod(u) / ncol(u) # Log-likelihood loglik_normal(u = u, sigma = sigma)
Reads the chain of a stored model in pieces and applies a function to the model holding each piece, which is how the analysis of a model too large to hold is done.
map_draws(x, f, ..., chunk = 100)map_draws(x, f, ..., chunk = 100)
x |
an object of class 'bvarfile', from |
f |
a function taking a model and returning whatever the caller wants to keep of that piece of the chain. |
... |
further arguments passed to |
chunk |
how many draws are read at a time. Defaults to 100. |
The model f is given is the model in the file with the draws of one
piece, so anything that works on a model works on it. What it returns is
collected in a list, one element per piece, and combining those is the
caller's business: the responses of an impulse response are stacked, the
shares of a variance decomposition are averaged over the pieces they came
from.
A list with one element per piece of the chain.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) file <- file.path(tempdir(), "bvartools-example-draws.h5") unlink(file) write_to_hdf5(model, filename = file) stored <- open_model(file) # The mean of every coefficient, without reading the chain at once sums <- map_draws(stored, function(model) { colSums(unclass(model[["posterior"]][["a"]][["coeffs"]])) }, chunk = 25) means <- Reduce(`+`, sums) / stored[["draws"]]data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) file <- file.path(tempdir(), "bvartools-example-draws.h5") unlink(file) write_to_hdf5(model, filename = file) stored <- open_model(file) # The mean of every coefficient, without reading the chain at once sums <- map_draws(stored, function(model) { colSums(unclass(model[["posterior"]][["a"]][["coeffs"]])) }, chunk = 25) means <- Reduce(`+`, sums) / stored[["draws"]]
Reads every model of a folder, applies a function to it, writes it back and drops it, so that a step over many models costs the memory of one model per worker rather than of all of them.
map_models(x, f, ..., models = NULL, write = TRUE, cores = 1, export = NULL)map_models(x, f, ..., models = NULL, write = TRUE, cores = 1, export = NULL)
x |
an object of class 'bvarfolder', from |
f |
a function taking a model – a 'bvarmodel', a 'bvecmodel', or the
model of another package that |
... |
further arguments passed to |
models |
character vector of the models the step is applied to, as the
manifest names them, or |
write |
whether what |
cores |
the number of worker processes the models are handled on. Defaults to one. With more than one the models are spread over a socket cluster; every model has its own file, so the workers share nothing. |
export |
character vector of names of objects in the calling
environment that the workers need, for instance the sampler that
|
The unit is one model, which is what a file of the folder holds. A model is
read with read_model_from_hdf5, passed to f, and written
back to its own file through a temporary file that replaces the old one once
it is complete, so an interrupted step leaves either the model as it was or
the model as f made it, never half of it. A file holding more than one
model cannot be worked on this way, since writing one of them back would have
to rewrite the others, and such a model is refused rather than risked.
The manifest is rebuilt from the specifications of the models that come back, so a step that changes what a model is – its rank, its lag orders, the chain it asks for – leaves the table describing the files. It records what a model is, not how many draws are left in it, so thinning the draws does not change it.
A step over a subset is a step over the whole folder applied to part of it:
the position a model has in the whole manifest is what is passed as
index and what numbers its seed, so a run taken model by model draws
what a run over all of them draws. That is what makes a long estimation
resumable, and the estimation steps for a folder pass models on.
With more than one core, f is sent to the workers as it stands, and
the workers load the installed package. A function that calls something the
package does not export, or something only a newer version of it has, fails
there rather than in the session it was written in. Pass what such a function
needs as an argument instead.
For the posterior itself, prefer bayests_files over a cluster:
the draws are the largest thing a model has, and reading them into R and
writing them out again costs more than the sampler. An idle R worker is not
cheap either – on Windows a fresh one commits about 2 GB before it does
anything and about 4 GB once it has loaded this package.
With write = TRUE, the object in x with its manifest
brought up to date, invisibly. With write = FALSE, a named list of
what f returned, one element per model.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("e1") train <- diff(log(e1)) * 100 models <- create_bvarmodel(data = train, p = 1:2, deterministic = "const", iterations = 20, burnin = 10) folder <- file.path(tempdir(), "bvartools-example-map") unlink(folder, recursive = TRUE) dir.create(folder, recursive = TRUE) write_to_hdf5(models, folder = folder) stored <- open_models(folder) # What add_priors() for a folder does stored <- map_models(stored, function(model) { add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) }) # Reading only: how many observations each model was built on map_models(stored, function(model) nrow(model$data$train$y), write = FALSE)data("e1") train <- diff(log(e1)) * 100 models <- create_bvarmodel(data = train, p = 1:2, deterministic = "const", iterations = 20, burnin = 10) folder <- file.path(tempdir(), "bvartools-example-map") unlink(folder, recursive = TRUE) dir.create(folder, recursive = TRUE) write_to_hdf5(models, folder = folder) stored <- open_models(folder) # What add_priors() for a folder does stored <- map_models(stored, function(model) { add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) }) # Reading only: how many observations each model was built on map_models(stored, function(model) nrow(model$data$train$y), write = FALSE)
Calculates the Minnesota prior for a model.
minnesota_prior(object, ...)minnesota_prior(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
A generic function used to generate data matrices based on the Minnesota prior. The function invokes particular methods which depend on the class of the first argument.
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: minnesota_prior.bvarmodel,
minnesota_prior.bvecmodel,
minnesota_prior.externalforecast,
minnesota_prior.modellist.
Calculates the Minnesota prior for a VAR model.
## S3 method for class 'bvarmodel' minnesota_prior( object, kappa1 = 2, kappa2 = 0.5, kappa3 = NULL, kappa4 = 5, max_var = NULL, coint_var = FALSE, sigma = "AR", ... )## S3 method for class 'bvarmodel' minnesota_prior( object, kappa1 = 2, kappa2 = 0.5, kappa3 = NULL, kappa4 = 5, max_var = NULL, coint_var = FALSE, sigma = "AR", ... )
object |
an object of class 'bvarmodel', usually, a result of a call to
|
kappa1 |
a numeric specifying the prior variance of coefficients that correspond to own lags of endogenous variables. See 'Details'. |
kappa2 |
a numeric specifying the size of the prior variance of endogenous variables, which do not correspond to own lags. See 'Details'. |
kappa3 |
a numeric specifying the size of the prior variance of non-deterministic exogenous
variables. Default is |
kappa4 |
a numeric specifying the size of the prior variance of deterministic
terms relative to argument |
max_var |
a positive numeric specifying the maximum prior variance that is allowed for
coefficients of non-deterministic variables. If |
coint_var |
a logical specifying whether the model is a cointegrated VAR model, for which the prior means of first own lags should be set to one. |
sigma |
either |
... |
further arguments passed to or from other methods. |
The function calculates the Minnesota prior of a VAR model. For the
endogenous variable the prior variance of the th lag of
regressor is obtained as
where is the residual standard deviation of variable of an unrestricted
LS estimate. For exogenous variables is the sample standard deviation.
In case structural parameters are estimated, the formula
is used.
If is not provided, prior variances are calculated in the same way as for
deterministic terms.
If the model does not contain exogenous variables, argument kappa3 will be ignored.
A list containing a matrix of prior means and the precision matrix of the coefficients and the inverse variance-covariance matrix of the error term, which was obtained by an LS estimation.
Chan, J., Koop, G., Poirier, D. J., & Tobias, J. L. (2019). Bayesian Econometric Methods (2nd ed.). Cambridge: University Press.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model input object <- create_bvarmodel(e6, p = 1, deterministic = "both", seasonal = TRUE) # Obtain Minnesota prior prior <- minnesota_prior(object)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model input object <- create_bvarmodel(e6, p = 1, deterministic = "both", seasonal = TRUE) # Obtain Minnesota prior prior <- minnesota_prior(object)
Calculates the Minnesota prior for a VEC model.
## S3 method for class 'bvecmodel' minnesota_prior( object, kappa1 = 2, kappa2 = 1, kappa3 = NULL, kappa4 = 10, max_var = NULL, sigma = "AR", ... )## S3 method for class 'bvecmodel' minnesota_prior( object, kappa1 = 2, kappa2 = 1, kappa3 = NULL, kappa4 = 10, max_var = NULL, sigma = "AR", ... )
object |
an object of class 'bvecmodel', usually, a result of a call to
|
kappa1 |
a numeric specifying the prior variance of coefficients that correspond to own lags of endogenous variables. See 'Details'. |
kappa2 |
a numeric specifying the size of the prior variance of endogenous variables, which do not correspond to own lags. See 'Details'. |
kappa3 |
a numeric specifying the size of the prior variance of non-deterministic exogenous
variables. Default is |
kappa4 |
a numeric specifying the size of the prior variance of deterministic terms. See 'Details'. |
max_var |
a positive numeric specifying the maximum prior variance that is allowed for
coefficients of non-deterministic variables. If |
sigma |
either |
... |
further arguments passed to or from other methods. |
The function calculates the Minnesota prior in the same manner as for
a traditional VAR model. For the endogenous variable
the prior variance of the th lag of regressor is obtained as
where is the residual standard deviation of variable of an unrestricted
LS estimate. For exogenous variables is the sample standard deviation.
In case structural parameters are estimated, the formula
is used.
If kappa3 is not provided, prior variances are calculated in the same way as for
deterministic terms.
If the model does not contain exogenous variables, argument kappa3 will be ignored.
The function only provides priors for the non-cointegration part of the model. The
residual standard errors are based on an unrestricted LS regression of the
endogenous variables on the error correction term and the non-cointegration regressors.
A list containing a matrix of prior means and the precision matrix of the coefficients and the inverse variance-covariance matrix of the error term, which was obtained by an LS estimation.
Chan, J., Koop, G., Poirier, D. J., & Tobias, J. L. (2019). Bayesian Econometric Methods (2nd ed.). Cambridge: University Press.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
# Load data data("e6") # Generate model input object <- create_bvecmodel(e6, r = 0:2, p = 1:4, const = "unrestricted", seasonal = "unrestricted") # Obtain Minnesota prior prior <- minnesota_prior(object)# Load data data("e6") # Generate model input object <- create_bvecmodel(e6, r = 0:2, p = 1:4, const = "unrestricted", seasonal = "unrestricted") # Obtain Minnesota prior prior <- minnesota_prior(object)
Forwards the elements of an object of class 'modellist' forward to its respective method.
## S3 method for class 'modellist' minnesota_prior(object, ...)## S3 method for class 'modellist' minnesota_prior(object, ...)
object |
a list of class 'modellist'. |
... |
further arguments passed to or from other methods. |
A list of class 'modellist'.
A generic function used to calculate the dynamic multipliers of a model with weakly exogenous variables. The function invokes particular methods which depend on the class of the first argument.
multipliers(x, ...)multipliers(x, ...)
x |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
A dynamic multiplier is the response of the endogenous variables of a model to a change in one of its weakly exogenous variables. It is what an impulse response is for a shock to an error term, for a variable the model does not explain: the exogenous variable is moved by hand and the endogenous ones are followed.
The quantity is central to models whose foreign block is weakly exogenous, such as the country models of a global VAR (Pesaran, Schuermann and Weiner, 2004), where the responses to a change in the foreign variables are what the country model has to say about the rest of the world without the rest of the world being solved.
The value returned by the method for the class of x, as
described on the pages of the methods.
Pesaran, M. H., Schuermann, T., Weiner, S. M. (2004). Modeling regional interdependencies using a global error-correcting macroeconometric model. Journal of Business & Economic Statistics, 22(2), 129-162.
Methods: multipliers.bvarmodel,
multipliers.bvecmodel.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
Computes the response of an endogenous variable to a change in a weakly exogenous variable of an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' multipliers( x, impulse = NULL, response = NULL, n_ahead = 5, ci = 0.95, shock = 1, type = "permanent", cumulative = FALSE, keep_draws = FALSE, period = NULL, ... )## S3 method for class 'bvarmodel' multipliers( x, impulse = NULL, response = NULL, n_ahead = 5, ci = 0.95, shock = 1, type = "permanent", cumulative = FALSE, keep_draws = FALSE, period = NULL, ... )
x |
an object of class 'bvarmodel' with at least one exogenous variable. |
impulse |
name of the exogenous variable that is moved. |
response |
name of the endogenous variable whose response is returned. |
n_ahead |
number of steps ahead. Zero is allowed and returns the impact response alone. |
ci |
a numeric between 0 and 1 specifying the probability mass covered by the credible intervals. Defaults to 0.95. |
shock |
size of the change in the exogenous variable, in its own units. Defaults to one. |
type |
|
cumulative |
logical specifying whether the responses should be cumulated. |
keep_draws |
logical specifying whether the function should return all
draws of the posterior multipliers. Defaults to |
period |
integer. Index of the period the coefficients are taken from.
Only used for models with time varying parameters. Defaults to |
... |
further arguments passed to or from other methods. |
For the model
where is weakly exogenous, the dynamic multipliers are
obtained from the recursion
with for and the unit vector that selects
the exogenous variable in impulse. The sum over is what
makes the change permanent: the variable is one unit higher from period zero
on, so every lag of it that has come into range contributes. With
type = "transitory" the variable is one unit higher in period zero
alone, the sum collapses to , and the response returns to zero
unless the endogenous block has a unit root.
The deterministic terms and the errors play no part: a multiplier is a difference between two paths of the same model that differ only in the exogenous variable, so everything both paths share cancels. The responses are in the units of the endogenous variables per unit of the exogenous one, and they are computed draw by draw, so what is returned is a posterior distribution of multipliers rather than a point estimate of them.
Whether the multipliers settle down is a property of the endogenous block
alone. If the companion matrix of the has a root on or outside the
unit circle – which is the normal case for a model in levels whose variables
are integrated – a permanent change moves the endogenous variables
permanently, and the multipliers converge to a level rather than to zero.
A time-series object of class 'bvarirf', which is what
irf returns, so that the same plot method applies.
Pesaran, M. H., Schuermann, T., Weiner, S. M. (2004). Modeling regional interdependencies using a global error-correcting macroeconometric model. Journal of Business & Economic Statistics, 22(2), 129-162.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
data("e1") e1 <- diff(log(e1)) * 100 # Investment and income as endogenous, consumption as weakly exogenous model <- create_bvarmodel(data = e1[, c("invest", "income")], exogen = e1[, "cons", drop = FALSE], p = 2, s = 1, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_posterior_coefficients(add_initial_values(model)) dm <- multipliers(model, impulse = "cons", response = "income", n_ahead = 8) plot(dm)data("e1") e1 <- diff(log(e1)) * 100 # Investment and income as endogenous, consumption as weakly exogenous model <- create_bvarmodel(data = e1[, c("invest", "income")], exogen = e1[, "cons", drop = FALSE], p = 2, s = 1, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) model <- add_posterior_coefficients(add_initial_values(model)) dm <- multipliers(model, impulse = "cons", response = "income", n_ahead = 8) plot(dm)
Computes the response of an endogenous variable to a change in a weakly exogenous variable of an object of class 'bvecmodel'.
## S3 method for class 'bvecmodel' multipliers(x, ...)## S3 method for class 'bvecmodel' multipliers(x, ...)
x |
an object of class 'bvecmodel' with at least one exogenous variable. |
... |
arguments of |
A multiplier is a statement about the levels of the endogenous variables, so
the model is put into its levels form with vec_to_var and the
multipliers of that form are returned. The transformation is exact, and it is
where the error correction term does its work: the long-run relations enter
the levels coefficients, so a change in an exogenous variable that belongs to
a cointegrating relation moves the endogenous variables permanently, while at
rank zero it moves them only through the short-run terms.
The responses are therefore in the units of the levels of the endogenous variables, whatever the error correction form has on its left-hand side.
A time-series object of class 'bvarirf', which is what
irf returns, so that the same plot method applies.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
data("e6") set.seed(1) exogen <- ts(cbind(g = as.numeric(e6[, "R"]) * 0.3 + rnorm(nrow(e6), sd = 0.1)), start = start(e6), frequency = frequency(e6)) model <- create_bvecmodel(data = e6, exogen = exogen, p = 2, s = 1, r = 1, const = "unrestricted", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = 3, scale = 0.0001)) model <- add_posterior_coefficients(add_initial_values(model)) dm <- multipliers(model, impulse = "g", response = "R", n_ahead = 8)data("e6") set.seed(1) exogen <- ts(cbind(g = as.numeric(e6[, "R"]) * 0.3 + rnorm(nrow(e6), sd = 0.1)), start = start(e6), frequency = frequency(e6)) model <- create_bvecmodel(data = e6, exogen = exogen, p = 2, s = 1, r = 1, const = "unrestricted", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = 3, scale = 0.0001)) model <- add_posterior_coefficients(add_initial_values(model)) dm <- multipliers(model, impulse = "g", response = "R", n_ahead = 8)
Opens a model written with write_to_hdf5 and returns a handle
to it, which the analysis functions work through a piece of the chain at a
time rather than reading every draw into the session.
open_model(filename, group = "") ## S3 method for class 'bvarfile' print(x, ...)open_model(filename, group = "") ## S3 method for class 'bvarfile' print(x, ...)
filename |
path to an HDF5 file holding a model. |
group |
the group the model's tree hangs under inside its file, as
|
x |
an object of class 'bvarfile'. |
... |
further arguments passed to or from other methods. |
The draws of a model are what it is large in. A model with time varying coefficients keeps a path per draw, and a global model solved from many sub-models keeps a square matrix per lag and draw, so a chain that a posterior summary is comfortable with is a chain an analysis cannot hold beside everything else it needs.
A handle carries what a model is – its specification, its data and its priors – and the length of its chain, but none of the draws. The methods for it read the draws in pieces and keep only what they are asked for: the responses of an impulse response, the shares of a variance decomposition. What they return is what the same call on the model in memory returns.
A list of class 'bvarfile' with the elements filename,
group, model, data, priors and draws, the
number of draws in the file.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) file <- file.path(tempdir(), "bvartools-example-model.h5") unlink(file) write_to_hdf5(model, filename = file) stored <- open_model(file) stored # The analysis reads the draws in pieces ir <- irf(stored, impulse = "invest", response = "income", n_ahead = 5, chunk = 25)# Load data data("e1") e1 <- diff(log(e1)) * 100 model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), sigma = list(df = 1, scale = .0001)) model <- add_posterior_coefficients(add_initial_values(model)) file <- file.path(tempdir(), "bvartools-example-model.h5") unlink(file) write_to_hdf5(model, filename = file) stored <- open_model(file) stored # The analysis reads the draws in pieces ir <- irf(stored, impulse = "invest", response = "income", n_ahead = 5, chunk = 25)
Opens a folder written with write_to_hdf5 and returns a handle
to the models in it, which the estimation steps work on one at a time rather
than reading all of them into the session.
open_models(folder) ## S3 method for class 'bvarfolder' print(x, ...) model_files(x, models = NULL)open_models(folder) ## S3 method for class 'bvarfolder' print(x, ...) model_files(x, models = NULL)
folder |
path to a folder holding models in HDF5 files. |
x |
an object of class 'bvarfolder'. |
... |
further arguments passed to or from other methods. |
models |
character vector of the models to name, as the manifest names
them, or |
read_models_from_folder reads a folder into a list, draws and
all, which is what to do with models that fit. Many do not. A lag and rank
grid is dozens of models, an expanding window is one per quarter, and a model
with time varying coefficients keeps a coefficient path per draw, so a folder
can be tens of gigabytes while each model in it is a few hundred megabytes.
A handle carries what the folder holds – a row per model, saying where it is
and what it is – and none of the draws. map_models and the
estimation steps for a handle then read one model, change it, write it back
and drop it, so a step costs one model per worker rather than the whole
folder. open_model is the same idea for one model whose chain is
too long to hold: a handle to a file, read a piece at a time.
The manifest is built by reading the specification of every model, which is a
set of attributes rather than any of its data, so opening a folder is cheap.
A model is named by where its file sits below folder, without the
extension, and by its group where a file holds more than one – the names
read_models_from_folder gives.
model_files names the files the models lie in, which is what a program
that works on the files is pointed at. With
bayests_files a folder is estimated as
run <- bayests_files(executable = "/opt/bayests/bin/bayests") run(model_files(stored), jobs = 6)
and the draws never pass through R. Files are named once however many models they hold, since BayesTS works through every model in a file it is given.
A list of class 'bvarfolder' with the elements folder and
manifest, a data frame with the columns model, file,
group and the specification of each model.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("e1") train <- diff(log(e1)) * 100 models <- create_bvarmodel(data = train, p = 1:3, deterministic = "const", iterations = 20, burnin = 10) folder <- file.path(tempdir(), "bvartools-example-folder") unlink(folder, recursive = TRUE) dir.create(folder, recursive = TRUE) write_to_hdf5(models, folder = folder) stored <- open_models(folder) stored stored[["manifest"]][, c("model", "p", "iterations")]data("e1") train <- diff(log(e1)) * 100 models <- create_bvarmodel(data = train, p = 1:3, deterministic = "const", iterations = 20, burnin = 10) folder <- file.path(tempdir(), "bvartools-example-folder") unlink(folder, recursive = TRUE) dir.create(folder, recursive = TRUE) write_to_hdf5(models, folder = folder) stored <- open_models(folder) stored stored[["manifest"]][, c("model", "p", "iterations")]
A generic function used to calculate the persistence profiles of the cointegrating relations of a model.
persistence_profiles(object, ...)persistence_profiles(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Pesaran, M. H., & Shin, Y. (1996). Cointegration and speed of convergence to equilibrium. Journal of Econometrics, 71(1-2), 117–143. doi:10.1016/0304-4076(94)01697-6
Methods: persistence_profiles.bvecmodel.
Calculates the persistence profiles of the cointegrating relations of an object of class 'bvecmodel'.
## S3 method for class 'bvarmodel' persistence_profiles(object, ...) ## S3 method for class 'bvecmodel' persistence_profiles( object, n_ahead = 20, ci = 0.95, keep_draws = FALSE, period = NULL, ... ) ## S3 method for class 'modellist' persistence_profiles(object, ...) ## S3 method for class 'expandingwindow' persistence_profiles(object, ...)## S3 method for class 'bvarmodel' persistence_profiles(object, ...) ## S3 method for class 'bvecmodel' persistence_profiles( object, n_ahead = 20, ci = 0.95, keep_draws = FALSE, period = NULL, ... ) ## S3 method for class 'modellist' persistence_profiles(object, ...) ## S3 method for class 'expandingwindow' persistence_profiles(object, ...)
object |
an object of class 'bvecmodel', usually, the result of a call
to |
... |
further arguments passed to or from other methods. |
n_ahead |
the number of horizons the profile is followed over. |
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
keep_draws |
logical. If |
period |
the period of a model with time varying coefficients the
profile is calculated at. Defaults to |
The persistence profile of Pesaran and Shin (1996) is the response of a cointegrating relation to a system-wide shock, scaled to one on impact:
where are the moving average coefficients of the level VAR the
model implies, , and is the covariance of its
errors. It starts at one by construction.
A profile that does not fall to zero says the relation is not cointegrating, whatever the rank says. That is what the statistic is for: a rank chosen by a test or a criterion is an assertion about how many stationary combinations exist, and the profile is the check on it. How quickly the profile falls is the speed of convergence to equilibrium.
Unlike irf and fevd, which a VEC model reaches
through vec_to_var, this statistic cannot be taken from the
level VAR alone: vec_to_var drops beta, and the profile is a
statement about the cointegrating vectors themselves. The level form is used
for the moving average coefficients and the model's own beta for the
relations.
For a model with weakly exogenous variables the profile is partial.
A cointegrating vector of a VECX model spans the domestic variables and the
weakly exogenous ones, and only the domestic block responds to a shock to
this model. The relation is therefore followed over the part of it this model
governs, which is the whole relation only where the model has no
exogen. Where the weakly exogenous variables are endogenous to a
larger system – a global model assembled from sub-models – take the profile
there instead, and the function warns to that effect.
A list with one element per cointegrating relation, each a matrix
with one row per horizon and, unless keep_draws is TRUE,
the columns median, lower and upper.
Pesaran, M. H., & Shin, Y. (1996). Cointegration and speed of convergence to equilibrium. Journal of Econometrics, 71(1-2), 117–143. doi:10.1016/0304-4076(94)01697-6
persistence_profiles for the generic.
# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 0.0001)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) profiles <- persistence_profiles(model, n_ahead = 12) round(profiles[[1]][1:5, ], 3)# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- add_priors(model, coef = list(v_i = 0, v_i_det = 0), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 0.0001)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) profiles <- persistence_profiles(model, n_ahead = 12) round(profiles[[1]][1:5, ], 3)
Plots the forecast errors of a list of Bayesian models as error bars for each period, for which a forecast was made.
plot_forecast_errors_by_period( x, criterion = "AFE", ci = 0.95, col = "black", pch = 20, cex = 1, lwd = 1, main = NULL, xlab = "Period", ... )plot_forecast_errors_by_period( x, criterion = "AFE", ci = 0.95, col = "black", pch = 20, cex = 1, lwd = 1, main = NULL, xlab = "Period", ... )
x |
an object of class 'bvarmodel', 'bvecmodel', 'expandingwindow' or
'modellist', which contains forecast errors. Usually, a result of a call to
|
criterion |
the statistic that should be plotted. Available choices are
|
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
col |
a vector of colours, which is recycled over the models in |
pch |
the plotting symbol used for the mean of a model. |
cex |
the size of the plotting symbol used for the mean of a model. |
lwd |
a vector of line widths, which is recycled over the models in |
main |
the title of the plot. If |
xlab |
the label of the x-axis. If |
... |
further graphical parameters, which are passed on to
|
Each row of the plot corresponds to an endogenous variable, each column
to a forecast horizon and the x-axis to the period, for which a forecast was
made. Within a period each model is represented by an error bar, which covers
the credible band of the respective statistic and which is marked by the median
and the mean of the posterior draws of its forecast errors. The position of a
model in x is added above its error bar. For criterion = "FE" a
horizontal reference line is added at zero.
In contrast to plot.selcritlist, which plots statistics that are
calculated across all periods of the evaluation sample, this function plots the
statistics of each period separately. Thus, it is most useful for forecast errors,
which were obtained for multiple periods as, for example, in the case of
expanding window estimation. For objects of class 'expandingwindow' the forecast
errors of all estimation windows of a model are combined, where the period of an
error is obtained from the end of the training sample of the respective window.
x, invisibly. The function is called for its side effect, the
plot.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
data("us_macrodata") # AR(1) models as benchmark model <- create_bvarmodel(data = us_macrodata, p = 1:2, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = 2007) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = us_macrodata) # Plot absolute forecast errors of each period plot_forecast_errors_by_period(model)data("us_macrodata") # AR(1) models as benchmark model <- create_bvarmodel(data = us_macrodata, p = 1:2, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = 2007) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = us_macrodata) # Plot absolute forecast errors of each period plot_forecast_errors_by_period(model)
Plots the log predictive density of each evaluated period for one or more Bayesian models, either period by period or as a running sum.
plot_predictive_loglik( x, baseline = NULL, cumulative = TRUE, col = "black", lwd = 1, lty = 1, legend = TRUE, legend_position = "topleft", main = NULL, xlab = "Period", ylab = NULL, ... )plot_predictive_loglik( x, baseline = NULL, cumulative = TRUE, col = "black", lwd = 1, lty = 1, legend = TRUE, legend_position = "topleft", main = NULL, xlab = "Period", ylab = NULL, ... )
x |
an object of class 'selcrit' or 'selcritlist' whose entries contain
the log predictive likelihood, usually a result of a call to
|
baseline |
the model every other model is compared with, given as its
position in |
cumulative |
logical. Should the running sum over the periods be plotted
( |
col |
a vector of colours, which is recycled over the models in |
lwd |
a vector of line widths, which is recycled over the models in
|
lty |
a vector of line types, which is recycled over the models in
|
legend |
logical. Should a legend of the models be added? |
legend_position |
the position of the legend, passed on to
|
main |
the title of the plot. If |
xlab |
the label of the x-axis. |
ylab |
the label of the y-axis. If |
... |
further graphical parameters, which are passed on to
|
The log predictive likelihood of a model is the sum of the log
predictive densities of the periods it was evaluated for, and
selection_criteria reports that sum with a band. This function
plots the terms of the sum, which answers a question the sum cannot: whether a
difference between two models is a steady advantage or the consequence of a
few periods. A single quarter can decide a comparison of this kind, and with
cumulative = TRUE such a quarter is a step in an otherwise flat line
rather than a number hidden in a total.
With a baseline the plot shows differences, the cumulative sum
of over the evaluated periods, and a
horizontal reference line is drawn at zero. A line that ends above zero
belongs to a model that predicted better than the baseline over the whole
evaluation sample, and the slope at any point is how much better it was
predicting then. Differences are what the criterion is read in, so a baseline
is usually what is wanted as soon as there is more than one model; without one
the lines are dominated by the periods that were hard for every model alike.
The periods come from attribute "terms" of the LPL entry of each
model, which also holds the numerical standard error of each period. Models are
plotted over the periods they share with the baseline, and a model without an
LPL entry is left out with a warning.
x, invisibly. The function is called for its side effect, the
plot.
selection_criteria for the sum and its band,
add_predictive_loglik for the draws it is computed from, and
plot_forecast_errors_by_period for the same question asked of
forecast errors.
data("us_macrodata") # Two specifications to compare models <- create_bvarmodel(data = us_macrodata, p = 1:2, deterministic = "const", iterations = 100, burnin = 50) models <- add_priors(models, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = 3, scale = 1)) # One window per evaluated period windows <- lapply(models, use_expanding_window, start = c(1972, 1)) criteria <- lapply(windows, function(w) { w <- add_initial_values(w) w <- add_posterior_coefficients(w) w <- add_predictive_loglik(w) selection_criteria(w) }) class(criteria) <- append("selcritlist", class(criteria)) plot_predictive_loglik(criteria, baseline = 1)data("us_macrodata") # Two specifications to compare models <- create_bvarmodel(data = us_macrodata, p = 1:2, deterministic = "const", iterations = 100, burnin = 50) models <- add_priors(models, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = 3, scale = 1)) # One window per evaluated period windows <- lapply(models, use_expanding_window, start = c(1972, 1)) criteria <- lapply(windows, function(w) { w <- add_initial_values(w) w <- add_posterior_coefficients(w) w <- add_predictive_loglik(w) selection_criteria(w) }) class(criteria) <- append("selcritlist", class(criteria)) plot_predictive_loglik(criteria, baseline = 1)
A plot function for objects of class "bvarfevd".
## S3 method for class 'bvarfevd' plot(x, max_groups = NULL, ...)## S3 method for class 'bvarfevd' plot(x, max_groups = NULL, ...)
x |
an object of class "bvarfevd", usually, a result of a call to |
max_groups |
integer. Maximum number of variables shown in the plot. The
|
... |
further graphical parameters. |
x, invisibly. The function is called for its side effect, the
plot.
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Obtain FEVD vd <- fevd(object, response = "cons") # Plot plot(vd)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Obtain FEVD vd <- fevd(object, response = "cons") # Plot plot(vd)
Stacked bars of the contributions of the shocks in each period, and the part of the response they account for as a line.
## S3 method for class 'bvarhd' plot(x, baseline = FALSE, ...)## S3 method for class 'bvarhd' plot(x, baseline = FALSE, ...)
x |
an object of class |
baseline |
logical: should the baseline be stacked with the shocks?
Defaults to |
... |
further arguments passed to |
x, invisibly.
A plot function for objects of class "bvarirf".
## S3 method for class 'bvarirf' plot(x, ...)## S3 method for class 'bvarirf' plot(x, ...)
x |
an object of class "bvarirf", usually, a result of a call to |
... |
further graphical parameters. |
x, invisibly. The function is called for its side effect, the
plot.
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Calculate IR ir <- irf(object, impulse = "invest", response = "cons") # Plot IR plot(ir)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Calculate IR ir <- irf(object, impulse = "invest", response = "cons") # Plot IR plot(ir)
A plot function for objects of class 'bvarmodel'.
## S3 method for class 'bvarmodel' plot(x, ci = 0.95, type = "hist", show_zero_y = TRUE, max_cols = 6, ...)## S3 method for class 'bvarmodel' plot(x, ci = 0.95, type = "hist", show_zero_y = TRUE, max_cols = 6, ...)
x |
an object of class 'bvarmodel'. |
ci |
interval used to calculate credible bands for time-varying parameters. |
type |
either |
show_zero_y |
if |
max_cols |
an integer of the maximum number of regressors per figure. A block with more regressors than this is drawn as several figures of nearly equal width. Defaults to 6. |
... |
further graphical parameters. |
The function draws one figure per block of coefficients – the lags of the endogenous variables, the exogenous variables, the deterministic terms, the contemporaneous endogenous variables of a structural model, and the covariance matrix of the error term – instead of one figure for the whole model. A model with many regressors would otherwise produce panels too small to read.
A plot per block of coefficients.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Plot plot(model, type = "hist") plot(model, type = "trace") plot(model, type = "boxplot")# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Plot plot(model, type = "hist") plot(model, type = "trace") plot(model, type = "boxplot")
A plot function for objects of class 'bvarprd'.
## S3 method for class 'bvarprd' plot(x, n_pre = NULL, ci = 0.95, ...)## S3 method for class 'bvarprd' plot(x, n_pre = NULL, ci = 0.95, ...)
x |
an object of class 'bvarprd', usually, a result of a call to |
n_pre |
number of plotted observations that precede the forecasts. If |
ci |
interval used to calculate the credible bands of the forecasts. |
... |
further graphical parameters. Arguments |
x, invisibly. The function is called for its side effect, the
plot.
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add the data the forecasts are produced from model <- add_forecast_input(model, n_ahead = 10) # Simulate the forecasts model <- add_posterior_forecasts(model) # Collect them pred <- predict(model) # Plot forecasts plot(pred)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add the data the forecasts are produced from model <- add_forecast_input(model, n_ahead = 10) # Simulate the forecasts model <- add_posterior_forecasts(model) # Collect them pred <- predict(model) # Plot forecasts plot(pred)
A plot function for objects of class 'bvarprdlist'.
## S3 method for class 'bvarprdlist' plot(x, n_pre = NULL, ci = 0.95, ...)## S3 method for class 'bvarprdlist' plot(x, n_pre = NULL, ci = 0.95, ...)
x |
an object of class 'bvarprdlist', usually, a result of a call to
|
n_pre |
number of plotted observations that precede the forecasts.
If |
ci |
interval used to calculate the credible bands of the forecasts. |
... |
further graphical parameters, which are passed on to
|
The forecasts of the models in x are plotted on a grid, where
each column corresponds to a model and each row to an endogenous variable.
x, invisibly. The function is called for its side effect, the
plot of the forecasts.
Plots the directional connectedness measures of Diebold and Yilmaz (2012).
## S3 method for class 'bvarspillover' plot(x, which = "net", ...)## S3 method for class 'bvarspillover' plot(x, which = "net", ...)
x |
an object of class 'bvarspillover', usually the result of a call to
|
which |
which measure to plot. One of |
... |
further arguments passed to |
One bar per variable, with the credible interval drawn on it where the object carries one. Net values above zero mark variables that transmit more forecast error variance than they receive.
NULL, invisibly. Called for its side effect.
Plot a Rolling Spillover Index
## S3 method for class 'bvarspilloverts' plot(x, ...)## S3 method for class 'bvarspilloverts' plot(x, ...)
x |
an object of class 'bvarspilloverts'. |
... |
further arguments passed to |
NULL, invisibly. Called for its side effect.
A plot function for objects of class 'bvecmodel'.
## S3 method for class 'bvecmodel' plot(x, ci = 0.95, type = "hist", show_zero_y = TRUE, max_cols = 6, ...)## S3 method for class 'bvecmodel' plot(x, ci = 0.95, type = "hist", show_zero_y = TRUE, max_cols = 6, ...)
x |
an object of class 'bvecmodel'. |
ci |
interval used to calculate credible bands for time-varying parameters. |
type |
either |
show_zero_y |
if |
max_cols |
an integer of the maximum number of regressors per figure. A block with more regressors than this is drawn as several figures of nearly equal width. Defaults to 6. |
... |
further graphical parameters. |
The coefficients of the error correction term are displayed as draws
of the cointegration matrix and not as draws
of the loading matrix and the cointegration matrix
separately. The latter two are only identified up to a rotation, so their
individual draws are not informative, while their product is.
The function draws one figure per block of coefficients – the cointegration matrix, the lagged differenced endogenous variables, the differenced exogenous variables, the deterministic terms, the contemporaneous endogenous variables of a structural model, and the covariance matrix of the error term – instead of one figure for the whole model. A model with many regressors would otherwise produce panels too small to read.
A plot per block of coefficients.
# Load data data("e6") e6 <- e6 * 100 # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "restricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Plot plot(model, type = "hist") plot(model, type = "trace") plot(model, type = "boxplot")# Load data data("e6") e6 <- e6 * 100 # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "restricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Plot plot(model, type = "hist") plot(model, type = "trace") plot(model, type = "boxplot")
A plot function for objects of class 'expandwindbvarprdlist'.
## S3 method for class 'expandwindbvarprdlist' plot(x, n_pre = NULL, ci = 0.95, ...)## S3 method for class 'expandwindbvarprdlist' plot(x, n_pre = NULL, ci = 0.95, ...)
x |
an object of class 'expandwindbvarprdlist', usually, a result of a call to
|
n_pre |
number of plotted observations that precede the forecasts.
If |
ci |
interval used to calculate the credible bands of the forecasts. |
... |
further graphical parameters, which are passed on to
|
x, invisibly. The function is called for its side effect, the
plot of the forecasts.
A plot function for objects of class 'modellist'.
## S3 method for class 'modellist' plot(x, ...)## S3 method for class 'modellist' plot(x, ...)
x |
an object of class 'modellist'. |
... |
arguments passed forward to other methods. |
x, invisibly. The function is called for its side effect, one
plot per model in the list, drawn by the plot method of that model.
A plot function for objects of class 'selcritlist' and 'selcrit'.
## S3 method for class 'selcritlist' plot(x, criterion = "WAIC", ...) ## S3 method for class 'selcrit' plot(x, criterion = "WAIC", ...)## S3 method for class 'selcritlist' plot(x, criterion = "WAIC", ...) ## S3 method for class 'selcrit' plot(x, criterion = "WAIC", ...)
x |
an object of class 'selcritlist' or 'selcrit', usually, a result of a
call to |
criterion |
the selection criterion that should be plotted. Available choices
are the in-sample criteria |
... |
further graphical parameters. |
For in-sample criteria each model is represented by a horizontal error
bar, which is marked by the value of the criterion. The log-likelihood has a
posterior distribution, so its bar covers the credible band and is marked by the
median as well as the mean of its draws. "WAIC", "LOOIC" and
"LPL" are
point estimates whose bars cover a normal interval built from their standard
error. The interval of "LPL" is the one of
selection_criteria, around the sum of the log predictive
densities of the evaluated periods;
plot_predictive_loglik plots the terms of that sum, which is
where a difference between two models can be seen to be steady or to rest on
a few periods. "AIC", "BIC", "HQ" and "LML" are point estimates without a
standard error, so they are drawn as a single point. The default is
"WAIC", for the reasons given in selection_criteria.
The criterion is measured on
the x-axis and the models are arranged along the y-axis, beginning with the first
model of x at the top. This keeps the plot readable, if x contains
many models. The position of a model in x is added at the upper end of its
error bar.
The specifications of the models are used as labels of the y-axis, where only the
specifications that differ across the models are used, as in
print.modellist. The lag order is always used. The left margin is
adjusted to the width of the labels.
No title is added by default. Space above the plot is only used, if argument
main is specified.
For out-of-sample statistics each row of the plot corresponds to an endogenous
variable and the x-axis to the forecast horizon. Within a forecast horizon each
model is represented by an error bar, which covers the credible band of the
respective statistic and which is marked by the median and the mean of its
posterior draws. The position of a model in x is added above its error
bar. Since forecast errors can be positive and negative, a horizontal reference
line is added at zero for criterion = "FE".
For both types of criteria arguments col, pch, cex,
lwd, main and xlab can be used to change the appearance of
the plot, where col and lwd are recycled over the models in
x.
A 'selcrit' – the criteria of one model, or those of the windows of an 'expandingwindow' pooled into one – is drawn as a 'selcritlist' of that one model.
x, invisibly. The function is called for its side effect, the
plot.
Combines the forecasts of several models into one equal-weight pool, which is compared with the models like any of them.
pool_forecasts(...) ## S3 method for class 'forecastpool' add_priors(object, ...) ## S3 method for class 'forecastpool' add_initial_values(object, ...) ## S3 method for class 'forecastpool' add_seed(object, seed, ...) ## S3 method for class 'forecastpool' add_posterior_coefficients(object, ...) ## S3 method for class 'forecastpool' add_posterior_loglik(object, ...) ## S3 method for class 'forecastpool' add_forecast_input(object, ...) ## S3 method for class 'forecastpool' add_posterior_forecasts(object, ...) ## S3 method for class 'forecastpool' add_predictive_loglik(object, ...) ## S3 method for class 'forecastpool' thin(x, thin = 10, ...) ## S3 method for class 'poolwindow' add_priors(object, ...) ## S3 method for class 'poolwindow' add_initial_values(object, ...) ## S3 method for class 'poolwindow' add_seed(object, seed, ...) ## S3 method for class 'poolwindow' add_posterior_coefficients(object, ...) ## S3 method for class 'poolwindow' add_posterior_loglik(object, ...) ## S3 method for class 'poolwindow' add_forecast_input(object, ...) ## S3 method for class 'poolwindow' add_posterior_forecasts(object, ...) ## S3 method for class 'poolwindow' add_predictive_loglik(object, ...) ## S3 method for class 'poolwindow' thin(x, thin = 10, ...) ## S3 method for class 'forecastpool' write_to_hdf5(object, ...) ## S3 method for class 'poolwindow' write_to_hdf5(object, ...) ## S3 method for class 'forecastpool' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'poolwindow' print(x, digits = max(3L, getOption("digits") - 3L), ...)pool_forecasts(...) ## S3 method for class 'forecastpool' add_priors(object, ...) ## S3 method for class 'forecastpool' add_initial_values(object, ...) ## S3 method for class 'forecastpool' add_seed(object, seed, ...) ## S3 method for class 'forecastpool' add_posterior_coefficients(object, ...) ## S3 method for class 'forecastpool' add_posterior_loglik(object, ...) ## S3 method for class 'forecastpool' add_forecast_input(object, ...) ## S3 method for class 'forecastpool' add_posterior_forecasts(object, ...) ## S3 method for class 'forecastpool' add_predictive_loglik(object, ...) ## S3 method for class 'forecastpool' thin(x, thin = 10, ...) ## S3 method for class 'poolwindow' add_priors(object, ...) ## S3 method for class 'poolwindow' add_initial_values(object, ...) ## S3 method for class 'poolwindow' add_seed(object, seed, ...) ## S3 method for class 'poolwindow' add_posterior_coefficients(object, ...) ## S3 method for class 'poolwindow' add_posterior_loglik(object, ...) ## S3 method for class 'poolwindow' add_forecast_input(object, ...) ## S3 method for class 'poolwindow' add_posterior_forecasts(object, ...) ## S3 method for class 'poolwindow' add_predictive_loglik(object, ...) ## S3 method for class 'poolwindow' thin(x, thin = 10, ...) ## S3 method for class 'forecastpool' write_to_hdf5(object, ...) ## S3 method for class 'poolwindow' write_to_hdf5(object, ...) ## S3 method for class 'forecastpool' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'poolwindow' print(x, digits = max(3L, getOption("digits") - 3L), ...)
... |
two or more models with forecasts: objects of class
|
object, x
|
an object of class |
seed |
not used, since a pool is not simulated. |
thin |
an integer specifying the thinning interval between successive draws. |
digits |
the number of significant digits. |
A pool of forecasts is a mixture of predictive distributions: the predictive distribution of the pool is the average of those of its members. Combining forecasts in this way is one of the most reliable ways of improving them, because the errors of different models are not perfectly correlated and no single specification is best in every period (Bates and Granger, 1969; Hall and Mitchell, 2007; Geweke and Amisano, 2011).
The pool is built from draws the members already hold. For every forecast,
the same number of draws is taken at random from each member – as many as
the member with the fewest draws has – and stacked, so that every member
has the same weight. The draws are selected with R's random number
generator, so set.seed() makes a pool reproducible.
The members must forecast the same thing. The pool contains the endogenous variables all members share, and the forecast horizons all of them reach. A variable forecast by only some of the members is left out, and a pool of models that share no variable is refused. A VEC model forecasts the levels of its variables, so it can be pooled with VAR models of the same levels, but not with VAR models of their growth rates. Forecasts aggregated to annual figures can only be pooled with forecasts aggregated in the same way.
The windows of expanding window exercises are matched by the end of their
estimation samples, so that each pooled forecast combines forecasts made with
the same information. Windows that not every member has are left out, with a
message. Single models and expanding windows cannot be pooled with each
other, and external forecasts, which are point forecasts rather than
predictive distributions, cannot be pooled at all: they are compared beside a
pool, by combining both with combine_models.
The log predictive densities that add_predictive_loglik and
the forecasts of BayesTS provide are pooled as the forecasts are, which gives
the log of the average predictive density of the members – the score of the
mixture, not of its draws. They are kept only if every member carries them
and all members have the same endogenous variables, because a predictive
density is a joint density of all the variables of a model.
The weights are equal. Weights that favour members which forecast better in the past must only use the periods before each forecast, or they flatter the pool with information it did not have.
A pool is formed after the members' forecasts are drawn, and the
functions that estimate a model leave it unchanged. It can be passed to
add_forecast_errors and selection_criteria, and
included in a list of models with combine_models. It cannot be
written to a file: write its members and form the pool again after reading
them back.
A pool is formed from draws its members already hold, so the functions that
add priors, initial values, posterior draws, forecasts or predictive
log-likelihoods to a model return it unchanged. This allows to combine a pool
with its members in a list of class "modellist" and to apply the usual
workflow to all elements of that list.
An object of class "forecastpool", which behaves like an
expanding window exercise, or, if single models were pooled, a single pooled
forecast of class "poolwindow". Each pooled forecast holds the draws
of the pool in posterior$forecast$forecasts and, in model,
the names of the members in members and the number of draws taken from
each in draws.
Bates, J. M., & Granger, C. W. J. (1969). The combination of forecasts. Journal of the Operational Research Society, 20(4), 451–468. doi:10.1057/jors.1969.103
Geweke, J., & Amisano, G. (2011). Optimal prediction pools. Journal of Econometrics, 164(1), 130–141. doi:10.1016/j.jeconom.2011.02.017
Hall, S. G., & Mitchell, J. (2007). Combining density forecasts. International Journal of Forecasting, 23(1), 1–13. doi:10.1016/j.ijforecast.2006.08.001
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e1") e1 <- diff(log(e1)) * 100 train <- window(e1, end = c(1978, 4)) # Two specifications, each estimated over expanding windows model <- create_bvarmodel(train, p = 1:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 1 / 10, v_i_det = 1 / 100), sigma = list(df = "k", scale = 1)) model <- use_expanding_window(model, start = c(1978, 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) model <- add_forecast_input(model, n_ahead = 2) model <- add_posterior_forecasts(model) # The equal-weight pool of both set.seed(123) pool <- pool_forecasts(p1 = model[[1]], p2 = model[[2]]) # Scored and compared like the models all_models <- combine_models(model, pool) all_models <- add_forecast_errors(all_models, test_sample = e1) selection_criteria(all_models)# Load data data("e1") e1 <- diff(log(e1)) * 100 train <- window(e1, end = c(1978, 4)) # Two specifications, each estimated over expanding windows model <- create_bvarmodel(train, p = 1:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burn-in should be much higher. model <- add_priors(model, coef = list(v_i = 1 / 10, v_i_det = 1 / 100), sigma = list(df = "k", scale = 1)) model <- use_expanding_window(model, start = c(1978, 1)) model <- add_initial_values(model) model <- add_posterior_coefficients(model) model <- add_forecast_input(model, n_ahead = 2) model <- add_posterior_forecasts(model) # The equal-weight pool of both set.seed(123) pool <- pool_forecasts(p1 = model[[1]], p2 = model[[2]]) # Scored and compared like the models all_models <- combine_models(model, pool) all_models <- add_forecast_errors(all_models, test_sample = e1) selection_criteria(all_models)
post_bvs employs Bayesian variable selection as proposed by Korobilis (2013)
to produce a vector of inclusion parameters for the coefficient matrix
of a VAR model.
post_bvs(y, z, a, k, m, lambda, sigma_i, prob_prior, include = NULL)post_bvs(y, z, a, k, m, lambda, sigma_i, prob_prior, include = NULL)
y |
a |
z |
a |
a |
an M-dimensional vector of parameter draws. If time varying parameters are used,
an |
k |
integer of the number of endogenous variables. |
m |
integer of the number of M |
lambda |
an |
sigma_i |
a sparse |
prob_prior |
an M-dimensional vector of prior inclusion probabilities. |
include |
an integer vector specifying the positions of variables, which should be
included in the BVS algorithm. If |
The function employs Bayesian variable selection as proposed
by Korobilis (2013) to produce a vector of inclusion parameters, which are
the diagonal elements of the inclusion matrix for the VAR model
where .
is a K-dimensional vector of endogenous variables and
is a matrix of regressors with
as a vector of regressors.
A matrix of inclusion parameters on its diagonal.
Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model input, which uses BVS as variable selection algorithm object <- create_bvarmodel(data = e1, p = 2, deterministic = "const", varsel = "bvs") # Add prior specifications, including the prior inclusion probabilities object <- add_priors(object, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1), varsel = list(inprior = .1)) # Add initial values object <- add_initial_values(object) # Obtain data, initial values and priors y <- matrix(t(object[["data"]][["train"]][["y"]])) z <- object[["data"]][["train"]][["z"]] # Argument 'z' is taken dense k <- object[["model"]][["k"]] tt <- nrow(object[["data"]][["train"]][["y"]]) m <- ncol(z) a <- object[["initial"]][["a"]] prob_prior <- object[["priors"]][["a"]][["inprior"]] # Arguments 'lambda' and 'sigma_i' have to be sparse lambda <- Matrix::Matrix(diag(1, m), sparse = TRUE) # Initial value of the inverse error covariance matrix u <- matrix(y - z %*% a, k) sigma_i <- Matrix::Matrix(kronecker(diag(1, tt), solve(tcrossprod(u) / tt)), sparse = TRUE) # Draw inclusion parameters post_bvs(y, z, a, k, m, lambda, sigma_i, prob_prior)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model input, which uses BVS as variable selection algorithm object <- create_bvarmodel(data = e1, p = 2, deterministic = "const", varsel = "bvs") # Add prior specifications, including the prior inclusion probabilities object <- add_priors(object, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1), varsel = list(inprior = .1)) # Add initial values object <- add_initial_values(object) # Obtain data, initial values and priors y <- matrix(t(object[["data"]][["train"]][["y"]])) z <- object[["data"]][["train"]][["z"]] # Argument 'z' is taken dense k <- object[["model"]][["k"]] tt <- nrow(object[["data"]][["train"]][["y"]]) m <- ncol(z) a <- object[["initial"]][["a"]] prob_prior <- object[["priors"]][["a"]][["inprior"]] # Arguments 'lambda' and 'sigma_i' have to be sparse lambda <- Matrix::Matrix(diag(1, m), sparse = TRUE) # Initial value of the inverse error covariance matrix u <- matrix(y - z %*% a, k) sigma_i <- Matrix::Matrix(kronecker(diag(1, tt), solve(tcrossprod(u) / tt)), sparse = TRUE) # Draw inclusion parameters post_bvs(y, z, a, k, m, lambda, sigma_i, prob_prior)
Produces a draw of coefficients for cointegration models with a prior on the cointegration space as proposed in Koop et al. (2010) and a draw of non-cointegration coefficients from a normal density.
post_coint_kls( y, beta, w, sigma_i, v_i, p_tau_i, g_i, x = NULL, gamma_mu_prior = NULL, gamma_v_i_prior = NULL )post_coint_kls( y, beta, w, sigma_i, v_i, p_tau_i, g_i, x = NULL, gamma_mu_prior = NULL, gamma_v_i_prior = NULL )
y |
a |
beta |
a |
w |
a |
sigma_i |
an inverse of the |
v_i |
a numeric between 0 and 1 specifying the shrinkage of the cointegration space prior. |
p_tau_i |
an inverted |
g_i |
a |
x |
a |
gamma_mu_prior |
a |
gamma_v_i_prior |
an inverted |
The function produces posterior draws of the coefficient
matrices , and for the model
where is a K-dimensional vector of differenced endogenous variables.
is an vector of variables in the cointegration term,
which include lagged values of endogenous and exogenous variables in levels and
restricted deterministic terms. is an N-dimensional vector of
differenced endogenous and exogenous explanatory variabes as well as unrestricted
deterministic terms. The error term is .
Draws of the loading matrix are obtained using the prior on the cointegration space
as proposed in Koop et al. (2010). The posterior covariance matrix is
and the posterior mean by
where is a matrix of differenced endogenous variables and
with as an matrix of
variables in the cointegration term.
For a given prior mean vector and prior covariance matrix
the posterior covariance matrix of non-cointegration coefficients in is obtained by
and the posterior mean by
where is an matrix of
explanatory variables, which do not enter the cointegration term.
Draws of the cointegration matrix are obtained using the prior on the cointegration space
as proposed in Koop et al. (2010). The posterior covariance matrix of the unrestricted cointegration
matrix is
and the posterior mean by
where and .
The final draws of and are calculated using
and
.
A named list containing the following elements:
alpha |
a draw of the |
beta |
a draw of the |
Pi |
a draw of the |
Gamma |
a draw of the coefficients of the non-cointegration regressors
in |
Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior simulation for cointegrated models with priors on the cointegration space. Econometric Reviews, 29(2), 224-242. doi:10.1080/07474930903382208
# Load data data("e6") # Generate model data temp <- create_bvecmodel(e6, p = 2, r = 1) y <- t(temp$data$train$y) ect <- t(temp$data$train$w) x <- t(temp$data$train$x) k <- nrow(y) # Endogenous variables tt <- ncol(y) # Number of observations r <- temp$model$rank # Cointegration rank # Priors. They cover the alpha block as well as the Gamma coefficients, # so the length is k * r + k * nrow(x). n_ag <- k * (r + nrow(x)) gamma_mu_prior <- matrix(0, n_ag) gamma_v_i_prior <- diag(0, n_ag) # Initial value of Sigma sigma <- tcrossprod(y) / tt sigma_i <- solve(sigma) # Initial values of beta beta <- matrix(c(1, -4), nrow(ect)) # Draw parameters coint <- post_coint_kls(y = y, beta = beta, w = ect, x = x, sigma_i = sigma_i, v_i = 0, p_tau_i = diag(1, nrow(ect)), g_i = sigma_i, gamma_mu_prior = gamma_mu_prior, gamma_v_i_prior = gamma_v_i_prior)# Load data data("e6") # Generate model data temp <- create_bvecmodel(e6, p = 2, r = 1) y <- t(temp$data$train$y) ect <- t(temp$data$train$w) x <- t(temp$data$train$x) k <- nrow(y) # Endogenous variables tt <- ncol(y) # Number of observations r <- temp$model$rank # Cointegration rank # Priors. They cover the alpha block as well as the Gamma coefficients, # so the length is k * r + k * nrow(x). n_ag <- k * (r + nrow(x)) gamma_mu_prior <- matrix(0, n_ag) gamma_v_i_prior <- diag(0, n_ag) # Initial value of Sigma sigma <- tcrossprod(y) / tt sigma_i <- solve(sigma) # Initial values of beta beta <- matrix(c(1, -4), nrow(ect)) # Draw parameters coint <- post_coint_kls(y = y, beta = beta, w = ect, x = x, sigma_i = sigma_i, v_i = 0, p_tau_i = diag(1, nrow(ect)), g_i = sigma_i, gamma_mu_prior = gamma_mu_prior, gamma_v_i_prior = gamma_v_i_prior)
Produces a draw of coefficients for cointegration models in SUR form with a prior on the cointegration space as proposed in Koop et al. (2010) and a draw of non-cointegration coefficients from a normal density.
post_coint_kls_sur( y, beta, w, sigma_i, v_i, p_tau_i, g_i, x = NULL, gamma_mu_prior = NULL, gamma_v_i_prior = NULL, svd = FALSE )post_coint_kls_sur( y, beta, w, sigma_i, v_i, p_tau_i, g_i, x = NULL, gamma_mu_prior = NULL, gamma_v_i_prior = NULL, svd = FALSE )
y |
a |
beta |
a |
w |
a |
sigma_i |
the inverse of the constant |
v_i |
a numeric between 0 and 1 specifying the shrinkage of the cointegration space prior. |
p_tau_i |
an inverted |
g_i |
a |
x |
a |
gamma_mu_prior |
a |
gamma_v_i_prior |
an inverted |
svd |
logical. If |
The function produces posterior draws of the coefficient
matrices , and for the model
where is a K-dimensional vector of differenced endogenous variables.
is an vector of variables in the cointegration term,
which include lagged values of endogenous and exogenous variables in levels and
restricted deterministic terms. is an N-dimensional vector of
differenced endogenous and exogenous explanatory variabes as well as unrestricted
deterministic terms. The error term is .
Draws of the loading matrix are obtained using the prior on the cointegration space
as proposed in Koop et al. (2010). The posterior covariance matrix is
and the posterior mean by
where is a matrix of differenced endogenous variables and
with as an matrix of
variables in the cointegration term.
For a given prior mean vector and prior covariance matrix
the posterior covariance matrix of non-cointegration coefficients in is obtained by
and the posterior mean by
where is an matrix of
explanatory variables, which do not enter the cointegration term.
Draws of the cointegration matrix are obtained using the prior on the cointegration space
as proposed in Koop et al. (2010). The posterior covariance matrix of the unrestricted cointegration
matrix is
and the posterior mean by
where and .
The final draws of and are calculated using
and
.
A named list containing the following elements:
alpha |
a draw of the |
beta |
a draw of the |
Pi |
a draw of the |
Gamma |
a draw of the coefficients of the non-cointegration regressors
in |
Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior simulation for cointegrated models with priors on the cointegration space. Econometric Reviews, 29(2), 224-242. doi:10.1080/07474930903382208
# Load data data("e6") # Generate model data temp <- create_bvecmodel(e6, p = 1, r = 1) y <- t(temp$data$train$y) ect <- t(temp$data$train$w) k <- nrow(y) # Endogenous variables tt <- ncol(y) # Number of observations # Initial value of Sigma sigma <- tcrossprod(y) / tt sigma_i <- solve(sigma) # Initial values of beta beta <- matrix(c(1, -4), k) # Draw parameters coint <- post_coint_kls_sur(y = y, beta = beta, w = ect, sigma_i = sigma_i, v_i = 0, p_tau_i = diag(1, nrow(ect)), g_i = sigma_i)# Load data data("e6") # Generate model data temp <- create_bvecmodel(e6, p = 1, r = 1) y <- t(temp$data$train$y) ect <- t(temp$data$train$w) k <- nrow(y) # Endogenous variables tt <- ncol(y) # Number of observations # Initial value of Sigma sigma <- tcrossprod(y) / tt sigma_i <- solve(sigma) # Initial values of beta beta <- matrix(c(1, -4), k) # Draw parameters coint <- post_coint_kls_sur(y = y, beta = beta, w = ect, sigma_i = sigma_i, v_i = 0, p_tau_i = diag(1, nrow(ect)), g_i = sigma_i)
Produces a draw of the constant diagonal error variance matrix of the measurement equation of a state space model using an inverse gamma posterior density.
post_gamma_measurement_variance(u, shape_prior, rate_prior, inverse)post_gamma_measurement_variance(u, shape_prior, rate_prior, inverse)
u |
a |
shape_prior |
a |
rate_prior |
a |
inverse |
logical. If |
For a model with measurement equation
with
the function produces a draw of the constant diagonal error variance matrix
.
A matrix.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
k <- 10 # Number of endogenous variables tt <- 1000 # Number of observations set.seed(1234) # Set RNG seed # Generate artificial error series with N(0, 1) u <- matrix(rnorm(k * tt)) # Define priors shape_prior <- matrix(1, k) rate_prior <- matrix(.0001, k) # Obtain posterior draw post_gamma_measurement_variance(u, shape_prior, rate_prior, inverse = FALSE)k <- 10 # Number of endogenous variables tt <- 1000 # Number of observations set.seed(1234) # Set RNG seed # Generate artificial error series with N(0, 1) u <- matrix(rnorm(k * tt)) # Define priors shape_prior <- matrix(1, k) rate_prior <- matrix(.0001, k) # Obtain posterior draw post_gamma_measurement_variance(u, shape_prior, rate_prior, inverse = FALSE)
Produces a draw of the constant diagonal error variance matrix of the state equation of a state space model using an inverse gamma posterior density.
post_gamma_state_variance(a, a_init, shape_prior, rate_prior, inverse)post_gamma_state_variance(a, a_init, shape_prior, rate_prior, inverse)
a |
a |
a_init |
a |
shape_prior |
a |
rate_prior |
a |
inverse |
logical. If |
For the state space model with state equation
and measurement equation
with and
the function produces a draw of the constant diagonal error variances matrix of the
state equation .
A matrix.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
k <- 10 # Number of artificial coefficients tt <- 1000 # Number of observations set.seed(1234) # Set RNG seed # Generate artificial data according to a random walk a <- matrix(rnorm(k), k, tt + 1) for (i in 2:(tt + 1)) { a[, i] <- a[, i - 1] + rnorm(k, 0, sqrt(1 / 100)) } a_init <- matrix(a[, 1]) # Define initial state a <- matrix(a[, -1]) # Drop initial state from main sample and make vector # Define priors shape_prior <- matrix(1, k) rate_prior <- matrix(.0001, k) # Obtain posterior draw post_gamma_state_variance(a, a_init, shape_prior, rate_prior, inverse = FALSE)k <- 10 # Number of artificial coefficients tt <- 1000 # Number of observations set.seed(1234) # Set RNG seed # Generate artificial data according to a random walk a <- matrix(rnorm(k), k, tt + 1) for (i in 2:(tt + 1)) { a[, i] <- a[, i - 1] + rnorm(k, 0, sqrt(1 / 100)) } a_init <- matrix(a[, 1]) # Define initial state a <- matrix(a[, -1]) # Drop initial state from main sample and make vector # Define priors shape_prior <- matrix(1, k) rate_prior <- matrix(.0001, k) # Obtain posterior draw post_gamma_state_variance(a, a_init, shape_prior, rate_prior, inverse = FALSE)
Produces a draw of coefficients from a normal posterior density.
post_normal(y, x, sigma_i, a_prior, v_i_prior)post_normal(y, x, sigma_i, a_prior, v_i_prior)
y |
a |
x |
an |
sigma_i |
the inverse of the |
a_prior |
a |
v_i_prior |
the inverse of the |
The function produces a vectorised posterior draw of the
coefficient matrix for the model
where is a K-dimensional vector of endogenous variables,
is an M-dimensional vector of explanatory variabes
and the error term is .
For a given prior mean vector and prior covariance matrix
the posterior covariance matrix is obtained by
and the posterior mean by
where is a matrix of the endogenous variables and is an matrix of
the explanatory variables.
A vector.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data, p = 2, deterministic = "const") y <- t(temp$data$train$y) x <- t(temp$data$train$x) k <- nrow(y) tt <- ncol(y) m <- k * nrow(x) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(0.1, m) # Initial value of inverse Sigma sigma_i <- solve(tcrossprod(y) / tt) # Draw parameters a <- post_normal(y = y, x = x, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior)# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data, p = 2, deterministic = "const") y <- t(temp$data$train$y) x <- t(temp$data$train$x) k <- nrow(y) tt <- ncol(y) m <- k * nrow(x) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(0.1, m) # Initial value of inverse Sigma sigma_i <- solve(tcrossprod(y) / tt) # Draw parameters a <- post_normal(y = y, x = x, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior)
Produces a draw of coefficients from a normal posterior density for a model with seemingly unrelated regresssions (SUR).
post_normal_sur(y, z, sigma_i, a_prior, v_i_prior, svd = FALSE)post_normal_sur(y, z, sigma_i, a_prior, v_i_prior, svd = FALSE)
y |
a |
z |
a |
sigma_i |
the inverse of the constant |
a_prior |
a |
v_i_prior |
the inverse of the |
svd |
logical. If |
The function produces a posterior draw of the coefficient vector for the model
where .
is a K-dimensional vector of endogenous variables and
is a matrix of regressors with
as a vector of regressors.
For a given prior mean vector and prior covariance matrix
the posterior covariance matrix is obtained by
and the posterior mean by
A vector.
# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data, p = 2, deterministic = "const") y <- t(temp$data$train$y) z <- temp$data$train$z k <- nrow(y) tt <- ncol(y) m <- ncol(z) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(0.1, m) # Initial value of inverse Sigma sigma_i <- solve(tcrossprod(y) / tt) # Draw parameters a <- post_normal_sur(y = y, z = z, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior)# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data, p = 2, deterministic = "const") y <- t(temp$data$train$y) z <- temp$data$train$z k <- nrow(y) tt <- ncol(y) m <- ncol(z) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(0.1, m) # Initial value of inverse Sigma sigma_i <- solve(tcrossprod(y) / tt) # Draw parameters a <- post_normal_sur(y = y, z = z, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior)
Forecasting a Bayesian VAR object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' predict(object, n_ahead = NULL, ...)## S3 method for class 'bvarmodel' predict(object, n_ahead = NULL, ...)
object |
an object of class 'bvarmodel'. |
n_ahead |
number of steps ahead at which to predict. If |
... |
additional arguments. |
For the VAR model
with the function produces n_ahead forecasts.
An object of class 'bvarprd', a list with element fcst, an
array of the forecast draws, whose first two
dimensions are named after the forecast periods and the endogenous variables, and
element y, the endogenous variables of the training sample.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add the data the forecasts are produced from model <- add_forecast_input(model, n_ahead = 10) # Simulate the forecasts model <- add_posterior_forecasts(model) # Collect them pred <- predict(model)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add the data the forecasts are produced from model <- add_forecast_input(model, n_ahead = 10) # Simulate the forecasts model <- add_posterior_forecasts(model) # Collect them pred <- predict(model)
Summarises the forecasts of a VEC model, in levels.
## S3 method for class 'bvecmodel' predict(object, n_ahead = NULL, ...)## S3 method for class 'bvecmodel' predict(object, n_ahead = NULL, ...)
object |
an object of class 'bvecmodel', usually, the result of a call to
|
n_ahead |
number of steps ahead at which to predict. If |
... |
additional arguments passed to |
The forecasts are of the levels, and so is the history they are shown with: it
is recovered from the differences and the error correction term the way
vec_to_var recovers it.
A time-series object of class "bvarprd", as returned by
predict.bvarmodel.
Other posterior simulation:
add_forecast_input.bvarmodel(),
add_forecast_input.bvecmodel(),
add_posterior_coefficients.bvarmodel(),
add_posterior_coefficients.bvecmodel(),
add_posterior_forecasts.bvarmodel(),
add_posterior_forecasts.bvecmodel(),
add_posterior_loglik.bvarmodel(),
add_posterior_loglik.bvecmodel(),
add_seed(),
bayests_files(),
bayests_posterior(),
bvar(),
bvec(),
chain_diagnostics()
Forecasting Bayesian VAR objects in a list of class 'expandingwindow'.
## S3 method for class 'expandingwindow' predict(object, ...)## S3 method for class 'expandingwindow' predict(object, ...)
object |
an object of class 'expandingwindow'. |
... |
additional arguments. |
A time-series object of class 'expandwindbvarprdlist'.
data("us_macrodata") model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = 2007) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) model <- add_forecast_input(model, n_ahead = 10) model <- add_posterior_forecasts(model) # Predict prd <- predict(model, n_ahead = 4)data("us_macrodata") model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Obtain objects for expanding window estimation model <- use_expanding_window(model, start = 2007) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(shape = 3, rate = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) model <- add_forecast_input(model, n_ahead = 10) model <- add_posterior_forecasts(model) # Predict prd <- predict(model, n_ahead = 4)
Forecasting Bayesian VAR objects in a list of class 'modellist'.
## S3 method for class 'modellist' predict(object, ...)## S3 method for class 'modellist' predict(object, ...)
object |
an object of class 'modellist'. |
... |
additional arguments. |
A time-series object of class 'bvarprdlist'.
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 1:2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add forecast input data model <- add_forecast_input(model, n_ahead = 10) model <- add_posterior_forecasts(model) # Generate forecasts bvar_pred <- predict(model, n_ahead = 10)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 1:2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add forecast input data model <- add_forecast_input(model, n_ahead = 10) model <- add_posterior_forecasts(model) # Generate forecasts bvar_pred <- predict(model, n_ahead = 10)
Generic function that generates data matrices serving as data input for downstream forecasting functions.
prepare_forecast_input(object, ...)prepare_forecast_input(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: prepare_forecast_input.bvarmodel,
prepare_forecast_input.bvecmodel.
Generates data matrices serving as input for forecasting simulation for objects of class 'bvarmodel'.
## S3 method for class 'bvarmodel' prepare_forecast_input( object, n_ahead = 10, deterministic = NULL, exogen = NULL, ... )## S3 method for class 'bvarmodel' prepare_forecast_input( object, n_ahead = 10, deterministic = NULL, exogen = NULL, ... )
object |
an object of class 'bvarmodel'. |
n_ahead |
number of steps ahead at which to predict. |
deterministic |
a time-series object with deterministic data. If not specified, the function will try to identify the deterministic terms automatically. If this is not successful, an error message we be returned. |
exogen |
a time-series object with the unmodelled, non-deterministic variables of the model. Required if the model has such variables. See 'Details'. |
... |
additional arguments. |
The regressors of a forecast period contain the values of the unmodelled,
non-deterministic variables in that period and in the s periods before it. Argument
exogen therefore has to cover the last s periods of the estimation sample as well
as the n_ahead forecast periods, at the frequency of the model. A series that starts with
the first forecast period, or ends before the last one, is refused with a message that names the
periods it has to cover.
If deterministic is not given, the deterministic terms are continued from the estimation
sample, which works for a constant, a linear trend, seasonal dummies and the dummy variables of
add_dummy_variables.
A list with elements h, the forecast horizon, and x,
the out-of-sample regressors: h rows, one per period, by one column
per regressor. That is the compact layout, the same one a coefficient matrix
is k by; the SUR layout this used to return spread every regressor
over k columns and was k^2 the size for no extra content.
The lags of the endogenous variables that the estimation sample does not
reach are the forecasts of earlier periods, which the forecast fills in as it
goes; they are zero here, since the samplers refuse a missing value anywhere
in x.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Generate forcast input fcst_input <- prepare_forecast_input(model, n_ahead = 4)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Generate forcast input fcst_input <- prepare_forecast_input(model, n_ahead = 4)
Prepares the regressors of the forecast periods of a VEC model, in levels.
## S3 method for class 'bvecmodel' prepare_forecast_input(object, ...)## S3 method for class 'bvecmodel' prepare_forecast_input(object, ...)
object |
an object of class 'bvecmodel'. |
... |
arguments passed to |
A VEC model is forecast in levels, so its forecast regressors are those of its
VAR representation. They are prepared from the data and specification
vec_to_var builds; the posterior draws are not converted.
A list with the forecast horizon in element h and the regressors of the
forecast periods in element x, as returned by
prepare_forecast_input.bvarmodel.
print method for objects of class 'bvarmodel'.
## S3 method for class 'bvarmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)## S3 method for class 'bvarmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)
x |
an object of class 'bvarmodel'. |
digits |
the number of significant digits to use when printing. |
... |
further arguments passed to or from other methods. |
A data frame of the model's specification, as printed, invisibly. It
is the result of get_model_specifications with the columns
renamed for display and, where the model has no unmodelled variables, the
columns m and s dropped.
Prints the connectedness table of Diebold and Yilmaz (2012).
## S3 method for class 'bvarspillover' print(x, digits = 1, ...)## S3 method for class 'bvarspillover' print(x, digits = 1, ...)
x |
an object of class 'bvarspillover', usually the result of a call to
|
digits |
the number of decimal places. Defaults to 1, which is what this literature reports. |
... |
not used. |
The body of the table is the posterior mean share of the forecast
error variance of the variable in the row that is attributed to a shock to the
variable in the column, in percent. The from column and the to
row are the directional spillovers, and the corner is the total index.
Only the means appear here. The credible intervals are in the total,
from, to and net elements of the object.
x, invisibly.
print method for objects of class 'bvecmodel'.
## S3 method for class 'bvecmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)## S3 method for class 'bvecmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)
x |
an object of class 'bvecmodel'. |
digits |
the number of significant digits to use when printing. |
... |
further arguments passed to or from other methods. |
A data frame of the model's specification, as printed, invisibly. It
is the result of get_model_specifications with the columns
renamed for display and, where the model has no unmodelled variables, the
columns m and s dropped.
print method for objects of class 'modellist'.
## S3 method for class 'modellist' print(x, digits = max(3L, getOption("digits") - 3L), ...)## S3 method for class 'modellist' print(x, digits = max(3L, getOption("digits") - 3L), ...)
x |
an object of class 'modellist'. |
digits |
the number of significant digits to use when printing. |
... |
further arguments passed to or from other methods. |
A data frame with one row per model, as printed, invisibly: the
specifications of get_model_specifications, without the
columns in which every model agrees.
Imports model information and posterior draws from an HDF5 file.
read_expanding_window_model_from_folder(folder)read_expanding_window_model_from_folder(folder)
folder |
Path to a folder with HDF5 files containing model data. |
A list of class 'expandingwindow' with one model per file in
folder, each read by read_model_from_hdf5, in the order
list.files returns the files.
Imports model information and posterior draws from an HDF5 file.
read_model_from_hdf5(filename, group = "", draws = NULL)read_model_from_hdf5(filename, group = "", draws = NULL)
filename |
Path to an HDF5 file containing model data. |
group |
the group the model's tree hangs under inside its file.
Defaults to |
draws |
the draws to read, as their positions in the chain. Defaults to
|
With a group every path the reader looks for is read under it
instead of at the root, so one file can hold several models side by side.
list_models_in_hdf5 reports which groups of a file hold one.
The spelling is the one the BayesTS command line uses for its --group
flag: a leading slash and no trailing slash, with "" for the root.
draws reads part of a chain. Every block of a posterior holds one row
per draw, and only the rows asked for are read from the file, so a caller
that works through a long chain in pieces – solving a global model draw by
draw, for instance – never holds more of it than the piece it is working
on. integer(0) reads a model without its draws, which is what a step
needs that only looks at what a model is.
A partial read cannot describe the chain it came from, so the blocks it returns are labelled as a chain of their own, from one to the number of draws read. A full read keeps the labels the file carries.
An object of class 'bvarmodel' or 'bvecmodel', depending on the
algorithm recorded in the file, with the elements that file holds:
model, data, priors, initial and, where the
model has been estimated, posterior. The draws of a sampler are
mcmc objects; the per-period posterior of a discounted
model is a plain matrix, since its rows are periods rather than draws.
bvartools_model describes the elements one by one.
A model of another package – a dynamic factor model of dfmtools,
say – is returned as the object of that package's
from_bayests_tree method, so that one 'modellist' can hold
and evaluate models of either.
Imports every model stored below a folder.
read_models_from_folder(folder, draws = NULL)read_models_from_folder(folder, draws = NULL)
folder |
Path to a folder containing model data. |
draws |
the draws to read of every model, as
|
The folder is walked recursively, and each HDF5 file in it is asked which of
its groups hold a model – so a file holding several models contributes all
of them. See list_models_in_hdf5 for what counts as one.
The result is a flat named list rather than a nesting that mirrors the
directory tree. Each name is the path of the file relative to folder
without its extension, followed by the group where a model does not sit at
the root of its file. Names are what a caller needs to tell one model from
another – which sub-model of a global model it is, say – and a nesting
whose depth depended on where the caller pointed could not provide them.
The one exception is an expanding window: the windows that
write_to_hdf5 wrote to one directory come back as one element
of class 'expandingwindow', named after that directory, so that the windows of
different specifications are not pooled. A folder that holds a single
expanding window is returned as that expanding window. A model list written
by write_to_hdf5 comes back in the order it was written in,
which the files record; other models are in the order of their names.
The class of each model comes from the rclass attribute the writer
records, not from its file name.
draws is what makes a folder larger than the session readable: with
integer(0) the models come back with their specification, their data
and their priors and no draws, and with a vector of positions the chain is
read a piece at a time. For working on the models rather than reading them,
open_models hands them over one at a time instead.
A named list of class 'modellist', or of class 'expandingwindow' if the models say they belong to one.
# Load data data("e1") train <- diff(log(e1)) * 100 # Create and store models folder <- file.path(tempdir(), "models") dir.create(folder, showWarnings = FALSE) for (p in 1:2) { model <- create_bvarmodel(data = train, p = p, deterministic = "const", iterations = 10, burnin = 10) write_to_hdf5(model, filename = file.path(folder, paste0("model-", p, ".h5"))) } models <- read_models_from_folder(folder) names(models)# Load data data("e1") train <- diff(log(e1)) * 100 # Create and store models folder <- file.path(tempdir(), "models") dir.create(folder, showWarnings = FALSE) for (p in 1:2) { model <- create_bvarmodel(data = train, p = p, deterministic = "const", iterations = 10, burnin = 10) write_to_hdf5(model, filename = file.path(folder, paste0("model-", p, ".h5"))) } models <- read_models_from_folder(folder) names(models)
Rescales the series in the error correction series.
rescale_error_correction(object, ...)rescale_error_correction(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: rescale_error_correction.bvecmodel.
Puts the series in the error correction term of an object of class 'bvecmodel', and the posterior draws that belong to them, back in terms of the input data.
## S3 method for class 'bvecmodel' rescale_error_correction(object, ...)## S3 method for class 'bvecmodel' rescale_error_correction(object, ...)
object |
object of class 'bvecmodel'. |
... |
arguments passed forward to method. |
The function transforms element object$data$train$w, the
posterior draws and the starting values back to the series of the input
data, based on the attributes "scale" and "centre" that
scale_error_correction stored in object$data$train$w,
and drops the attributes.
If is the diagonal matrix of scaling factors, function
scale_error_correction replaced by
, so that the estimated error correction term is
. The draws of are
therefore multiplied by , while the draws of are
not affected by the transformation and are carried over unchanged.
If the series were centred on their means , the estimated term is
, with the identity
matrix if they were not scaled. The draws of the unrestricted constant are
therefore shifted by , draw by draw
and, for a model with time varying parameters, period by period with the
loadings and the cointegration vectors of that period. The fitted values and
the log-likelihood of every draw are unchanged by that. The starting values
of the constant are shifted in the same way. If variable selection covered
the deterministic terms, the draws of the inclusion indicators of the
constant are carried over as they are, so they describe the constant of the
centred series.
What is unchanged is the sample. Beyond it, a model with time varying
cointegration vectors cannot be carried on from the rescaled draws: the state
equation of was estimated for the transformed series, and the
constant absorbs of the last period
only, so a step of would reintroduce the intercept the centring
removed. The function therefore sets object$model$ect_rescaled for such a
model, and add_posterior_forecasts.bvecmodel and
add_predictive_loglik.bvecmodel accept it only with
forecast_states = "hold".
An object of class 'bvecmodel'.
Scales the series in the error correction series.
scale_error_correction(object, ...)scale_error_correction(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: scale_error_correction.bvecmodel.
Scales, centres, or centres and scales the series in the error correction term of an object of class 'bvecmodel'.
## S3 method for class 'bvecmodel' scale_error_correction(object, scale = TRUE, centre = FALSE, ...)## S3 method for class 'bvecmodel' scale_error_correction(object, scale = TRUE, centre = FALSE, ...)
object |
object of class 'bvecmodel'. |
scale |
logical. If |
centre |
logical. If |
... |
arguments passed forward to method. |
The function transforms element object$data$train$w, and
rescale_error_correction undoes the transformation once the
posterior draws are in.
With scale = TRUE, stochastic series are divided by the standard
deviation of the corresponding differenced series. If the time-series object
contains a column named "trend", this series is divided by its own
standard deviation, i.e. in levels. The scaling factors are stored as a new
attribute of object$data$train$w named "scale".
With centre = TRUE, the sample mean of each stochastic series is
subtracted from it. The deterministic terms restricted to the cointegration
space, which are the last columns of the term, are left as they are. The
means are stored as attribute "centre", with zeros for the
deterministic terms. If both arguments are TRUE, the series are
centred first and scaled second, so that becomes
.
Centring requires an unrestricted constant, which takes up what the series
lose: . For a model with
constant coefficients it is therefore a reparameterisation that leaves the
likelihood and the priors on and as they are and
changes only what the prior of the constant refers to. For a model with
time varying cointegration vectors it changes more. A step of
their state equation moves by
, which for series far from zero acts as a random
walk intercept that no prior on the deterministic terms controls; see
section 'Prior on the cointegration space' of cointspace_prior.
On centred series the same step moves the term by
, and the intercept is left to the constant
and its own prior. That holds for the estimation. The forecast of such a
model, which needs rescale_error_correction first, can only hold
the cointegration vectors at their last value (forecast_states = "hold"
in add_posterior_forecasts.bvecmodel), since after rescaling a
step of them acts on the series as they are.
Starting values of the constant in object$initial are shifted by
, computed from the starting values of the loadings and of
, so that the chain starts from the model it simulates.
Neither transformation can be applied twice, and neither can be added to a
model that already carries the other: rescale_error_correction has
to be called in between.
An object of class 'bvecmodel'.
Generic function used to calculate selection criteria.
selection_criteria(object, ...) ## S3 method for class 'selcrit' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'selcritlist' print(x, digits = max(3L, getOption("digits") - 3L), relative = 0, ...)selection_criteria(object, ...) ## S3 method for class 'selcrit' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'selcritlist' print(x, digits = max(3L, getOption("digits") - 3L), relative = 0, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
x |
an object used to select a method. Usually, the result of a call to
|
digits |
the minimum number of significant digits to be printed in values. |
relative |
an integer specifying the model that is used as the reference
of relative forecast performance. Default is |
The in-sample criteria are obtained from the draws of the
log-likelihood that add_posterior_loglik adds to a model. With
the log-likelihood of period in draw of
draws, and
the number of estimated parameters, these are
"LL": the log-likelihood , which is summarised by
the mean, the median and the bounds of the credible band of its draws.
"AIC": ;
"BIC": ;
"HQ": ;
"WAIC": ;
"LOOIC": times the expected log pointwise predictive
density of leave-one-out cross validation, obtained by Pareto smoothed
importance sampling.
is the deviance of the model at its point estimate. Since AIC, BIC
and HQ correct the deviance of a fitted model for the optimism of having
fitted it, it is the deviance at the point estimate that their penalties
belong to. The mean of the deviance over the posterior is the larger
quantity, by about the effective number of parameters, so adding a penalty
to it would charge the complexity of the model a second time and tilt every
comparison towards the smaller model. is therefore the deviance at
the posterior mean of the parameters, obtained by evaluating the
log-likelihood of the model once at that point. For a VEC model the point is
the matrix of the rank of the model that is closest to the posterior mean of
in the metric of the likelihood, i.e. that
minimises , where
is its difference to the posterior mean, the posterior mean of the
error precision and the error correction term, since and
are identified only up to a rotation and their own means say
nothing. The point does not depend on the scale of the series. Under a
flat prior is close to the deviance at the maximum likelihood
estimates. Evaluated at the maximum
likelihood estimates AIC reduces to times the expression in
Luetkepohl (2006) plus terms that do not depend on the lag order, so both
order a set of lag orders in the same way.
AIC, BIC and HQ are point estimates rather than quantities with a posterior
distribution, so their credible bands are NA. WAIC and LOOIC are
point estimates as well, and their bands are normal intervals built from
their standard errors, which is the usual way they are reported.
The choice between the criteria is one of what means for the
model at hand. A count of parameters describes a model with constant
coefficients and a weak prior, which is the case AIC, BIC and HQ are derived
for and the one in which they reproduce the textbook lag order selection. It
does not describe a model whose coefficients or variances follow a state
equation, where the prior on the state variances decides how much of the
nominal freedom is used, and it does not describe a shrinkage prior, which
buys back degrees of freedom that does not see. WAIC and LOOIC
penalise by the flexibility the fit actually used and remain defined in
those cases.
LOOIC estimates the same quantity as WAIC by reweighting the posterior towards the one that has not seen a period, which is the more accurate route when it works and which says when it does not: the shape parameter of the Pareto tail fitted to the importance ratios of a period exceeds its threshold when that period is too influential to be reweighted, and the print methods report how many periods this happened for.
For a model whose coefficients or variances follow a state equation, the
pointwise log-likelihood that WAIC and LOOIC are built from is evaluated at
the states of each period, which have seen that period's observation. The
state of a period is informed mostly by its own observation, so leaving the
observation out by reweighting fails for exactly the periods a path bends
towards, and neither criterion separates models that differ in how much of
that freedom they have, such as the cointegration ranks of a time varying
VEC model. The criterion for those comparisons is "LPL", the log
predictive likelihood, whose densities condition only on the data before the
period they evaluate. Koop, León-González and Strachan (2011) choose between time
varying cointegration models with it.
Two things produce those densities and both report them as "LPL".
add_predictive_loglik takes one per window of an expanding
window exercise, carrying the states forward with their state equations, which
is the form the comparison of ranks above is made in. A single model carries
one per horizon of its forecast in posterior$forecast$loglik, written
by BayesTS against the values in data$test$y, each conditioning on the
periods realised before it. They are the same quantity computed two ways and
are summarised by the same code, so the same densities give the same number.
All criteria require that the models that are compared were estimated on the
same observations. create_bvarmodel and
create_bvecmodel ensure this for a vector of lag orders by
trimming the data by the maximum lag, and align_model_obs
restricts models that were created separately to their common sample.
The value returned by the method for the class of object,
as described on the pages of the methods.
Koop, G., León-González, R., & Strachan, R. W. (2011). Bayesian inference in a time varying cointegration model. Journal of Econometrics, 165(2), 210–220. doi:10.1016/j.jeconom.2011.07.007
Luetkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Vehtari, A., Gelman, A., & Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27(5), 1413–1432. doi:10.1007/s11222-016-9696-4
Vehtari, A., Simpson, D., Gelman, A., Yao, Y., & Gabry, J. (2024). Pareto smoothed importance sampling. Journal of Machine Learning Research, 25(72), 1–58.
Watanabe, S. (2010). Asymptotic equivalence of Bayes cross validation and widely applicable information criterion in singular learning theory. Journal of Machine Learning Research, 11, 3571–3594.
Zhang, J., & Stephens, M. A. (2009). A new and efficient estimation method for the generalized Pareto distribution. Technometrics, 51(3), 316–325. doi:10.1198/tech.2009.08017
Methods: selection_criteria.bvarmodel,
selection_criteria.bvecmodel,
selection_criteria.expandingwindow,
selection_criteria.externalforecast,
selection_criteria.modellist.
Calculates model selection criteria for an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' selection_criteria(object, ci = 0.95, plugin = c("mean", "best"), ...)## S3 method for class 'bvarmodel' selection_criteria(object, ci = 0.95, plugin = c("mean", "best"), ...)
object |
an object of class 'bvarmodel'. |
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
plugin |
the point at which the deviance of |
... |
further arguments passed to or from other methods. |
A list of class 'selcrit', which also inherits the class of the model, with the
element model and one data frame per criterion. If the model contains
posterior$loglik, these are LL, AIC, BIC, HQ,
WAIC and LOOIC, each with the columns mean, median,
qlower and qupper, where bands that do not apply are NA. If it
contains posterior$forecast$errors, these are FE, AFE and
RSFE, the forecast errors and their absolute and root squared values, with the
columns variable, h, mean, median, qlower and
qupper. For RSFE only mean is a statistic of its own, the root
of the mean squared error. Its median and quantiles are those of the squared
errors, rooted, and so differ from AFE's only by the interpolation
between neighbouring draws that quantile and
median do – which, the root of an average of squares
being at least the average of the roots, can only raise them. They add
nothing to AFE's. If it contains posterior$forecast$loglik, the score of its
forecast against data$test$y, there is LPL, the log predictive
likelihood: the log of the mean of the draws of each scored period's predictive
density, summed over the periods. Attribute "terms" holds those per period
and "nse" their numerical standard error.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvecmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 1:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add log-likelihoods model <- add_posterior_loglik(model) # Calculate selection criteria sel <- selection_criteria(model) sel# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 1:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add log-likelihoods model <- add_posterior_loglik(model) # Calculate selection criteria sel <- selection_criteria(model) sel
Calculates model selection criteria for an object of class 'bvecmodel'.
## S3 method for class 'bvecmodel' selection_criteria(object, ci = 0.95, plugin = c("mean", "best"), ...)## S3 method for class 'bvecmodel' selection_criteria(object, ci = 0.95, plugin = c("mean", "best"), ...)
object |
an object of class 'bvecmodel'. |
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
plugin |
the point at which the deviance of |
... |
further arguments passed to or from other methods. |
A list of class 'selcrit', which also inherits the class of the model, with the
element model and one data frame per criterion, as described in
selection_criteria.bvarmodel.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.default(),
selection_criteria.modellist()
# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 4, const = "unrestricted", seasonal = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add log-likelihoods model <- add_posterior_loglik(model) # Calculate selection criteria sel <- selection_criteria(model) sel# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 4, const = "unrestricted", seasonal = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add log-likelihoods model <- add_posterior_loglik(model) # Calculate selection criteria sel <- selection_criteria(model) sel
Calculates the criteria that a pointwise log-likelihood and a scored forecast are enough for, whatever the model is.
## Default S3 method: selection_criteria(object, ci = 0.95, ...)## Default S3 method: selection_criteria(object, ci = 0.95, ...)
object |
any object with |
ci |
the width of the credible bands, a value between 0 and 1. Defaults to 0.95. |
... |
additional arguments. |
The criteria of selection_criteria.bvarmodel fall into two
groups. AIC, BIC and HQ charge a model for its size, so
they need a count of its free parameters, which is a property of the model and
cannot be read off its draws. FE, AFE and RSFE need the
forecast errors, which need the variables to be named and paired up. Neither
group is available here.
What is left needs nothing but the draws themselves:
LL, the log-likelihood of the whole sample per draw, summed over
the periods of posterior$loglik;
WAIC and LOOIC, which penalise by the flexibility the fit
used rather than by a count of parameters – see selection_criteria
for why that is what makes constant, time varying and stochastic volatility
specifications comparable at all;
LPL, the log predictive likelihood of
posterior$forecast$loglik, the score of a forecast against what its
horizon realised.
The periods of the "terms" attribute of LPL are numbered from
one rather than dated: this method knows nothing of where a model keeps its
sample, so it cannot say when the scored periods were. A class that can say
should write its own method, as selection_criteria.bvarmodel
does.
A list of class 'selcrit', which also inherits the class of
object, with the element model and one data frame per criterion
that the draws supported, each with the columns mean, median,
qlower and qupper. choose_best_model ranks a list
of them and print shows them.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.modellist()
# Any object with the draws will do, whatever produced them. set.seed(7) model <- list(model = list(k = 2), posterior = list(loglik = matrix(stats::rnorm(200, -3), 50, 4), forecast = list(loglik = matrix(stats::rnorm(150, -3), 50, 3)))) criteria <- selection_criteria(model) names(criteria) criteria[["LPL"]][["mean"]]# Any object with the draws will do, whatever produced them. set.seed(7) model <- list(model = list(k = 2), posterior = list(loglik = matrix(stats::rnorm(200, -3), 50, 4), forecast = list(loglik = matrix(stats::rnorm(150, -3), 50, 3)))) criteria <- selection_criteria(model) names(criteria) criteria[["LPL"]][["mean"]]
Calculates model selection criteria for an object of class 'expandingwindow'.
## S3 method for class 'expandingwindow' selection_criteria(object, ci = 0.95, ...)## S3 method for class 'expandingwindow' selection_criteria(object, ci = 0.95, ...)
object |
an object of class 'expandingwindow'. |
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
... |
further arguments passed to or from other methods. |
The in-sample criteria are those of the last window, the one estimated on the most data, and the forecast error statistics those of all windows.
If the windows hold the draws of add_predictive_loglik,
criterion "LPL" is the log predictive likelihood: the sum over the
windows of the log of the mean of the draws of the predictive density of the
observation that the next window adds. Its band is the normal interval of
probability ci around the sum with standard error
over the periods, as for LOOIC.
Attribute "terms" holds the log predictive density of each period and
its numerical standard error, attribute "nse" the numerical standard
error of the sum.
An object of class 'selcrit'.
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig) # Calculate selection criteria sel <- selection_criteria(model) sel# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. model <- use_expanding_window(model, start = 1982.25) # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig) # Calculate selection criteria sel <- selection_criteria(model) sel
Calculates out-of-sample statistics for an object of class 'externalforecast'.
## S3 method for class 'externalforecast' selection_criteria(object, ci = 0.95, ...)## S3 method for class 'externalforecast' selection_criteria(object, ci = 0.95, ...)
object |
an object of class 'externalforecast'. |
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
... |
further arguments passed to or from other methods. |
External forecasts are not estimated, so only out-of-sample statistics are calculated. Since they are point forecasts, each publication contributes a single value to the statistics of a variable and forecast horizon.
An object of class 'selcrit'.
data("us_macrodata") # Create model model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. model <- use_expanding_window(model, start = 2007) # Artificial external forecasts fcst <- expand.grid(origin = c(2007, 2007.25), h = 1:2, variable = c("Dp", "r"), stringsAsFactors = FALSE) fcst[["period"]] <- fcst[["origin"]] + fcst[["h"]] / 4 fcst[["value"]] <- 0 ext <- create_external_forecast(fcst, model, n_ahead = 4) # Calculate forecast errors ext <- add_forecast_errors(ext, test_sample = us_macrodata) # Calculate selection criteria selection_criteria(ext)data("us_macrodata") # Create model model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. model <- use_expanding_window(model, start = 2007) # Artificial external forecasts fcst <- expand.grid(origin = c(2007, 2007.25), h = 1:2, variable = c("Dp", "r"), stringsAsFactors = FALSE) fcst[["period"]] <- fcst[["origin"]] + fcst[["h"]] / 4 fcst[["value"]] <- 0 ext <- create_external_forecast(fcst, model, n_ahead = 4) # Calculate forecast errors ext <- add_forecast_errors(ext, test_sample = us_macrodata) # Calculate selection criteria selection_criteria(ext)
Calculates model selection criteria for a list of Bayesian models.
## S3 method for class 'modellist' selection_criteria(object, ...)## S3 method for class 'modellist' selection_criteria(object, ...)
object |
an object of class 'modellist'. |
... |
further arguments passed to or from other methods. |
A list of class 'selcritlist' with one object of class 'selcrit' per model, as
described in selection_criteria.bvarmodel, which
choose_best_model compares.
Other model comparison:
add_forecast_errors.bvarmodel(),
add_forecast_errors.bvecmodel(),
add_predictive_loglik(),
add_predictive_loglik.bvarmodel(),
add_predictive_loglik.bvecmodel(),
aggregate_forecasts(),
align_model_obs.modellist(),
analysis_of_stored_models,
choose_best_model.selcritlist(),
create_external_forecast(),
folder_steps,
map_draws(),
map_models(),
open_model(),
open_models(),
plot_forecast_errors_by_period(),
pool_forecasts(),
selection_criteria.bvarmodel(),
selection_criteria.bvecmodel(),
selection_criteria.default()
# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig) # Calculate selection criteria sel <- selection_criteria(model) sel# Load data data("e1") orig <- diff(log(e1)) * 100 train <- window(orig, end = c(1982, 2)) # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Add data used for forecast calculation model <- add_forecast_input(model, n_ahead = 4) # Add forecasts model <- add_posterior_forecasts(model) # Add forecast errors model <- add_forecast_errors(model, test_sample = orig) # Calculate selection criteria sel <- selection_criteria(model) sel
A generic function used to calculate the connectedness measures of Diebold and Yilmaz (2012) from the posterior draws of a model.
spillover(object, ...)spillover(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: spillover.bvarmodel,
spillover.expandingwindow, spillover.modellist.
Produces the connectedness measures of Diebold and Yilmaz (2012) for an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' spillover( object, n_ahead = 10, type = "gir", ci = 0.95, keep_draws = FALSE, period = NULL, impact = NULL, ... )## S3 method for class 'bvarmodel' spillover( object, n_ahead = 10, type = "gir", ci = 0.95, keep_draws = FALSE, period = NULL, impact = NULL, ... )
object |
an object of class 'bvarmodel'. |
n_ahead |
the forecast horizon |
type |
type of the impulse responses the decomposition is based on.
Possible choices are generalised |
ci |
a numeric between 0 and 1 specifying the probability mass covered by the credible intervals. Defaults to 0.95. |
keep_draws |
logical specifying whether the function should return all draws of
the indices. Defaults to |
period |
integer. Index of the period, for which the measures should be generated.
Only used for TVP or SV models. Default is |
impact |
the impact matrix of a |
... |
further arguments passed to or from other methods. |
The function produces the connectedness measures of Diebold and Yilmaz (2012) for the VAR model
with .
Let be the share of the step forecast error
variance of variable that is attributed to a shock to variable
. Under type = "gir" this is the generalised decomposition of
Pesaran and Shin (1998),
where is the forecast error impulse response of period
and the variance of the shock variable. These shares
do not add up over , so each row is normalised,
Under type = "oir" the decomposition uses the Choleski factor of
, adds up by construction and depends on the ordering of the
variables, which is what the generalised version of Diebold and Yilmaz (2012)
avoids. Under type = "sign" it uses the Choleski factor rotated by
what add_sign_restrictions accepted for that draw, leaving out
the draws no rotation was found for. Under type = "custom" it uses the
matrix supplied in argument
impact in place of that factor and is otherwise the orthogonalised
case, the scaling by included: an impact matrix
carries the scale of its own shocks in its columns. The row normalisation is
applied to all three, so it will produce shares that sum to one even from an
impact matrix that does not factorise and is therefore not a
check that one does.
From the normalised table the measures are
totalthe total spillover index,
, the share of forecast
error variance across the system that comes from other variables.
fromspillovers received by each variable from all others,
.
tospillovers transmitted by each variable to all others,
summed down column .
netto less from. Positive values mark net
transmitters of shocks and negative values net receivers.
pairwisenet pairwise spillovers,
.
Every measure is computed once per posterior draw and only then summarised. That is not interchangeable with computing it from the posterior mean table: the measures are ratios, so the index of the mean is not the mean of the index. It is also what gives the index a credible interval, which the original point estimate based version does not have.
Objects of class 'bvecmodel' have to be transformed with
vec_to_var first, as for fevd.
An object of class 'bvarspillover', a list containing
total |
the total spillover index. The median and the bounds of the
credible interval, or all draws if |
to, from, net
|
the directional measures, one column per variable, in the same form. |
table |
the posterior mean of the normalised decomposition table, in
percent, with the |
pairwise |
the posterior mean of the net pairwise spillovers. |
specification |
a list recording |
Diebold, F. X., & Yilmaz, K. (2012). Better to give than to receive: Predictive directional measurement of volatility spillovers. International Journal of Forecasting, 28(1), 57–66. doi:10.1016/j.ijforecast.2011.02.006
Diebold, F. X., & Yilmaz, K. (2014). On the network topology of variance decompositions: Measuring the connectedness of financial firms. Journal of Econometrics, 182(1), 119–134. doi:10.1016/j.jeconom.2014.04.012
Pesaran, H. H., & Shin, Y. (1998). Generalized impulse response analysis in linear multivariate models. Economics Letters, 58, 17–29. doi:10.1016/S0165-1765(97)00214-0
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Obtain the connectedness measures sp <- spillover(object) sp # Net directional spillovers plot(sp)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 100, burnin = 10) # Chosen number of iterations and burnin should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws object <- add_posterior_coefficients(model) # Obtain the connectedness measures sp <- spillover(object) sp # Net directional spillovers plot(sp)
Guard method for objects of class 'bvecmodel'.
## S3 method for class 'bvecmodel' spillover(object, ...)## S3 method for class 'bvecmodel' spillover(object, ...)
object |
an object of class 'bvecmodel'. |
... |
additional arguments. |
Nothing. The method raises an error, since spillover indices of a VEC model are
obtained from its VAR representation: apply vec_to_var first and then
spillover to the resulting 'bvarmodel'.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
split_quantile_grid(),
vec_to_var.bvecmodel()
Produces the total spillover index of Diebold and Yilmaz (2012) over the windows of an object of class 'expandingwindow'.
## S3 method for class 'expandingwindow' spillover(object, ...)## S3 method for class 'expandingwindow' spillover(object, ...)
object |
an object of class 'expandingwindow' whose models carry posterior draws. |
... |
arguments passed forward to |
The index over a moving sample is the chart this literature is built
around, and use_expanding_window already produces the models it
needs. Each window contributes one value, dated at its own last observation,
so the result reads as the connectedness of the system as it was known up to
that date.
Note that the windows expand rather than roll: every one of them starts at the beginning of the sample, so later values are estimated on more data. Diebold and Yilmaz use a fixed width instead, which trades that away for a constant amount of information per point.
A time-series object of class 'bvarspilloverts' with the median of the
total index and the bounds of its credible interval, one row per window.
Windows whose estimation failed are NA.
Diebold, F. X., & Yilmaz, K. (2012). Better to give than to receive: Predictive directional measurement of volatility spillovers. International Journal of Forecasting, 28(1), 57–66. doi:10.1016/j.ijforecast.2011.02.006
# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 1, deterministic = "const", iterations = 50, burnin = 10) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Estimate over expanding windows windows <- use_expanding_window(model, start = c(1976, 1)) windows <- lapply(windows, function(w) { add_posterior_coefficients(add_initial_values(w)) }) class(windows) <- append("expandingwindow", class(windows)) # The index as the sample grows si <- spillover(windows, n_ahead = 5) plot(si)# Load data data("e1") e1 <- diff(log(e1)) * 100 e1 <- window(e1, end = c(1978, 4)) # Generate model data model <- create_bvarmodel(e1, p = 1, deterministic = "const", iterations = 50, burnin = 10) model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Estimate over expanding windows windows <- use_expanding_window(model, start = c(1976, 1)) windows <- lapply(windows, function(w) { add_posterior_coefficients(add_initial_values(w)) }) class(windows) <- append("expandingwindow", class(windows)) # The index as the sample grows si <- spillover(windows, n_ahead = 5) plot(si)
Produces the connectedness measures of Diebold and Yilmaz (2012) for every model in an object of class 'modellist'.
## S3 method for class 'modellist' spillover(object, ...)## S3 method for class 'modellist' spillover(object, ...)
object |
an object of class 'modellist'. |
... |
arguments passed forward to |
A list of objects of class 'bvarspillover'. Elements belonging to
models whose estimation failed are NULL.
Splits a structural quantile VAR, a model created with quantile_grid = TRUE in
create_bvarmodel, into one model per quantile.
split_quantile_grid(object)split_quantile_grid(object)
object |
an object of class 'bvarmodel' holding a grid of quantiles, usually the
result of a call to |
The draws of a grid are stacked level by level, and each level's draws are the chain the
single-quantile model would have drawn. The models returned hold those draws with the
specification of that model, so that everything written for a single quantile –
summary, plot,
add_posterior_loglik – reads them as such. What describes the grid as a
whole, its forecasts and its log likelihood, is not carried over. The impulse responses of
a structural grid are differences of forecasts at a fixed level with and without a
scenario; see forecast_quantile in add_posterior_forecasts.
A list of class 'modellist' with one object of class 'bvarmodel' per quantile, in increasing order.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
vec_to_var.bvecmodel()
data("us_macrodata") object <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "const", structural = TRUE, error = "ald", quantile = c(0.1, 0.5, 0.9), quantile_grid = TRUE, iterations = 20, burnin = 10) object <- add_priors(object, coef = list(v_i = 1), sigma = list(shape = 3, rate = .01)) object <- add_initial_values(object) object <- add_posterior_coefficients(object) levels <- split_quantile_grid(object) summary(levels[[3]])data("us_macrodata") object <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "const", structural = TRUE, error = "ald", quantile = c(0.1, 0.5, 0.9), quantile_grid = TRUE, iterations = 20, burnin = 10) object <- add_priors(object, coef = list(v_i = 1), sigma = list(shape = 3, rate = .01)) object <- add_initial_values(object) object <- add_posterior_coefficients(object) levels <- split_quantile_grid(object) summary(levels[[3]])
ssvs employs stochastic search variable selection as proposed by George et al. (2008)
to produce a draw of the precision matrix of the coefficients in a VAR model.
ssvs(a, tau0, tau1, prob_prior, include = NULL)ssvs(a, tau0, tau1, prob_prior, include = NULL)
a |
an M-dimensional vector of coefficient draws. |
tau0 |
an M-dimensional vector of prior standard deviations for restricted
coefficients in vector |
tau1 |
an M-dimensional vector of prior standard deviations for unrestricted
coefficients in vector |
prob_prior |
an M-dimensional vector of prior inclusion probabilites for the coefficients
in vector |
include |
an integer vector specifying the positions of coefficients in vector |
The function employs stochastic search variable selection (SSVS) as proposed
by George et al. (2008) to produce a draw of the diagonal inverse prior covariance matrix
and the corresponding vector of inclusion parameters
of the vectorised coefficient matrix for the VAR model
where is a K-dimensional vector of endogenous variables,
is a vector of explanatory variabes
and the error term is .
A named list containing two components:
v_i |
an |
lambda |
an M-dimensional vector of inclusion parameters. |
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data, p = 2, deterministic = "const") y <- t(temp$data$train$y) x <- t(temp$data$train$x) k <- nrow(y) tt <- ncol(y) m <- k * nrow(x) # Obtain SSVS priors using the semiautomatic approach priors <- ssvs_prior(temp, semiautomatic = c(0.1, 10)) tau0 <- priors$tau0 tau1 <- priors$tau1 # Prior for inclusion parameter prob_prior <- matrix(0.5, m) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(c(tau1^2), m) # Initial value of Sigma sigma_i <- solve(tcrossprod(y) / tt) # Draw parameters a <- post_normal(y = y, x = x, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior) # Run SSVS lambda <- ssvs(a = a, tau0 = tau0, tau1 = tau1, prob_prior = prob_prior)# Load data data("e1") data <- diff(log(e1)) # Generate model data temp <- create_bvarmodel(data, p = 2, deterministic = "const") y <- t(temp$data$train$y) x <- t(temp$data$train$x) k <- nrow(y) tt <- ncol(y) m <- k * nrow(x) # Obtain SSVS priors using the semiautomatic approach priors <- ssvs_prior(temp, semiautomatic = c(0.1, 10)) tau0 <- priors$tau0 tau1 <- priors$tau1 # Prior for inclusion parameter prob_prior <- matrix(0.5, m) # Priors a_mu_prior <- matrix(0, m) a_v_i_prior <- diag(c(tau1^2), m) # Initial value of Sigma sigma_i <- solve(tcrossprod(y) / tt) # Draw parameters a <- post_normal(y = y, x = x, sigma_i = sigma_i, a_prior = a_mu_prior, v_i_prior = a_v_i_prior) # Run SSVS lambda <- ssvs(a = a, tau0 = tau0, tau1 = tau1, prob_prior = prob_prior)
Calculates the priors for a Bayesian VAR model, which employs stochastic search variable selection (SSVS).
ssvs_prior(object, ...)ssvs_prior(object, ...)
object |
an object of class |
... |
arguments passed forward to method. |
A list containing the vectors of prior standard deviations for restricted and unrestricted variables, respectively.
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
Methods: ssvs_prior.bvarmodel,
ssvs_prior.bvecmodel, ssvs_prior.externalforecast.
# Prepare data data("e1") data <- diff(log(e1)) # Generate model input object <- create_bvarmodel(data) # Obtain SSVS prior prior <- ssvs_prior(object, semiautomatic = c(.1, 10))# Prepare data data("e1") data <- diff(log(e1)) # Generate model input object <- create_bvarmodel(data) # Obtain SSVS prior prior <- ssvs_prior(object, semiautomatic = c(.1, 10))
Calculates the priors for a Bayesian VAR model, which employs stochastic search variable selection (SSVS).
## S3 method for class 'bvarmodel' ssvs_prior(object, tau = c(0.05, 10), semiautomatic = NULL, ...)## S3 method for class 'bvarmodel' ssvs_prior(object, tau = c(0.05, 10), semiautomatic = NULL, ...)
object |
an object of class |
tau |
a numeric vector of two elements containing the prior standard errors of restricted
variables ( |
semiautomatic |
an optional numeric vector of two elements containing the factors by which
the standard errors associated with an unconstrained least squares estimate of the VAR model are
multiplied to obtain the prior standard errors of restricted ( |
... |
arguments passed forward to method. |
A list containing the vectors of prior standard deviations for restricted and unrestricted variables, respectively.
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
# Prepare data data("e1") train <- diff(log(e1)) # Generate model input model <- create_bvarmodel(train, p = 2, deterministic = "const", iterations = 5000, burnin = 1000) # Obtain SSVS prior prior <- ssvs_prior(model, semiautomatic = c(.1, 10))# Prepare data data("e1") train <- diff(log(e1)) # Generate model input model <- create_bvarmodel(train, p = 2, deterministic = "const", iterations = 5000, burnin = 1000) # Obtain SSVS prior prior <- ssvs_prior(model, semiautomatic = c(.1, 10))
Calculates the priors for a Bayesian VAR model, which employs stochastic search variable selection (SSVS).
## S3 method for class 'bvecmodel' ssvs_prior(object, tau = c(0.05, 10), semiautomatic = NULL, ...)## S3 method for class 'bvecmodel' ssvs_prior(object, tau = c(0.05, 10), semiautomatic = NULL, ...)
object |
an object of class |
tau |
a numeric vector of two elements containing the prior standard errors of restricted
variables ( |
semiautomatic |
an optional numeric vector of two elements containing the factors by which
the standard errors associated with an unconstrained least squares estimate of the VAR model are
multiplied to obtain the prior standard errors of restricted ( |
... |
arguments passed forward to method. |
A list containing the vectors of prior standard deviations for restricted
and unrestricted variables, respectively. The first elements, those of the
loadings, are one: the loadings are not selected over, and their prior is the one the
cointegration space prior implies, which the samplers form themselves every draw, so
these entries are placeholders that are never read.
George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. Journal of Econometrics, 142(1), 553–580. doi:10.1016/j.jeconom.2007.08.017
# Prepare data data("e6") # Generate model input object <- create_bvecmodel(e6, p = 2, r = 1) # Obtain SSVS prior prior <- ssvs_prior(object, semiautomatic = c(.1, 10))# Prepare data data("e6") # Generate model input object <- create_bvecmodel(e6, p = 2, r = 1) # Obtain SSVS prior prior <- ssvs_prior(object, semiautomatic = c(.1, 10))
Produces a draw of log-volatilities based on Kim, Shephard and Chib (1998).
stochvol_ksc_1998(y, h, sigma, h_init, constant)stochvol_ksc_1998(y, h, sigma, h_init, constant)
y |
a |
h |
a |
sigma |
a |
h_init |
a |
constant |
a |
For each column in y the function produces a posterior
draw of the log-volatility for the model
where and is assumed to evolve according to a random walk
with .
The implementation follows the algorithm of Kim, Shephard and Chib (1998) and performs the following steps:
Perform the transformation .
Obtain a sample from the seven-component normal mixture for
approximating the log- distribution.
Obtain a draw of log-volatilities.
The posterior precision of the log-volatility is tridiagonal – the random
walk contributes the two bands of and the mixture only a
diagonal – so the draw is obtained from a banded Cholesky factorisation,
which costs rather than the of a dense one.
The probabilities of the mixture components in step 2 are obtained in logs and shifted by their period-wise maximum before they are exponentiated. Weighting the component densities directly underflows to zero for all seven components once an observation lies far enough out in their tails, which leaves the probabilities of that period undefined and selects a component that does not exist.
The arguments are checked before the first draw and a violation raises an
error. sigma and constant have to be finite and positive, since
the algorithm divides by the former and takes the logarithm of a sum
containing the latter, and all three of sigma, h_init and
constant have to have one element per column of y.
The draw uses R's random number generator, so set.seed makes it
reproducible.
A matrix of log-volatility draws.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
Kim, S., Shephard, N., & Chib, S. (1998). Stochastic volatility. Likelihood inference and comparison with ARCH models. Review of Economic Studies 65(3), 361–393. doi:10.1111/1467-937X.00050
data("us_macrodata") y <- diff(us_macrodata) h_init <- log(diag(var(y))) h <- t(matrix(h_init, 3, nrow(y))) sigma_h <- rep(.05, 3) const <- rep(.0001, 3) stochvol_ksc_1998(y, h, sigma_h, h_init, const)data("us_macrodata") y <- diff(us_macrodata) h_init <- log(diag(var(y))) h <- t(matrix(h_init, 3, nrow(y))) sigma_h <- rep(.05, 3) const <- rep(.0001, 3) stochvol_ksc_1998(y, h, sigma_h, h_init, const)
Produces a draw of log-volatilities based on Omori, Chib, Shephard and Nakajima (2007).
stochvol_ocsn_2007(y, h, sigma, h_init, constant)stochvol_ocsn_2007(y, h, sigma, h_init, constant)
y |
a |
h |
a |
sigma |
a |
h_init |
a |
constant |
a |
For each column in y the function produces a posterior
draw of the log-volatility for the model
where and is assumed to evolve according to a random walk
with .
The implementation follows the algorithm of Omori, Chib, Shephard and Nakajima (2007) and performs the following steps:
Perform the transformation .
Obtain a sample from the ten-component normal mixture for
approximating the log- distribution.
Obtain a draw of log-volatilities.
The ten components approximate the log- distribution more
closely than the seven of stochvol_ksc_1998, at a proportional
cost in the first step.
The posterior precision of the log-volatility is tridiagonal – the random
walk contributes the two bands of and the mixture only a
diagonal – so the draw is obtained from a banded Cholesky factorisation,
which costs rather than the of a dense one.
The probabilities of the mixture components in step 2 are obtained in logs and shifted by their period-wise maximum before they are exponentiated. Weighting the component densities directly underflows to zero for all ten components once an observation lies far enough out in their tails, which leaves the probabilities of that period undefined and selects a component that does not exist.
The arguments are checked before the first draw and a violation raises an
error. sigma and constant have to be finite and positive, since
the algorithm divides by the former and takes the logarithm of a sum
containing the latter, and all three of sigma, h_init and
constant have to have one element per column of y.
The draw uses R's random number generator, so set.seed makes it
reproducible.
A matrix of log-volatility draws.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
Kim, S., Shephard, N., & Chib, S. (1998). Stochastic volatility. Likelihood inference and comparison with ARCH models. Review of Economic Studies 65(3), 361–393. doi:10.1111/1467-937X.00050
Omori, Y., Chib, S., Shephard, N., & Nakajima, J. (2007). Stochastic volatility with leverage. Fast and efficient likelihood inference. Journal of Econometrics 140(2), 425–449. doi:10.1016/j.jeconom.2006.07.008
data("us_macrodata") y <- diff(us_macrodata) h_init <- log(diag(var(y))) h <- t(matrix(h_init, 3, nrow(y))) sigma_h <- rep(.05, 3) const <- rep(.0001, 3) stochvol_ocsn_2007(y, h, sigma_h, h_init, const)data("us_macrodata") y <- diff(us_macrodata) h_init <- log(diag(var(y))) h <- t(matrix(h_init, 3, nrow(y))) sigma_h <- rep(.05, 3) const <- rep(.0001, 3) stochvol_ocsn_2007(y, h, sigma_h, h_init, const)
summary method for class 'bvarmodel'.
## S3 method for class 'bvarmodel' summary(object, ci = 0.95, period = NULL, ...) ## S3 method for class 'summary.bvarmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)## S3 method for class 'bvarmodel' summary(object, ci = 0.95, period = NULL, ...) ## S3 method for class 'summary.bvarmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)
object |
an object of class 'bvarmodel'. |
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
period |
integer. Index of the period, for which the summary statistics should be generated.
Only used for TVP or SV models. Default is |
... |
further arguments passed to or from other methods. |
x |
an object of class 'summary.bvarmodel', usually, a result of a call to
|
digits |
the number of significant digits to use when printing. |
summary.bvarmodel returns a list of class 'summary.bvarmodel',
which contains the following components:
coefficients |
A list of various summary statistics of the posterior draws of the VAR coefficients. |
sigma |
A list of various summary statistics of the posterior draws of the variance-covariance matrix. |
specifications |
a list containing information on the model specification. |
summary method for class 'bvecmodel'.
## S3 method for class 'bvecmodel' summary(object, ci = 0.95, period = NULL, ...) ## S3 method for class 'summary.bvecmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)## S3 method for class 'bvecmodel' summary(object, ci = 0.95, period = NULL, ...) ## S3 method for class 'summary.bvecmodel' print(x, digits = max(3L, getOption("digits") - 3L), ...)
object |
an object of class 'bvecmodel'. |
ci |
a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95. |
period |
integer. Index of the period, for which the summary statistics should be generated.
Only used for TVP or SV models. Default is |
... |
further arguments passed to or from other methods. |
x |
an object of class 'summary.bvecmodel', usually, a result of a call to
|
digits |
the number of significant digits to use when printing. |
summary.bvecmodel returns a list of class 'summary.bvecmodel',
which contains the following components:
a |
A list of various summary statistics of the posterior draws of the VEC coefficients. |
sigma |
A list of various summary statistics of the posterior draws of the variance-covariance matrix. |
model |
a list containing information on the model specification. |
summary method for class 'expandingwindow'.
## S3 method for class 'expandingwindow' summary(object, ...)## S3 method for class 'expandingwindow' summary(object, ...)
object |
an object of class 'expandingwindow'. |
... |
further arguments passed to or from other methods. |
The method passes the last element of the expanding window model list to its corresponding summary function; assuming that this object contains the model with the highest amount of available observations.
A list of class 'summary.bvarmodel' or 'summary.bvecmodel'.
summary method for class 'modellist'.
## S3 method for class 'modellist' summary(object, ...)## S3 method for class 'modellist' summary(object, ...)
object |
an object of class 'modellist'. |
... |
further arguments passed to or from other methods. |
A list of class 'summary.modellist'.
Transforms a dense matrix of dimensions into a sparse block
diagonal matrix of dimensions .
sur_const_to_tvp(z, k, tt)sur_const_to_tvp(z, k, tt)
z |
a |
k |
integer of the number of endogenous variables. |
tt |
integer of the number of observations. |
A sparse block diagonal matrix of dimensions .
# Specify the dimensions of the dense matrix k <- 2 tt <- 5 m <- 3 # Generate artificial data z <- matrix(NA, k * tt, m) for (i in 1:tt) { z[(i - 1) * k + 1:k, ] <- i } # Perform transformation sur_const_to_tvp(z, k, tt)# Specify the dimensions of the dense matrix k <- 2 tt <- 5 m <- 3 # Generate artificial data z <- matrix(NA, k * tt, m) for (i in 1:tt) { z[(i - 1) * k + 1:k, ] <- i } # Perform transformation sur_const_to_tvp(z, k, tt)
Thins the MCMC posterior draws in an object of class 'bvarmodel'.
## S3 method for class 'bvarmodel' thin(x, thin = 10, ...)## S3 method for class 'bvarmodel' thin(x, thin = 10, ...)
x |
an object of class 'bvarmodel'. |
thin |
an integer specifying the thinning interval between successive values of posterior draws. |
... |
further arguments passed to or from other methods. |
An object of class 'bvarmodel'.
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Thinning model <- thin(model, 2)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(e1, p = 2, deterministic = "const", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Thinning model <- thin(model, 2)
Thins the MCMC posterior draws in an object of class 'bvecmodel'.
## S3 method for class 'bvecmodel' thin(x, thin = 10, ...)## S3 method for class 'bvecmodel' thin(x, thin = 10, ...)
x |
an object of class 'bvecmodel'. |
thin |
an integer specifying the thinning interval between successive values of posterior draws. |
... |
further arguments passed to or from other methods. |
An object of class 'bvecmodel' with every block of draws thinned.
# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Thinning model <- thin(model, 2)# Load data data("e6") # Create model model <- create_bvecmodel(e6, p = 2, r = 1, const = "unrestricted", iterations = 20, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Thinning model <- thin(model, 2)
Thins the MCMC posterior draws of the elements in an object of class 'expandingwindow'.
## S3 method for class 'expandingwindow' thin(x, thin = 10, ...)## S3 method for class 'expandingwindow' thin(x, thin = 10, ...)
x |
an object of class 'expandingwindow'. |
thin |
an integer specifying the thinning interval between successive values of posterior draws. |
... |
further arguments passed to or from other methods. |
An object of class 'expandingwindow'.
Thins the MCMC posterior draws of the elements in an object of class 'modellist'.
## S3 method for class 'modellist' thin(x, thin = 10, ...)## S3 method for class 'modellist' thin(x, thin = 10, ...)
x |
an object of class 'modellist'. |
thin |
an integer specifying the thinning interval between successive values of posterior draws. |
... |
further arguments passed to or from other methods. |
An object of class 'modellist'.
Generic function used to compute Bayes factors for time variation in the coefficients and volatilities of a model with time varying parameters.
time_variation_test(object, ...)time_variation_test(object, ...)
object |
an object with suitable posterior draws passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: time_variation_test.bvarmodel,
time_variation_test.bvecmodel, and for a list of models, the
windows of an expanding window comparison or a folder of stored models,
time_variation_test.modellist,
time_variation_test.expandingwindow and
time_variation_test.bvarfolder.
Computes the Bayes factors of Chan (2018) for time variation in each coefficient, each covariance coefficient and, under stochastic volatility, each log-volatility of a VAR or VEC model with time varying parameters, from the draws of a single estimation of that model.
## S3 method for class 'bvarmodel' time_variation_test(object, joint = TRUE, batches = 20, ...) ## S3 method for class 'bvecmodel' time_variation_test(object, joint = TRUE, batches = 20, ...) ## S3 method for class 'modellist' time_variation_test(object, ...) ## S3 method for class 'expandingwindow' time_variation_test(object, ...)## S3 method for class 'bvarmodel' time_variation_test(object, joint = TRUE, batches = 20, ...) ## S3 method for class 'bvecmodel' time_variation_test(object, joint = TRUE, batches = 20, ...) ## S3 method for class 'modellist' time_variation_test(object, ...) ## S3 method for class 'expandingwindow' time_variation_test(object, ...)
object |
an object of class |
joint |
logical. Should the Bayes factor for the time variation of every
state of a block at once be reported as well? Default is |
batches |
integer. The number of batches the draws are split into for the numerical standard errors. Default is 20. |
... |
further arguments, which are ignored. |
Under the prior omega_v a random walk
, , is estimated in the
non-centred form of Frühwirth-Schnatter and
Wagner (2010), with a standard random walk and the prior
. The state does not move exactly when
, which is a point inside the prior, so the Bayes factor of the
model in which the state varies against the one in which it is constant is the
Savage-Dickey density ratio
The numerator is the density of the prior at zero. The denominator is
estimated by the average over the draws of the density at zero of the
conditional posterior of , which the sampler stores for every draw
in omega_log_zero (Chan 2018). A positive log Bayes factor favours
time variation. On the scale of Kass and Raftery (1995), values of the log
Bayes factor between 1 and 3 are positive evidence, between 3 and 5 strong
evidence and above 5 very strong evidence, and the same values with a
negative sign are evidence for a constant state.
The joint Bayes factor of a block compares the model in which every state of the block varies with the model in which none does. It is not a test of whether at least one state varies: every state that is constant costs the joint model about the same as one of its own Bayes factors against time variation, so a block in which one state moves and many do not can come out against time variation as a whole. Conversely, the joint Bayes factor can be far larger than the individual ones: each state may have posterior mass near zero on its own while little of the joint posterior sits where all of them are near zero at once. Chan (2018, Table 2 and footnote 8) reports log Bayes factors of about 3 for each of two volatilities of Italian inflation and of 235 for the two together.
The estimate is least precise where the Bayes factor is large, since the ordinates are then an average of small numbers (Chan 2018, section 2.3). The numerical standard error of each log Bayes factor is obtained by the delta method from batch means, and says how much of the value is owed to the length of the chain. Where it is large, more draws are needed before the value is read as more than its sign.
Each block chooses its prior separately in add_priors, and only
the blocks estimated under omega_v are reported.
For a VEC model the coefficients are the loadings, labelled by the error
correction term they load on (ect1, ect2, ...), followed by the
other coefficients. The cointegration space itself follows a state equation
with a fixed variance, which has no prior to test against and is not
reported.
A data frame of class "bvartimevar" with one row per state and,
if joint = TRUE, one per block, and the columns
block"coefficients", "covariances" or
"volatilities".
equationthe endogenous variable of the equation the state
belongs to; NA for the joint rows.
termthe regressor of a coefficient, the variable whose error
a covariance coefficient loads on, "log-volatility", or
"(joint)".
log_bfthe log Bayes factor in favour of time variation.
nseits numerical standard error.
Chan, J. C. C. (2018). Specification tests for time-varying parameter models with stochastic volatility. Econometric Reviews, 37(8), 807–823. doi:10.1080/07474938.2016.1167948
Frühwirth-Schnatter, S., & Wagner, H. (2010). Stochastic model specification search for Gaussian and partial non-Gaussian state space models. Journal of Econometrics, 154(1), 85–100. doi:10.1016/j.jeconom.2009.07.003
Kass, R. E., & Raftery, A. E. (1995). Bayes factors. Journal of the American Statistical Association, 90(430), 773–795. doi:10.1080/01621459.1995.10476572
# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(e1, p = 1, deterministic = "const", tvp = TRUE, error = "sv", iterations = 100, burnin = 50) # The non-centred prior on the coefficients and the log-volatilities model <- add_priors(model, coef = list(v_i = 1 / 10, omega_v = 0.001), sigma = list(mu = 0, v_i = 1 / 100, omega_v = 0.1, state_variance = 0.05, offset = 1e-4)) model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Bayes factors for time variation time_variation_test(model)# Load data data("e1") e1 <- diff(log(e1)) * 100 # Generate model model <- create_bvarmodel(e1, p = 1, deterministic = "const", tvp = TRUE, error = "sv", iterations = 100, burnin = 50) # The non-centred prior on the coefficients and the log-volatilities model <- add_priors(model, coef = list(v_i = 1 / 10, omega_v = 0.001), sigma = list(mu = 0, v_i = 1 / 100, omega_v = 0.1, state_variance = 0.05, offset = 1e-4)) model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Bayes factors for time variation time_variation_test(model)
Transforms the columns of a time-series object using the seven transformation codes of FRED-MD/FRED-QD.
transform_variables(x, code)transform_variables(x, code)
x |
a time-series object. |
code |
a named integer vector of transformation codes, one of
|
The seven codes, applied column by column, are
no transformation,
first difference,
second difference,
logarithm,
first difference of the logarithm,
second difference of the logarithm,
first difference of the growth rate,
Codes 4:6 need a strictly positive series.
A transformation loses as many leading observations as it reaches back –
one for codes 2 and 5, two for 3, 6 and
7, the last being the difference of a growth rate that is itself
taken over one period – rather than shortening the series: those leading
periods become NA,
so every column keeps the time index of x and can still be combined
with ts.intersect or passed to
create_bvarmodel.
A time-series object of the same shape as x: a vector series
for a vector series, and a matrix of series with the same columns otherwise.
McCracken, M. W., & Ng, S. (2016). FRED-MD: A monthly database for macroeconomic research. Journal of Business & Economic Statistics, 34(4), 574–589.
McCracken, M. W., & Ng, S. (2021). FRED-QD: A quarterly database for macroeconomic research. Federal Reserve Bank of St. Louis Review, 103(1), 1–44.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
use_expanding_window.bvarmodel(),
use_expanding_window.bvecmodel()
data("us_macrodata") code <- c(Dp = 2, u = 1, r = 2) x <- transform_variables(us_macrodata, code)data("us_macrodata") code <- c(Dp = 2, u = 1, r = 2) x <- transform_variables(us_macrodata, code)
The data set contains quarterly time series for two UK interest rates and inflation from 1957Q4 to 2009Q3. It was produced from the supplementary material to Koop, León-González and Strachan (2011).
data("uk_macrodata")data("uk_macrodata")
A named time-series object with 210 rows and 3 variables:
short term rate: Treasury bills. This should be series 'FITB_PA' of the IMF's International Financial Statistics database.
long term rate: Government bonds. This should be series 'FIGB_PA' of the IMF's International Financial Statistics database.
inflation: Quarterly change in the log CPI annualized by multiplying the change by 400.
Koop, G., León-González, R., & Strachan R. W. (2011). Bayesian inference in a time varying cointegration model. Journal of Econometrics, 165(2), 210–220. doi:10.1016/j.jeconom.2011.07.007
The data set contains quarterly time series for the US CPI inflation rate, unemployment rate, and Fed Funds rate from 1959Q2 to 2007Q4. It was produced from file "US_macrodata.csv" of the data sets associated with Chan, Koop, Poirier and Tobias (2019). Raw data are available at https://web.ics.purdue.edu/~jltobias/second_edition/Chapter20/code_for_exercise_1/US_macrodata.csv.
data("us_macrodata")data("us_macrodata")
A named time-series object with 195 rows and 3 variables:
CPI inflation rate.
unemployment rate.
Fed Funds rate.
Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.
Creates objects for expanding window posterior simulation.
use_expanding_window(object, ...)use_expanding_window(object, ...)
object |
an object containing model specifications and input data.
Usually, the output of a call to |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: use_expanding_window.bvarmodel,
use_expanding_window.bvecmodel,
use_expanding_window.modellist.
Creates objects for expanding window posterior simulation.
## S3 method for class 'bvarmodel' use_expanding_window(object, start, ...)## S3 method for class 'bvarmodel' use_expanding_window(object, start, ...)
object |
an object of class 'bvarmodel' containing model specifications
and input data. Usually, the output of a call to |
start |
the start period of the prediction of the first iteration of the expanding window approach. |
... |
arguments passed forward to method. |
A list of class 'expandingwindow' with one object of class 'bvarmodel' per
window. The training sample of the first ends in the period before start, and
each further window adds one period. Posterior draws, starting values and forecast input
that object already carries belong to the whole sample and are not copied into
the windows; a warning says so.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvecmodel()
data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # Create model model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", seasonal = FALSE, tvp = FALSE, error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Create multiple model objects for expanding window model <- use_expanding_window(model, start = start_period)data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # Create model model <- create_bvarmodel(data = us_macrodata, p = 1, deterministic = "none", seasonal = FALSE, tvp = FALSE, error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Create multiple model objects for expanding window model <- use_expanding_window(model, start = start_period)
Creates objects for expanding window posterior simulation.
## S3 method for class 'bvecmodel' use_expanding_window(object, start, ...)## S3 method for class 'bvecmodel' use_expanding_window(object, start, ...)
object |
an object of class 'bvecmodel' containing model specifications
and input data. Usually, the output of a call to |
start |
the start period of the prediction of the first iteration of the expanding window approach. |
... |
arguments passed forward to method. |
A list of class 'expandingwindow' with one object of class 'bvecmodel' per
window. The training sample of the first ends in the period before start, and
each further window adds one period. Posterior draws, starting values and forecast input
that object already carries belong to the whole sample and are not copied into
the windows; a warning says so.
Other model set-up:
add_dummy_variables.bvarmodel(),
add_initial_values.bvarmodel(),
add_initial_values.bvecmodel(),
add_prior_options(),
add_priors.bvarmodel(),
add_priors.bvecmodel(),
aggregation_weights(),
combine_models(),
create_bvarmodel(),
create_bvecmodel(),
transform_variables(),
use_expanding_window.bvarmodel()
# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Create multiple model objects for expanding window model <- use_expanding_window(model, start = 1998)# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Create multiple model objects for expanding window model <- use_expanding_window(model, start = 1998)
Creates objects for expanding window posterior simulation.
## S3 method for class 'modellist' use_expanding_window(object, start, ...)## S3 method for class 'modellist' use_expanding_window(object, start, ...)
object |
a list of objects containing model specifications and input data.
Usually, the output of a call to a model creation function such as
|
start |
the start period of the prediction of the first iteration of the expanding window approach. |
... |
arguments passed forward to method. |
A list of class 'modellist', which consists of objects of class 'expandingwindow'.
data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # Create model model <- create_bvarmodel(data = us_macrodata, p = 1:4, deterministic = "none", seasonal = FALSE, tvp = FALSE, error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Create multiple model objects for expanding window model <- use_expanding_window(model, start = start_period)data("us_macrodata") # Starting period of the forecasting exercise start_period <- 2007 # Create model model <- create_bvarmodel(data = us_macrodata, p = 1:4, deterministic = "none", seasonal = FALSE, tvp = FALSE, error = "gamma", iterations = 10, burnin = 2) # Chosen number of iterations and burn-in draws should be much higher. # Create multiple model objects for expanding window model <- use_expanding_window(model, start = start_period)
A generic function used to transform a vector error correction model into its VAR form. The function invokes particular methods which depend on the class of the first argument.
vec_to_var(object, ...)vec_to_var(object, ...)
object |
an object with suitable input data passed forward to method. |
... |
arguments passed forward to method. |
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: vec_to_var.bvecmodel,
vec_to_var.modellist.
An object of class 'bvecmodel' is transformed into an object of class
'bvarmodel', which contains the VAR representation of the model in
levels.
## S3 method for class 'bvecmodel' vec_to_var(object, ...)## S3 method for class 'bvecmodel' vec_to_var(object, ...)
object |
an object of class |
... |
arguments passed forward to method. |
A VEC model and its VAR representation in levels are the same model in two parameterisations, so a posterior draw of the one is a posterior draw of the other. The transformation is therefore a change of basis, which is applied draw by draw:
for the endogenous variables and, analogously, one block later for the unmodelled, non-deterministic variables
is the identity matrix unless the model is structural, in which
case it is the matrix of contemporaneous coefficients. It enters
because it multiplies in the VEC model and therefore
in its VAR representation, which leaves on the
right-hand side. The contemporaneous coefficients themselves are not
affected by the transformation and are carried over unchanged.
Deterministic terms that entered the model unrestricted carry over unchanged.
Those restricted to the cointegration space become ordinary regressors of the
VAR, entering after the unrestricted ones, and are dropped when the
cointegration rank is zero, in which case they had no effect on the model.
The coefficient transformation itself is performed by the C++ implementation
of the package's model library, which is also used to obtain forecasts of VEC
models.
The data matrices are reconstructed from the data of the VEC model, so the
resulting object covers exactly the same periods. Since a VEC model of lag
order and its VAR representation use the same number of observations,
no observations are gained or lost. The levels of the endogenous variables
are recovered from their differences and their first lag in the error
correction term, which requires both to be on the same scale. If the error
correction term was scaled or centred with
scale_error_correction, the function therefore expects
rescale_error_correction to have been applied before the
transformation.
Note that the covariance matrix of the error term is not affected by the transformation, since both parameterisations describe the same error term.
Note also that the elements priors and initial of the input
object are not carried over, because they describe the coefficients of the
VEC model. Use add_priors and add_initial_values
if the resulting model should be estimated in its VAR form. The same applies
to the results of variable selection algorithms: a coefficient of the VAR
representation is the sum of multiple coefficients of the VEC model, so no
single inclusion indicator describes it and the draws of those indicators are
dropped.
A model with time varying parameters is a sequence of VEC models, one per
period, and so is its VAR representation: the transformation is applied to
the draws of each period in turn, which yields a VAR model with time varying
parameters whose coefficient draws are the paths of the coefficients in
levels. Its forecasts start from the coefficients of the last period of the
sample, and its impulse responses and variance decompositions are those of
the period given in their argument period. The draws of the variances
of the state equations of the VEC coefficients and of are dropped,
since they describe how the coefficients of the VEC model drift and have no
counterpart among the coefficients in levels. For the same reason its
forecasts hold the coefficients and volatilities at the last period rather than
simulating them forward: model$forecast_states is set to "hold".
A model with constant coefficients and stochastic volatility has a VAR
representation with the same covariance block and the same log-volatility
random walk, so its forecasts simulate the volatility forward like those of any
other VAR model with stochastic volatility; see
add_posterior_forecasts.bvarmodel. A model of that kind estimated
with an earlier version of the package lacks posterior$u_sigma_inv$sigma,
the variance of the log-volatility innovations, and its VAR representation
holds the volatility instead.
An object of class 'bvarmodel' with the elements model and
data of the VAR in levels and, if object was estimated, element
posterior with the transformed draws, including loglik if it was
present. Priors and initial values are not carried over.
Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.
Other post-estimation analysis:
add_sign_restrictions.bvarmodel(),
add_sign_zero_restrictions.bvarmodel(),
fevd.bvarmodel(),
fevd.bvecmodel(),
historical_decomposition(),
historical_decomposition.bvarmodel(),
irf.bvarmodel(),
irf.bvecmodel(),
multipliers(),
multipliers.bvarmodel(),
multipliers.bvecmodel(),
predict.bvarmodel(),
spillover.bvarmodel(),
spillover.bvecmodel(),
split_quantile_grid()
# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 2, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Transform to a VAR model in levels object <- vec_to_var(model) # The result can be used like any other VAR model, e.g. for forecasting object <- add_forecast_input(object, n_ahead = 4) object <- add_posterior_forecasts(object)# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 2, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add prior specifications model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Obtain posterior draws model <- add_posterior_coefficients(model) # Transform to a VAR model in levels object <- vec_to_var(model) # The result can be used like any other VAR model, e.g. for forecasting object <- add_forecast_input(object, n_ahead = 4) object <- add_posterior_forecasts(object)
The models of the estimation windows of an object of class
'expandingwindow' are transformed into their VAR representation in
levels, which is the form in which forecasts, forecast errors and
out-of-sample selection criteria are obtained for VEC models.
## S3 method for class 'expandingwindow' vec_to_var(object, ...)## S3 method for class 'expandingwindow' vec_to_var(object, ...)
object |
an object of class |
... |
arguments passed forward to method. |
An object of class 'expandingwindow'.
The elements of an object of class 'modellist' are transformed into
their VAR representation in levels.
## S3 method for class 'modellist' vec_to_var(object, ...)## S3 method for class 'modellist' vec_to_var(object, ...)
object |
an object of class |
... |
arguments passed forward to method. |
An object of class 'modellist'.
Restricts the observations in the training sample of a model of class 'bvarmodel' to the specified time window.
## S3 method for class 'bvarmodel' window(x, start = NULL, end = NULL, ...)## S3 method for class 'bvarmodel' window(x, start = NULL, end = NULL, ...)
x |
an object of class 'bvarmodel'. |
start |
the start time of the period of interest. |
end |
the end time of the period of interest. |
... |
further arguments passed to or from other methods. |
Posterior draws that form a path over the periods of the training sample are cut to the periods that remain, so that they still refer to the same observations as the data. These are the coefficients of a model with time varying parameters, the draws of the error term that vary by period – as under stochastic volatility – and the pointwise log-likelihood. Draws that do not vary by period are left as they are. The posterior of a discounted model, which holds the moments of every period rather than draws, is cut to the same periods. In either case the draws or moments that remain were estimated from the whole sample; re-estimate the model to condition on the window alone.
An object of class 'bvarmodel'.
Restricts the observations in the training sample of a model of class 'bvecmodel' to the specified time window.
## S3 method for class 'bvecmodel' window(x, start = NULL, end = NULL, ...)## S3 method for class 'bvecmodel' window(x, start = NULL, end = NULL, ...)
x |
an object of class 'bvecmodel'. |
start |
the start time of the period of interest. |
end |
the end time of the period of interest. |
... |
further arguments passed to or from other methods. |
Posterior draws that form a path over the periods of the training
sample are cut to the periods that remain, so that they still refer to the
same observations as the data. These are the coefficients and cointegration
vectors of a model with time varying parameters, the draws of the error term
that vary by period – as under stochastic volatility – and the pointwise
log-likelihood. Draws that do not vary by period, such as those of
, are left as they are.
An object of class 'bvecmodel'.
Forwards model input to the same function for individual models.
## S3 method for class 'modellist' window(x, start = NULL, end = NULL, ...)## S3 method for class 'modellist' window(x, start = NULL, end = NULL, ...)
x |
an object of class 'modellist'. |
start |
the start time of the period of interest. |
end |
the end time of the period of interest. |
... |
further arguments passed to or from other methods. |
An object of class 'modellist'.
Writes a nested list into an HDF5 file as a model's tree, or reads such a
tree back as a nested list. These are the steps beneath
write_to_hdf5 and read_model_from_hdf5, exported
for packages that keep models of their own in BayesTS files – the dynamic
factor models of dfmtools, for instance.
write_bayests_tree(tree, filename, group = "") read_bayests_tree(filename, group = "", draws = NULL)write_bayests_tree(tree, filename, group = "") read_bayests_tree(filename, group = "", draws = NULL)
tree |
a named list. An element that is itself a list is a group; any other element is a dataset. See 'Details'. |
filename |
path to the HDF5 file. |
group |
the group the tree hangs under inside its file. Defaults to
|
draws |
the draws to read from the blocks of |
A model package translates its object into the layout BayesTS reads –
/model, /data, /priors, /initial and
/posterior, named and shaped as the sampler expects – and hands the
result to write_bayests_tree(). What is left to this function is what
every model shares: refusing to overwrite a model, undoing a write that fails
half-way, and the attributes that let a value be read back as what it was.
It does not check the tree against any sampler; a file that
BayesTS refuses is the translation's mistake, and bayests check is
the way to find it.
The tree is mapped onto the file as follows:
An element that is a list becomes a group of the same name, and
its elements go below it. NULL elements are left out.
The element .attributes of a list is not a group but the
attributes of the group it is in: a named list of values, each written
as an attribute. This is where /model keeps the specification –
algorithm, k, p and the rest – and where
rclass, the class read_model_from_hdf5 returns,
belongs, and rpackage, the package that defines that class,
whose namespace the reader loads for its methods.
Any other element becomes a dataset. HDF5 stores dimensions in the
reverse of R's order, so a matrix of tt rows and k columns
is a (k, tt) dataset, which is what BayesTS calls (tt, k)
"on paper". A vector is a one-dimensional dataset and is marked so that
it is read back as a vector. A time series carries its column names and
tsp, and draws of class mcmc their start, end
and thinning interval, so that both are read back as what they were.
Without a group the tree is the whole file, so an existing file is
refused; with one, only that group has to be free, which is how a second
model is added beside the first. A write that cannot be completed raises the
error and undoes what the call created.
read_bayests_tree() is the inverse, for any model file, including one
written by the BayesTS command line: groups become lists, the attributes of
each group its element .attributes, and datasets values, restored
through the attributes above where the file carries them and as matrices
where it does not.
A file whose /model carries rclass is read by
read_model_from_hdf5 through from_bayests_tree,
which is the method a model package provides to turn the tree back into its
object.
write_bayests_tree() returns the path to the written file,
invisibly. read_bayests_tree() returns the tree as a nested list.
from_bayests_tree, write_to_hdf5,
read_model_from_hdf5.
path <- tempfile(fileext = ".h5") tree <- list( "model" = list(".attributes" = list("algorithm" = "Example", "k" = 2L)), "data" = list("train" = list("y" = matrix(rnorm(20), 10, 2))) ) write_bayests_tree(tree, filename = path) str(read_bayests_tree(path))path <- tempfile(fileext = ".h5") tree <- list( "model" = list(".attributes" = list("algorithm" = "Example", "k" = 2L)), "data" = list("train" = list("y" = matrix(rnorm(20), 10, 2))) ) write_bayests_tree(tree, filename = path) str(read_bayests_tree(path))
A generic function used to export the content of models into HDF5 files. The function invokes particular methods which depend on the class of the first argument.
write_to_hdf5(object, ...)write_to_hdf5(object, ...)
object |
an object of a class, for which a method should be called. |
... |
arguments passed forward to method. |
Before the method is called, the size of object is compared
with options(bvartools.size_warning), and a warning is given if it is
larger, since that is about the disk space the files will need. See
expected_model_size.
The value returned by the method for the class of object,
as described on the pages of the methods.
Methods: write_to_hdf5.bvarmodel,
write_to_hdf5.bvecmodel,
write_to_hdf5.expandingwindow,
write_to_hdf5.modellist.
Exports the content of an object of class 'bvarmodel' to an HDF5 file.
## S3 method for class 'bvarmodel' write_to_hdf5(object, filename, group = "", ...)## S3 method for class 'bvarmodel' write_to_hdf5(object, filename, group = "", ...)
object |
list of class 'bvarmodel'. |
filename |
path to the file, in which output should be stored. |
group |
the group the model's tree should hang under inside its file.
Defaults to |
... |
further arguments passed to or from other methods. |
With a group every path is written under it instead of at the root,
so one file can hold several models side by side. The spelling is the one the
BayesTS command line uses for its --group flag: a leading slash and no
trailing slash, with "" for the root. Intermediate groups are created
as needed, and list_models_in_hdf5 reports which groups of a
file hold a model.
What must not already be there is the model rather than the file. Without a
group the model is the whole file, so an existing file is refused;
with one, only that group has to be free, which is what lets a second model
be added beside the first.
A write that cannot be completed raises the error rather than absorbing it, and undoes what the call created: a file it made is removed, a group it added to an existing file is unlinked on its own so the models beside it survive. A retry then meets the original problem rather than the leftovers.
The path to the written file, invisibly.
# Load data data("e1") train <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(data = train, p = 1, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_model <- tempfile(fileext = ".h5") write_to_hdf5(model, filename = path_to_model)# Load data data("e1") train <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(data = train, p = 1, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_model <- tempfile(fileext = ".h5") write_to_hdf5(model, filename = path_to_model)
Exports the content of an object of class 'bvarmodel' to an HDF5 file.
## S3 method for class 'bvecmodel' write_to_hdf5(object, filename, group = "", ...)## S3 method for class 'bvecmodel' write_to_hdf5(object, filename, group = "", ...)
object |
list of class 'bvarmodel'. |
filename |
path to the file, in which output should be stored. |
group |
the group the model's tree should hang under inside its file.
Defaults to |
... |
further arguments passed to or from other methods. |
With a group every path is written under it instead of at the root,
so one file can hold several models side by side. The spelling is the one the
BayesTS command line uses for its --group flag: a leading slash and no
trailing slash, with "" for the root. Intermediate groups are created
as needed, and list_models_in_hdf5 reports which groups of a
file hold a model.
What must not already be there is the model rather than the file. Without a
group the model is the whole file, so an existing file is refused;
with one, only that group has to be free, which is what lets a second model
be added beside the first.
A write that cannot be completed raises the error rather than absorbing it, and undoes what the call created: a file it made is removed, a group it added to an existing file is unlinked on its own so the models beside it survive. A retry then meets the original problem rather than the leftovers.
The path to the written file, invisibly.
# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_model <- tempfile(fileext = ".h5") write_to_hdf5(model, filename = path_to_model)# Load data data("e6") e6 <- e6 * 100 # Generate model model <- create_bvecmodel(e6, p = 1, r = 1, const = "restricted", iterations = 10, burnin = 10) # Chosen number of iterations and burn-in should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1, v_i_det = 1 / 10), coint = list(v_i = 0, p_tau_i = 1), sigma = list(df = "k", scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_model <- tempfile(fileext = ".h5") write_to_hdf5(model, filename = path_to_model)
Exports the content of an object of class 'expandingwindow' to multiple HDF5 file.
## S3 method for class 'expandingwindow' write_to_hdf5(object, folder, ...)## S3 method for class 'expandingwindow' write_to_hdf5(object, folder, ...)
object |
an object of class 'expandingwindow'. |
folder |
path to the folder where the individual models in argument
|
... |
further arguments passed to or from other methods. |
The paths of the written files, invisibly, one per window, in the
subfolder of folder created for the exercise.
# Load data data("e1") train <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Use expanding window model <- use_expanding_window(model, start = 1982.5) # Add priors model <- add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_target_directory <- tempdir() write_to_hdf5(model, folder = path_to_target_directory)# Load data data("e1") train <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(data = train, p = 0:2, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Use expanding window model <- use_expanding_window(model, start = 1982.5) # Add priors model <- add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_target_directory <- tempdir() write_to_hdf5(model, folder = path_to_target_directory)
Exports the content of an object of class 'modellist' to multiple HDF5 file.
## S3 method for class 'modellist' write_to_hdf5(object, folder, ...)## S3 method for class 'modellist' write_to_hdf5(object, folder, ...)
object |
an object of class 'modellist'. |
folder |
path to the folder where the individual models in argument
|
... |
further arguments passed to or from other methods. |
The paths of the written files, invisibly, one per model and, for a member that is itself a collection, one per model in it.
# Load data data("e1") train <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(data = train, p = 0:4, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_target_directory <- tempdir() write_to_hdf5(model, folder = path_to_target_directory)# Load data data("e1") train <- diff(log(e1)) * 100 # Create model model <- create_bvarmodel(data = train, p = 0:4, deterministic = "const", iterations = 10, burnin = 10) # Number of iterations and burnin should be much higher. # Add priors model <- add_priors(model, coef = list(v_i = 1), sigma = list(df = 3, scale = 1)) # Add initial values model <- add_initial_values(model) # Save model path_to_target_directory <- tempdir() write_to_hdf5(model, folder = path_to_target_directory)