Package 'bvartools'

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] (0009-0003-8890-7781)
Maintainer: Franz X. Mohr <[email protected]>
License: GPL (>= 2)
Version: 0.2.4
Built: 2024-11-04 06:53:22 UTC
Source: CRAN

Help Index


Add Priors to Bayesian Models A generic function used to generate prior specifications for a list of models. The function invokes particular methods which depend on the class of the first argument.

Description

Add Priors to Bayesian Models

A generic function used to generate prior specifications for a list of models. The function invokes particular methods which depend on the class of the first argument.

Usage

add_priors(object, ...)

Arguments

object

an object of class "bvarmodel" or "bvecmodel".

...

arguments passed forward to method.

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Obtain data matrices
model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burn-in draws should be much higher.

# Add prior specifications
model <- add_priors(model)

Add Priors for a Vector Autoregressive Models

Description

Adds prior specifications to a list of models, which was produced by function gen_var.

Usage

## S3 method for class 'bvarmodel'
add_priors(
  object,
  coef = list(v_i = 1, v_i_det = 0.1, shape = 3, rate = 1e-04, rate_det = 0.01),
  sigma = list(df = "k", scale = 1, mu = 0, v_i = 0.01, sigma_h = 0.05, constant = 1e-04),
  ssvs = NULL,
  bvs = NULL,
  ...
)

Arguments

object

a list, usually, the output of a call to gen_var.

coef

a named list of prior specifications for the coefficients of the models. For the default specification all prior means are set to zero and the diagonal elements of the inverse prior variance-covariance matrix are set to 1 for coefficients corresponding to non-deterministic and structural terms. For deterministic coefficients the prior variances are set to 10 via v_i_det = 0.1. The variances need to be specified as precisions, i.e. as inverses of the variances. For further specifications such as the Minnesota prior see 'Details'.

sigma

a named list of prior specifications for the error variance-covariance matrix of the models. For the default specification of an inverse Wishart distribution the prior degrees of freedom are set to the number of endogenous variables and the prior variances to 1. See 'Details'.

ssvs

optional; a named list of prior specifications for the SSVS algorithm. Not allowed for TVP models. See 'Details'.

bvs

optional; a named list of prior specifications for the BVS algorithm. See 'Details'.

...

further arguments passed to or from other methods.

Details

The arguments of the function require named lists. Possible specifications are described in the following. Note that it is important to specify the priors in the correct list. Otherwise, the provided specification will be disregarded and default values will be used.

Argument coef can contain the following elements

v_i

a numeric specifying the prior precision of the coefficients. Default is 1.

v_i_det

a numeric specifying the prior precision of coefficients corresponding to deterministic terms. Default is 0.1.

coint_var

a logical specifying whether the prior mean of the first own lag of an endogenous variable should be set to 1. Default is FALSE.

const

a 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 const = "mean", the mean of the respective endogenous variable is used as prior mean. If const = "first", the first values of the respective endogenous variable is used as prior mean.

minnesota

a list of length 4 containing parameters for the calculation of the Minnesota prior, where the element names must be kappa0, kappa1, kappa2 and kappa3. For the endogenous variable ii the prior variance of the llth lag of regressor jj is obtained as

κ0l2 for own lags of endogenous variables,\frac{\kappa_{0}}{l^2} \textrm{ for own lags of endogenous variables,}

κ0κ1l2σi2σj2 for endogenous variables other than own lags,\frac{\kappa_{0} \kappa_{1}}{l^2} \frac{\sigma_{i}^2}{\sigma_{j}^2} \textrm{ for endogenous variables other than own lags,}

κ0κ2(l+1)2σi2σj2 for exogenous variables,\frac{\kappa_{0} \kappa_{2}}{(l+1)^2} \frac{\sigma_{i}^2}{\sigma_{j}^2} \textrm{ for exogenous variables,}

κ0κ3σi2 for deterministic terms,\kappa_{0} \kappa_{3} \sigma_{i}^2 \textrm{ for deterministic terms,}

where σi\sigma_{i} is the residual standard deviation of variable ii of an unrestricted LS estimate. For exogenous variables σi\sigma_{i} is the sample standard deviation.

max_var

a numeric specifying the maximum prior variance that is allowed for non-deterministic coefficients.

shape

a numeric specifying the prior shape parameter of the error term of the state equation. Only used for models with time varying parameters. Default is 3.

rate

a numeric specifying the prior rate parameter of the error term of the state equation. Only used for models with time varying parameters. Default is 0.0001.

rate_det

a numeric specifying the prior rate parameter of the error term of the state equation for coefficients, which correspond to deterministic terms. Only used for models with time varying parameters. Default is 0.01.

If minnesota is specified, v_i and v_i_det are ignored.

Argument sigma can contain the following elements:

df

an integer or character specifying the prior degrees of freedom of the error term. Only used, if the prior is inverse Wishart. Default is "k", which indicates the amount of endogenous variables in the respective model. "k + 3" can be used to set the prior to the amount of endogenous variables plus 3. If an integer is provided, the degrees of freedom are set to this value in all models.

scale

a numeric specifying the prior error variance of endogenous variables. Default is 1.

shape

a numeric or character specifying the prior shape parameter of the error term. Only used, if the prior is inverse gamma or if time varying volatilities are estimated. For models with constant volatility the default is "k", which indicates the amount of endogenous variables in the respective country model. "k + 3" can be used to set the prior to the amount of endogenous variables plus 3. If a numeric is provided, the shape parameters are set to this value in all models. For models with stochastic volatility this prior refers to the error variance of the state equation.

rate

a numeric specifying the prior rate parameter of the error term. Only used, if the prior is inverse gamma or if time varying volatilities are estimated. For models with stochastic volatility this prior refers to the error variance of the state equation.

mu

numeric of the prior mean of the initial state of the log-volatilities. Only used for models with time varying volatility.

v_i

numeric of the prior precision of the initial state of the log-volatilities. Only used for models with time varying volatility.

sigma_h

numeric of the initial draw for the variance of the log-volatilities. Only used for models with time varying volatility.

constant

numeric of the constant, which is added before taking the log of the squared errors. Only used for models with time varying volatility.

covar

logical indicating whether error covariances should be estimated. Only used in combination with an inverse gamma prior or stochastic volatility, for which shape and rate must be specified.

df and scale must be specified for an inverse Wishart prior. shape and rate are required for an inverse gamma prior. For structural models or models with stochastic volatility only a gamma prior specification is allowed.

Argument ssvs can contain the following elements:

inprior

a numeric between 0 and 1 specifying the prior probability of a variable to be included in the model.

tau

a numeric vector of two elements containing the prior standard errors of restricted variables (τ0\tau_0) as its first element and unrestricted variables (τ1\tau_1) as its second.

semiautomatic

an 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 (τ0\tau_0) and unrestricted (τ1\tau_1) variables, respectively. This is the semiautomatic approach described in George et al. (2008).

covar

logical indicating if SSVS should also be applied to the error covariance matrix as in George et al. (2008).

exclude_det

logical indicating if deterministic terms should be excluded from the SSVS algorithm.

minnesota

a numeric vector of length 4 containing parameters for the calculation of the Minnesota-like inclusion priors. See below.

Either tau or semiautomatic must be specified.

The argument bvs can contain the following elements

inprior

a numeric between 0 and 1 specifying the prior probability of a variable to be included in the model.

covar

logical indicating if BVS should also be applied to the error covariance matrix.

exclude_det

logical indicating if deterministic terms should be excluded from the BVS algorithm.

minnesota

a numeric vector of length 4 containing parameters for the calculation of the Minnesota-like inclusion priors. See below.

If either ssvs$minnesota or bvs$minnesota is specified, prior inclusion probabilities are calculated in a Minnesota-like fashion as

κ1l\frac{\kappa_1}{l} for own lags of endogenous variables,
κ2l\frac{\kappa_2}{l} for other endogenous variables,
κ31+l\frac{\kappa_3}{1 + l} for exogenous variables,
κ4\kappa_{4} for deterministic variables,

for lag ll with κ1\kappa_1, κ2\kappa_2, κ3\kappa_3, κ4\kappa_4 as the first, second, third and forth element in ssvs$minnesota or bvs$minnesota, respectively.

Value

A list of country models.

References

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

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.

Examples

data("e1")
e1 <- diff(log(e1)) * 100

model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)

model <- add_priors(model)

Add Priors for Vector Error Correction Models

Description

Adds prior specifications to a list of models, which was produced by function gen_vec.

Usage

## S3 method for class 'bvecmodel'
add_priors(
  object,
  coef = list(v_i = 1, v_i_det = 0.1, shape = 3, rate = 1e-04, rate_det = 0.01),
  coint = list(v_i = 0, p_tau_i = 1, shape = 3, rate = 1e-04, rho = 0.999),
  sigma = list(df = "k", scale = 1, mu = 0, v_i = 0.01, sigma_h = 0.05, constant = 1e-04),
  ssvs = NULL,
  bvs = NULL,
  ...
)

Arguments

object

a list, usually, the output of a call to gen_vec.

coef

a named list of prior specifications for coefficients that do not determine the cointegration space. For the default specification all prior means are set to zero and the diagonal elements of the inverse prior variance-covariance matrix are set to 1 for coefficients corresponding to non-deterministic terms. For deterministic coefficients the prior variances are set to 10 by v_i_det = 0.1. The variances need to be specified as precisions, i.e. as inverses of the variances. For further specifications such as the Minnesota prior see 'Details'.

coint

a named list of prior specifications for coefficients determining the cointegration space of VEC models. See 'Details'.

sigma

a named list of prior specifications for the error variance-covariance matrix of the models. For the default specification of an inverse Wishart distribution the prior degrees of freedom are set to the number of endogenous variables plus the rank of the cointegration matrix. The prior variance is to 1. See 'Details'.

ssvs

optional; a named list of prior specifications for the SSVS algorithm. Not allowed for TVP models. See 'Details'.

bvs

optional; a named list of prior specifications for the BVS algorithm. See 'Details'.

...

further arguments passed to or from other methods.

Details

The arguments of the function require named lists. Possible specifications are described in the following. Note that it is important to specify the priors in the correct list. Otherwise, the provided specification will be disregarded and default values will be used.

Argument coef contains the following elements

v_i

a numeric specifying the prior precision of the coefficients. Default is 1.

v_i_det

a numeric specifying the prior precision of coefficients that correspond to deterministic terms. Default is 0.1.

const

a character specifying the prior mean of coefficients, which correspond to the intercept. If const = "mean", the means of the series of endogenous variables are used as prior means. If const = "first", the first values of the series of endogenous variables are used as prior means.

minnesota

a list of length 4 containing parameters for the calculation of the Minnesota prior, where the element names must be kappa0, kappa1, kappa2 and kappa3. For the endogenous variable ii the prior variance of the llth lag of regressor jj is obtained as

κ0l2 for own lags of endogenous variables,\frac{\kappa_{0}}{l^2} \textrm{ for own lags of endogenous variables,}

κ0κ1l2σi2σj2 for endogenous variables other than own lags,\frac{\kappa_{0} \kappa_{1}}{l^2} \frac{\sigma_{i}^2}{\sigma_{j}^2} \textrm{ for endogenous variables other than own lags,}

κ0κ2(l+1)2σi2σj2 for exogenous variables,\frac{\kappa_{0} \kappa_{2}}{(l+1)^2} \frac{\sigma_{i}^2}{\sigma_{j}^2} \textrm{ for exogenous variables,}

κ0κ3σi2 for deterministic terms,\kappa_{0} \kappa_{3} \sigma_{i}^2 \textrm{ for deterministic terms,}

where σi\sigma_{i} is the residual standard deviation of variable ii of an unrestricted LS estimate. For exogenous variables σi\sigma_{i} is the sample standard deviation.

The function only provides priors for the non-cointegration part of the model. However, the residual standard errors σi\sigma_i are based on an unrestricted LS regression of the endogenous variables on the error correction term and the non-cointegration regressors.

max_var

a numeric specifying the maximum prior variance that is allowed for non-deterministic coefficients.

shape

a numeric specifying the prior shape parameter of the error term of the state equation. Only used for models with time varying parameters. Default is 3.

rate

a numeric specifying the prior rate parameter of the error term of the state equation. Only used for models with time varying parameters. Default is 0.0001.

rate_det

a numeric specifying the prior rate parameter of the error term of the state equation for coefficients, which correspond to deterministic terms. Only used for models with time varying parameters. Default is 0.01.

If minnesota is specified, elements v_i and v_i_det are ignored.

Argument coint can contain the following elements:

v_i

numeric between 0 and 1 specifying the shrinkage of the cointegration space prior. Default is 0.

p_tau_i

numeric of the diagonal elements of the inverse prior matrix of the central location of the cointegration space sp(β)sp(\beta). Default is 1.

shape

an integer specifying the prior degrees of freedom of the error term of the state equation of the loading matrix α\alpha. Default is 3.

rate

a numeric specifying the prior variance of error term of the state equation of the loading matrix α\alpha. Default is 0.0001.

rho

a numeric specifying the autocorrelation coefficient of the state equation of β\beta. It must be smaller than 1. Default is 0.999. Note that in contrast to Koop et al. (2011) ρ\rho is not drawn in the Gibbs sampler of this package yet.

Argument sigma can contain the following elements:

df

an integer or character specifying the prior degrees of freedom of the error term. Only used, if the prior is inverse Wishart. Default is "k", which indicates the amount of endogenous variables in the respective model. "k + 3" can be used to set the prior to the amount of endogenous variables plus 3. If an integer is provided, the degrees of freedom are set to this value in all models. In all cases the rank rr of the cointegration matrix is automatically added.

scale

a numeric specifying the prior error variance of endogenous variables. Default is 1.

shape

a numeric or character specifying the prior shape parameter of the error term. Only used, if the prior is inverse gamma or if time varying volatilities are estimated. For models with constant volatility the default is "k", which indicates the amount of endogenous variables in the respective country model. "k + 3" can be used to set the prior to the amount of endogenous variables plus 3. If a numeric is provided, the shape parameters are set to this value in all models. For models with stochastic volatility this prior refers to the error variance of the state equation.

rate

a numeric specifying the prior rate parameter of the error term. Only used, if the prior is inverse gamma or if time varying volatilities are estimated. For models with stochastic volatility this prior refers to the error variance of the state equation.

mu

numeric of the prior mean of the initial state of the log-volatilities. Only used for models with time varying volatility.

v_i

numeric of the prior precision of the initial state of the log-volatilities. Only used for models with time varying volatility.

sigma_h

numeric of the initial draw for the variance of the log-volatilities. Only used for models with time varying volatility.

constant

numeric of the constant, which is added before taking the log of the squared errors. Only used for models with time varying volatility.

covar

logical indicating whether error covariances should be estimated. Only used in combination with an inverse gamma prior or stochastic volatility, for which shape and rate must be specified.

df and scale must be specified for an inverse Wishart prior. shape and rate are required for an inverse gamma prior. For structural models or models with stochastic volatility only a gamma prior specification is allowed.

Argument ssvs can contain the following elements:

inprior

a numeric between 0 and 1 specifying the prior probability of a variable to be included in the model.

tau

a numeric vector of two elements containing the prior standard errors of restricted variables (τ0\tau_0) as its first element and unrestricted variables (τ1\tau_1) as its second.

semiautomatic

an 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 (τ0\tau_0) and unrestricted (τ1\tau_1) variables, respectively. This is the semiautomatic approach described in George et al. (2008).

covar

logical indicating if SSVS should also be applied to the error covariance matrix as in George et al. (2008).

exclude_det

logical indicating if deterministic terms should be excluded from the SSVS algorithm.

minnesota

a numeric vector of length 4 containing parameters for the calculation of the Minnesota-like inclusion priors. See below.

Either tau or semiautomatic must be specified.

The argument bvs can contain the following elements

inprior

a numeric between 0 and 1 specifying the prior probability of a variable to be included in the model.

covar

logical indicating if BVS should also be applied to the error covariance matrix.

exclude_det

logical indicating if deterministic terms should be excluded from the BVS algorithm.

minnesota

a numeric vector of length 4 containing parameters for the calculation of the Minnesota-like inclusion priors. See below.

If either ssvs$minnesota or bvs$minnesota is specified, prior inclusion probabilities are calculated in a Minnesota-like fashion as

κ1l\frac{\kappa_1}{l} for own lags of endogenous variables,
κ2l\frac{\kappa_2}{l} for other endogenous variables,
κ31+l\frac{\kappa_3}{1 + l} for exogenous variables,
κ4\kappa_{4} for deterministic variables,

for lag ll with κ1\kappa_1, κ2\kappa_2, κ3\kappa_3, κ4\kappa_4 as the first, second, third and forth element in ssvs$minnesota or bvs$minnesota, respectively.

Value

A list of models.

References

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

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.

Examples

# Get data
data("e6")

# Create model
model <- gen_vec(e6, p = 4, r = 1,
                 const = "unrestricted", seasonal = "unrestricted",
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burnin should be much higher.

# Add priors
model <- add_priors(model)

Add Priors to Dynamic Factor Model

Description

Adds prior specifications to a list of models, which was produced by function gen_dfm.

Usage

## S3 method for class 'dfmodel'
add_priors(
  object,
  lambda = list(v_i = 0.01),
  sigma_u = list(shape = 5, rate = 4),
  a = list(v_i = 0.01),
  sigma_v = list(shape = 5, rate = 4),
  ...
)

Arguments

object

a list, usually, the output of a call to gen_dfm.

lambda

a named list of prior specifications for the factor loadings in the measurement equation. For the default specification the diagonal elements of the inverse prior variance-covariance matrix are set to 0.01. The variances need to be specified as precisions, i.e. as inverses of the variances.

sigma_u

a named list of prior specifications for the error variance-covariance matrix. See 'Details'.

a

a named list of prior specifications for the coefficients of the transition equation. For the default specification the diagonal elements of the inverse prior variance-covariance matrix are set to 0.01. The variances need to be specified as precisions, i.e. as inverses of the variances.

sigma_v

a named list of prior specifications for the error variance-covariance matrix. See 'Details'.

...

further arguments passed to or from other methods.

Details

Argument lambda can only contain the element v_i, which is a numeric specifying the prior precision of the loading factors of the measurement equation. Default is 0.01.

The function assumes an inverse gamma prior for the errors of the measurement equation. Argument sigma_u can contain the following elements:

shape

a numeric or character specifying the prior shape parameter of the error terms of the measurement equation. Default is 5.

rate

a numeric specifying the prior rate parameter of the error terms of the measurement equation. Default is 4.

Argument a can only contain the element v_i, which is a numeric specifying the prior precision of the coefficients of the transition equation. Default is 0.01.

The function assumes an inverse gamma prior for the errors of the transition equation. Argument sigma_v can contain the following elements:

shape

a numeric or character specifying the prior shape parameter of the error terms of the transition equation. Default is 5.

rate

a numeric specifying the prior rate parameter of the error terms of the transition equation. Default is 4.

Value

A list of models.

References

Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.

Lütkepohl, H. (2007). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.

Examples

# Load data
data("bem_dfmdata")

# Generate model data
model <- gen_dfm(x = bem_dfmdata, p = 1, n = 1,
                 iterations = 5000, burnin = 1000)
# Number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model,
                    lambda = list(v_i = .01),
                    sigma_u = list(shape = 5, rate = 4),
                    a = list(v_i = .01),
                    sigma_v = list(shape = 5, rate = 4))

FRED-QD data

Description

The data set contains quarterly time series for 196 US macroeconomic variables from 1959Q3 to 2015Q3. It was produced from file "freddata_Q.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/Chapter18/code_for_exercise_4/freddata_Q.csv.

Usage

data("bem_dfmdata")

Format

A named time-series object with 225 rows and 196 variables. A detailed explanation of the variables can be found in McCracken and Ng (2016).

References

Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.

McCracken, M. W., & Ng, S. (2016). FRED-MD: A monthly database for macroeconomic research. Journal of Business & Economic Statistics 34(4), 574-589. doi:10.1080/07350015.2015.1086655


Bayesian Vector Autoregression Objects

Description

bvar is used to create objects of class "bvar".

A plot function for objects of class "bvar".

Forecasting a Bayesian VAR object of class "bvar" with credible bands.

Usage

bvar(
  data = NULL,
  exogen = NULL,
  y,
  x = NULL,
  A0 = NULL,
  A = NULL,
  B = NULL,
  C = NULL,
  Sigma = NULL
)

## S3 method for class 'bvar'
plot(x, ci = 0.95, type = "hist", ...)

## S3 method for class 'bvar'
predict(object, ..., n.ahead = 10, new_x = NULL, new_d = NULL, ci = 0.95)

Arguments

data

the original time-series object of endogenous variables.

exogen

the original time-series object of unmodelled variables.

y

a time-series object of endogenous variables with TT observations, usually, a result of a call to gen_var.

x

an object of class "bvar", usually, a result of a call to draw_posterior.

A0

either a K2×SK^2 \times S matrix of MCMC coefficient draws of structural parameters or a named list, where element coeffs contains a K2×SK^2 \times S matrix of MCMC coefficient draws of structural parameters and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed. For time varying parameter models the coefficient matrix must be TK2×STK^2 \times S. Draws of the error covariance matrix of the state equation can be provided as a K2×SK^2 \times S matrix in an additional list element.

A

either a pK2×SpK^2 \times S matrix of MCMC coefficient draws of lagged endogenous variables or a named list, where element coeffs contains a pK2×SpK^2 \times S matrix of MCMC coefficient draws of lagged endogenous variables and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed. For time varying parameter models the coefficient matrix must be pTK2×SpTK^2 \times S. Draws of the error covariance matrix of the state equation can be provided as a pK2×SpK^2 \times S matrix in an additional list element.

B

either a ((1+s)MK)×S((1 + s)MK) \times S matrix of MCMC coefficient draws of unmodelled, non-deterministic variables or a named list, where element coeffs contains a ((1+s)MK)×S((1 + s)MK) \times S matrix of MCMC coefficient draws of unmodelled, non-deterministic variables and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed. For time varying parameter models the coefficient matrix must be (1+s)TMK×S(1 + s)TMK \times S. Draws of the error covariance matrix of the state equation can be provided as a (1+s)MK×S(1 + s)MK \times S matrix in an additional list element.

C

either a KN×SKN \times S matrix of MCMC coefficient draws of deterministic terms or a named list, where element coeffs contains a KN×SKN \times S matrix of MCMC coefficient draws of deterministic terms and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed. For time varying parameter models the coefficient matrix must be TKN×STKN \times S. Draws of the error covariance matrix of the state equation can be provided as a KN×SKN \times S matrix in an additional list element.

Sigma

a K2×SK^2 \times S matrix of MCMC draws for the error variance-covariance matrix or a named list, where element coeffs contains a K2×SK^2 \times S matrix of MCMC draws for the error variance-covariance matrix and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed to the covariances. For time varying parameter models the coefficient matrix must be TK2×STK^2 \times S. Draws of the error covariance matrix of the state equation can be provided as a K2×SK^2 \times S matrix in an additional list element.

ci

a numeric between 0 and 1 specifying the probability mass covered by the credible intervals. Defaults to 0.95.

type

either "hist" (default) for histograms, "trace" for a trace plot or "boxplot" for a boxplot. Only used for parameter draws of constant coefficients.

...

additional arguments.

object

an object of class "bvar", usually, a result of a call to bvar or bvec_to_bvar.

n.ahead

number of steps ahead at which to predict.

new_x

an object of class ts of new non-deterministic, exogenous variables. The object must have the same frequency as the time series in object[["x"]] and must contain at least all necessary observations for the predicted period.

new_d

a matrix of new deterministic variables. Must have n.ahead rows.

Details

For the VARX model

A0yt=i=1pAiyti+i=0sBixti+Cdt+utA_0 y_t = \sum_{i = 1}^{p} A_i y_{t-i} + \sum_{i = 0}^{s} B_i x_{t - i} + C d_t + u_t

the function collects the S draws of a Gibbs sampler (after the burn-in phase) in a standardised object, where yty_t is a K-dimensional vector of endogenous variables, A0A_0 is a K×KK \times K matrix of structural coefficients. AiA_i is a K×KK \times K coefficient matrix of lagged endogenous variabels. xtx_t is an M-dimensional vector of unmodelled, non-deterministic variables and BiB_i its corresponding coefficient matrix. dtd_t is an N-dimensional vector of deterministic terms and CC its corresponding coefficient matrix. utu_t is an error term with utN(0,Σu)u_t \sim N(0, \Sigma_u).

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.

For the VAR model

A0yt=i=1pAiyti+i=0sBixti+CDt+ut,A_0 y_t = \sum_{i = 1}^{p} A_{i} y_{t-i} + \sum_{i = 0}^{s} B_{i} x_{t-i} + C D_t + u_t,

with utN(0,Σ)u_t \sim N(0, \Sigma) the function produces n.ahead forecasts.

Value

An object of class "bvar" containing the following components, if specified:

data

the original time-series object of endogenous variables.

exogen

the original time-series object of unmodelled variables.

y

a K×TK \times T matrix of endogenous variables.

x

a (pK+(1+s)M+N)×T(pK + (1+s)M + N) \times T matrix of regressor variables.

A0

an S×K2S \times K^2 "mcmc" object of coefficient draws of structural parameters. In case of time varying parameters a list of such objects.

A0_lambda

an S×K2S \times K^2 "mcmc" object of inclusion parameters for structural parameters.

A0_sigma

an S×K2S \times K^2 "mcmc" object of the error covariance matrices of the structural parameters in a model with time varying parameters.

A

an S×pK2S \times pK^2 "mcmc" object of coefficient draws of lagged endogenous variables. In case of time varying parameters a list of such objects.

A_lambda

an S×pK2S \times pK^2 "mcmc" object of inclusion parameters for lagged endogenous variables.

A_sigma

an S×pK2S \times pK^2 "mcmc" object of the error covariance matrices of coefficients of lagged endogenous variables in a model with time varying parameters.

B

an S×((1+s)MK)S \times ((1 + s)MK) "mcmc" object of coefficient draws of unmodelled, non-deterministic variables. In case of time varying parameters a list of such objects.

B_lambda

an S×((1+s)MK)S \times ((1 + s)MK) "mcmc" object of inclusion parameters for unmodelled, non-deterministic variables.

B_sigma

an S×((1+s)MK)S \times ((1 + s)MK) "mcmc" object of the error covariance matrices of coefficients of unmodelled, non-deterministic variables in a model with time varying parameters.

C

an S×NKS \times NK "mcmc" object of coefficient draws of deterministic terms. In case of time varying parameters a list of such objects.

C_lambda

an S×NKS \times NK "mcmc" object of inclusion parameters for deterministic terms.

C_sigma

an S×NKS \times NK "mcmc" object of the error covariance matrices of coefficients of deterministic terms in a model with time varying parameters.

Sigma

an S×K2S \times K^2 "mcmc" object of variance-covariance draws. In case of time varying parameters a list of such objects.

Sigma_lambda

an S×K2S \times K^2 "mcmc" object of inclusion parameters for error covariances.

Sigma_sigma

an S×K2S \times K^2 "mcmc" object of the error covariance matrices of the coefficients of the error covariance matrix of the measurement equation of a model with time varying parameters.

specifications

a list containing information on the model specification.

A time-series object of class "bvarprd".

References

Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.

Examples

# Get data
data("e1")
e1 <- diff(log(e1))
e1 <- window(e1, end = c(1978, 4))

# Generate model data
data <- gen_var(e1, p = 2, deterministic = "const")

# Add priors
model <- add_priors(data,
                    coef = list(v_i = 0, v_i_det = 0),
                    sigma = list(df = 0, 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$Y)
x <- t(model$data$Z)
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$coefficients$mu # Vector of prior parameter means
a_v_i_prior <- model$priors$coefficients$v_i # Inverse of the prior covariance matrix

u_sigma_df_prior <- model$priors$sigma$df # Prior degrees of freedom
u_sigma_scale_prior <- model$priors$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 bvar object
bvar_est <- bvar(y = model$data$Y, x = model$data$Z,
                 A = draws_a[1:18,], C = draws_a[19:21, ],
                 Sigma = draws_sigma)
                 

# Load data 
data("e1")
e1 <- diff(log(e1)) * 100

# Generate model
model <- gen_var(e1, p = 1, deterministic = 2,
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burn-in should be much higher.

# Add priors
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Plot draws
plot(object)


# Load data
data("e1")
e1 <- diff(log(e1)) * 100
e1 <- window(e1, end = c(1978, 4))

# Generate model data
model <- gen_var(e1, p = 0, deterministic = "const",
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Generate forecasts
bvar_pred <- predict(object, n.ahead = 10, new_d = rep(1, 10))

# Plot forecasts
plot(bvar_pred)

Posterior Simulation for BVAR Models

Description

Produces draws from the posterior distributions of Bayesian VAR models.

Usage

bvarpost(object)

Arguments

object

an object of class "bvarmodel", usually, a result of a call to gen_var in combination with add_priors.

Details

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 BVAR 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 VAR model, the structural coefficients are drawn jointly with the other coefficients.

Value

An object of class "bvar".

References

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

Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271

Examples

# Get data
data("e1")
e1 <- diff(log(e1)) * 100

# Create model
model <- gen_var(e1, p = 2, deterministic = "const",
                 iterations = 50, burnin = 10)
# Number of iterations and burnin should be much higher.

# Add priors
model <- add_priors(model)

# Obtain posterior draws 
object <- bvarpost(model)

Bayesian Vector Error Correction Objects

Description

'bvec' is used to create objects of class "bvec".

A plot function for objects of class "bvec".

Usage

bvec(
  y,
  alpha = NULL,
  beta = NULL,
  beta_x = NULL,
  beta_d = NULL,
  r = NULL,
  Pi = NULL,
  Pi_x = NULL,
  Pi_d = 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
)

## S3 method for class 'bvec'
plot(x, ci = 0.95, type = "hist", ...)

Arguments

y

a time-series object of differenced endogenous variables, usually, a result of a call to gen_vec.

alpha

a Kr×SKr \times S matrix of MCMC coefficient draws of the loading matrix α\alpha.

beta

a Kr×SKr \times S matrix of MCMC coefficient draws of cointegration matrix β\beta corresponding to the endogenous variables of the model.

beta_x

a Mr×SMr \times S matrix of MCMC coefficient draws of cointegration matrix β\beta corresponding to unmodelled, non-deterministic variables.

beta_d

a NRr×SN^{R}r \times S matrix of MCMC coefficient draws of cointegration matrix β\beta corresponding to restricted deterministic terms.

r

an integer of the rank of the cointegration matrix.

Pi

a K2×SK^2 \times S matrix of MCMC coefficient draws of endogenous varaibles in the cointegration matrix.

Pi_x

a KM×SKM \times S matrix of MCMC coefficient draws of unmodelled, non-deterministic variables in the cointegration matrix.

Pi_d

a KNR×SKN^{R} \times S matrix of MCMC coefficient draws of restricted deterministic terms.

w

a time-series object of lagged endogenous variables in levels, which enter the cointegration term, usually, a result of a call to gen_vec.

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

w_d

a time-series object of deterministic terms, which enter the cointegration term, usually, a result of a call to gen_vec.

Gamma

a (p1)K2×S(p-1)K^2 \times S matrix of MCMC coefficient draws of differenced lagged endogenous variables or a named list, where element coeffs contains a (p1)K2×S(p - 1)K^2 \times S matrix of MCMC coefficient draws of lagged differenced endogenous variables and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed.

Upsilon

an sMK×SsMK \times S matrix of MCMC coefficient draws of differenced unmodelled, non-deterministic variables or a named list, where element coeffs contains a sMK×SsMK \times S matrix of MCMC coefficient draws of unmodelled, non-deterministic variables and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed.

C

an KNUR×SKN^{UR} \times S matrix of MCMC coefficient draws of unrestricted deterministic terms or a named list, where element coeffs contains a KNUR×SKN^{UR} \times S matrix of MCMC coefficient draws of deterministic terms and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed.

x

an object of class "bvec", usually, a result of a call to draw_posterior.

x_x

a time-series object of MsMs differenced unmodelled regressors.

x_d

a time-series object of NURN^{UR} deterministic terms that do not enter the cointegration term.

A0

either a K2×SK^2 \times S matrix of MCMC coefficient draws of structural parameters or a named list, where element coeffs contains a K2×SK^2 \times S matrix of MCMC coefficient draws of structural parameters and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed.

Sigma

a K2×SK^2 \times S matrix of MCMC draws for the error variance-covariance matrix or a named list, where element coeffs contains a K2×SK^2 \times S matrix of MCMC draws for the error variance-covariance matrix and element lambda contains the corresponding draws of inclusion parameters in case variable selection algorithms were employed to the covariances.

data

the original time-series object of endogenous variables.

exogen

the original time-series object of unmodelled variables.

ci

interval used to calculate credible bands for time-varying parameters.

type

either "hist" (default) for histograms, "trace" for a trace plot or "boxplot" for a boxplot. Only used for parameter draws of constant coefficients.

...

further graphical parameters.

Details

For the vector error correction model with unmodelled exogenous variables (VECX)

A0Δyt=Π+(yt1xt1dt1R)+i=1p1ΓiΔyti+i=0s1ΥiΔxti+CURdtUR+utA_0 \Delta y_t = \Pi^{+} \begin{pmatrix} y_{t-1} \\ x_{t-1} \\ d^{R}_{t-1} \end{pmatrix} + \sum_{i = 1}^{p-1} \Gamma_i \Delta y_{t-i} + \sum_{i = 0}^{s-1} \Upsilon_i \Delta x_{t-i} + C^{UR} d^{UR}_t + u_t

the function collects the SS draws of a Gibbs sampler in a standardised object, where Δyt\Delta y_t is a K-dimensional vector of differenced endogenous variables and A0A_0 is a K×KK \times K matrix of structural coefficients. Π+=[Π,Πx,Πd]\Pi^{+} = \left[ \Pi, \Pi^{x}, \Pi^{d} \right] is the coefficient matrix of the error correction term, where yt1y_{t-1}, xt1x_{t-1} and dt1Rd^{R}_{t-1} are the first lags of endogenous, exogenous variables in levels and restricted deterministic terms, respectively. Π\Pi, Πx\Pi^{x}, and Πd\Pi^{d} are the corresponding coefficient matrices, respectively. Γi\Gamma_i is a coefficient matrix of lagged differenced endogenous variabels. Δxt\Delta x_t is an M-dimensional vector of unmodelled, non-deterministic variables and Υi\Upsilon_i its corresponding coefficient matrix. dtd_t is an NURN^{UR}-dimensional vector of unrestricted deterministics and CURC^{UR} the corresponding coefficient matrix. utu_t is an error term with utN(0,Σu)u_t \sim N(0, \Sigma_u).

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, Pi, Pi_x, Pi_d, A0, Gamma, Ypsilon, C and Sigma have to correspond to the same MCMC iteration.

Value

An object of class "gvec" containing the following components, if specified:

data

the original time-series object of endogenous variables.

exogen

the original time-series object of unmodelled variables.

y

a time-series object of differenced endogenous variables.

w

a time-series object of lagged endogenous variables in levels, which enter the cointegration term.

w_x

a time-series object of lagged unmodelled, non-deterministic variables in levels, which enter the cointegration term.

w_d

a time-series object of deterministic terms, which enter the cointegration term.

x

a time-series object of K(p1)K(p - 1) differenced endogenous variables

x_x

a time-series object of MsMs differenced unmodelled regressors.

x_d

a time-series object of NURN^{UR} deterministic terms that do not enter the cointegration term.

A0

an S×K2S \times K^2 "mcmc" object of coefficient draws of structural parameters. In case of time varying parameters a list of such objects.

A0_lambda

an S×K2S \times K^2 "mcmc" object of inclusion parameters for coefficients corresponding to structural parameters.

A0_sigma

an S×K2S \times K^2 "mcmc" object of the error covariance matrices of the structural parameters in a model with time varying parameters.

alpha

an S×KrS \times Kr "mcmc" object of coefficient draws of loading parameters. In case of time varying parameters a list of such objects.

beta

an S×((K+M+NR)r)S \times ((K + M + N^{R})r) "mcmc" object of coefficient draws of cointegration parameters corresponding to the endogenous variables of the model. In case of time varying parameters a list of such objects.

beta_x

an S×KMS \times KM "mcmc" object of coefficient draws of cointegration parameters corresponding to unmodelled, non-deterministic variables. In case of time varying parameters a list of such objects.

beta_d

an S×KNRS \times KN^{R} "mcmc" object of coefficient draws of cointegration parameters corresponding to restricted deterministic variables. In case of time varying parameters a list of such objects.

Pi

an S×K2S \times K^2 "mcmc" object of coefficient draws of endogenous variables in the cointegration matrix. In case of time varying parameters a list of such objects.

Pi_x

an S×KMS \times KM "mcmc" object of coefficient draws of unmodelled, non-deterministic variables in the cointegration matrix. In case of time varying parameters a list of such objects.

Pi_d

an S×KNRS \times KN^{R} "mcmc" object of coefficient draws of restricted deterministic variables in the cointegration matrix. In case of time varying parameters a list of such objects.

Gamma

an S×(p1)K2S \times (p-1)K^2 "mcmc" object of coefficient draws of differenced lagged endogenous variables. In case of time varying parameters a list of such objects.

Gamma_lamba

an S×(p1)K2S \times (p-1)K^2 "mcmc" object of inclusion parameters for coefficients corresponding to differenced lagged endogenous variables.

Gamma_sigma

an S×(p1)K2S \times (p - 1)K^2 "mcmc" object of the error covariance matrices of the coefficients of lagged endogenous variables in a model with time varying parameters.

Upsilon

an S×sMKS \times sMK "mcmc" object of coefficient draws of differenced unmodelled, non-deterministic variables. In case of time varying parameters a list of such objects.

Upsilon_lambda

an S×sMKS \times sMK "mcmc" object of inclusion parameters for coefficients corresponding to differenced unmodelled, non-deterministic variables.

Upsilon_sigma

an S×sMKS \times sMK "mcmc" object of the error covariance matrices of the coefficients of unmodelled, non-deterministic variables in a model with time varying parameters.

C

an S×KNURS \times KN^{UR} "mcmc" object of coefficient draws of deterministic terms that do not enter the cointegration term. In case of time varying parameters a list of such objects.

C_lambda

an S×KNURS \times KN^{UR} "mcmc" object of inclusion parameters for coefficients corresponding to deterministic terms, that do not enter the conintegration term.

C_sigma

an S×KNURS \times KN^{UR} "mcmc" object of the error covariance matrices of the coefficients of deterministic terms, which do not enter the cointegration term, in a model with time varying parameters.

Sigma

an S×K2S \times K^2 "mcmc" object of variance-covariance draws. In case of time varying parameters a list of such objects.

Sigma_lambda

an S×K2S \times K^2 "mcmc" object inclusion parameters for the variance-covariance matrix.

Sigma_sigma

an S×K2S \times K^2 "mcmc" object of the error covariance matrices of the coefficients of the error covariance matrix of the measurement equation of a model with time varying parameters.

specifications

a list containing information on the model specification.

Examples

# Load data
data("e6")
# Generate model
data <- gen_vec(e6, p = 4, r = 1, const = "unrestricted", season = "unrestricted")
# Obtain data matrices
y <- t(data$data$Y)
w <- t(data$data$W)
x <- t(data$data$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_x * k) # Vector of prior parameter means
a_v_i_prior <- diag(0, k_x * k) # 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, 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_pi <- matrix(NA, k * k_w, 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, x = x, sigma_i = u_sigma_i,
                         v_i = v_i, p_tau_i = p_tau_i, g_i = g_i,
                         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_pi[, draw - burnin] <- Pi
    draws_gamma[, draw - burnin] <- gamma
    draws_sigma[, draw - burnin] <- u_sigma
  }
}

# Number of non-deterministic coefficients
k_nondet <- (k_x - 4) * k

# Generate bvec object
bvec_est <- bvec(y = data$data$Y, w = data$data$W,
                 x = data$data$X[, 1:6],
                 x_d = data$data$X[, 7:10],
                 Pi = draws_pi,
                 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 <- gen_vec(data = e6, p = 2, r = 1, const = "unrestricted",
                 iterations = 20, burnin = 10)
# Chosen number of iterations and burn-in should be much higher.

# Add priors
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Plot draws
plot(object)

Transform a VEC Model to a VAR in Levels

Description

An object of class "bvec" is transformed to a VAR in level representation.

Usage

bvec_to_bvar(object)

Arguments

object

an object of class "bvec".

Value

An object of class "bvar".

References

Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.

Examples

# Load data
data("e6")

# Generate model
data <- gen_vec(e6, p = 4, r = 1, const = "unrestricted", season = "unrestricted")

# Obtain data matrices
y <- t(data$data$Y)
w <- t(data$data$W)
x <- t(data$data$X)

# Reset random number generator for reproducibility
set.seed(1234567)

iterations <- 100 # 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_x * k) # Vector of prior parameter means
a_v_i_prior <- diag(0, k_x * k) # 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, 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_pi <- matrix(NA, k * k_w, 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, x = x, sigma_i = u_sigma_i,
                         v_i = v_i, p_tau_i = p_tau_i, g_i = g_i,
                         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_pi[, draw - burnin] <- Pi
    draws_gamma[, draw - burnin] <- gamma
    draws_sigma[, draw - burnin] <- u_sigma
  }
}

# Number of non-deterministic coefficients
k_nondet <- (k_x - 4) * k

# Generate bvec object
bvec_est <- bvec(y = data$data$Y, w = data$data$W,
                 x = data$data$X[, 1:6],
                 x_d = data$data$X[, 7:10],
                 Pi = draws_pi,
                 Gamma = draws_gamma[1:k_nondet,],
                 C = draws_gamma[(k_nondet + 1):nrow(draws_gamma),],
                 Sigma = draws_sigma)

# Thin posterior draws
bvec_est <- thin(bvec_est, thin = 5)

# Transfrom VEC output to VAR output
bvar_form <- bvec_to_bvar(bvec_est)

Posterior Simulation for BVEC Models

Description

Produces draws from the posterior distributions of Bayesian VEC models.

Usage

bvecpost(object)

Arguments

object

an object of class "bvecmodel", usually, a result of a call to gen_vec in combination with add_priors.

Details

The function implements posterior simulation algorithms proposed in Koop et al. (2010) and Koop et al. (2011), which place identifying restrictions on the cointegration space. Both algorithms are able to employ Bayesian variable selection (BVS) as proposed in Korobilis (2013). The algorithm of Koop et al. (2010) is also able to employ stochastic search variable selection (SSVS) as proposed by Geroge et al. (2008). Both SSVS and BVS can also be applied to the covariances of the error term. However, the algorithms cannot be applied to cointegration related coefficients, i.e. to the loading matrix α\alpha or the cointegration matrix betabeta.

The implementation primarily follows the description in Koop et al. (2010). Chan et al. (2019), George et al. (2008) and Korobilis (2013) were used to implement the variable selection algorithms. For all approaches the SUR form of a VEC 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. No identifying restrictions are made regarding the cointegration matrix.

Value

An object of class "bvec".

References

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

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

Examples

# Get data
data("e6")

# Create model
model <- gen_vec(e6, p = 4, r = 1,
                 const = "unrestricted", seasonal = "unrestricted",
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burnin should be much higher.

# Add priors
model <- add_priors(model)

# Obtain posterior draws 
object <- bvecpost(model)

Bayesian Variable Selection

Description

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.

Usage

bvs(y, z, a, lambda, sigma_i, prob_prior, include = NULL)

Arguments

y

a K×TK \times T matrix of the endogenous variables.

z

a KT×MKT \times M matrix of explanatory variables.

a

an M-dimensional vector of parameter draws. If time varying parameters are used, an M×TM \times T coefficient matrix can be provided.

lambda

an M×MM \times M inclusion matrix that should be updated.

sigma_i

the inverse variance-covariance matrix. If the variance-covariance matrix is time varying, a KT×KKT \times K matrix can be provided.

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 NULL (default), BVS will be applied to all variables.

Details

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 Λ\Lambda for the VAR model

yt=ZtΛat+ut,y_t = Z_t \Lambda a_t + u_t,

where utN(0,Σt)u_t \sim N(0, \Sigma_{t}). yty_t is a K-dimensional vector of endogenous variables and Zt=xtIKZ_t = x_t^{\prime} \otimes I_K is a K×MK \times M matrix of regressors with xtx_t as a vector of regressors.

Value

A matrix of inclusion parameters on its diagonal.

References

Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. Journal of Applied Econometrics, 28(2), 204–230. doi:10.1002/jae.1271

Examples

# Load data
data("e1")
data <- diff(log(e1)) * 100

# Generate model data
temp <- gen_var(data, p = 2, deterministic = "const")

y <- t(temp$data$Y)
z <- temp$data$SUR

tt <- ncol(y)
m <- ncol(z)

# Priors
a_mu_prior <- matrix(0, m)
a_v_i_prior <- diag(0.1, m)

# Prior for inclusion parameter
prob_prior <- matrix(0.5, m)

# Initial value of Sigma
sigma <- tcrossprod(y) / tt
sigma_i <- solve(sigma)

lambda <- diag(1, m)

z_bvs <- z %*% lambda

a <- post_normal_sur(y = y, z = z_bvs, sigma_i = sigma_i,
                     a_prior = a_mu_prior, v_i_prior = a_v_i_prior)

lambda <- bvs(y = y, z = z, a = a, lambda = lambda,
              sigma_i = sigma_i, prob_prior = prob_prior)

Bayesian Dynamic Factor Model Objects

Description

dfm is used to create objects of class "dfm".

A plot function for objects of class "dfm".

Usage

dfm(x, lambda = NULL, fac, sigma_u = NULL, a = NULL, sigma_v = NULL)

## S3 method for class 'dfm'
plot(x, ci = 0.95, ...)

Arguments

x

an object of class "dfm", usually, a result of a call to dfm.

lambda

an MN×SMN \times S matrix of MCMC coefficient draws of factor loadings of the measurement equation.

fac

an NT×SNT \times S matrix of MCMC draws of the factors in the transition equation, where the first N rows correspond to the N factors in period 1 and the next N rows to the factors in period 2 etc.

sigma_u

an M×SM \times S matrix of MCMC draws for the error variances of the measurement equation.

a

a pN2×SpN^2 \times S matrix of MCMC coefficient draws of the transition equation.

sigma_v

an N×SN \times S matrix of MCMC draws for the error variances of the transition equation.

ci

interval used to calculate credible bands.

...

further graphical parameters.

Details

The function produces a standardised object from S draws of a Gibbs sampler (after the burn-in phase) for the dynamic factor model (DFM) with measurement equation

xt=λft+ut,x_t = \lambda f_t + u_t,

where xtx_t is an M×1M \times 1 vector of observed variables, ftf_t is an N×1N \times 1 vector of unobserved factors and λ\lambda is the corresponding M×NM \times N matrix of factor loadings. utu_t is an M×1M \times 1 error term.

The transition equation is

ft=i=1pAifti+vt,f_t = \sum_{i=1}^{p} A_i f_{t - i} + v_t,

where AiA_i is an N×NN \times N coefficient matrix and vtv_t is an N×1N \times 1 error term.

Value

An object of class "dfm" containing the following components, if specified:

x

the standardised time-series object of observable variables.

lambda

an S×MNS \times MN "mcmc" object of draws of factor loadings of the measurement equation.

factor

an S×NTS \times NT "mcmc" object of draws of factors.

sigma_u

an S×MS \times M "mcmc" object of variance draws of the measurement equation.

a

an S×pN2S \times pN^2 "mcmc" object of coefficient draws of the transition equation.

sigma_v

an S×NS \times N "mcmc" object of variance draws of the transition equation.

specifications

a list containing information on the model specification.

Examples

# Load data
data("bem_dfmdata")

# Generate model data
model <- gen_dfm(x = bem_dfmdata, p = 1, n = 1,
                 iterations = 20, burnin = 10)
# Number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model,
                    lambda = list(v_i = .01),
                    sigma_u = list(shape = 5, rate = 4),
                    a = list(v_i = .01),
                    sigma_v = list(shape = 5, rate = 4))

# Obtain posterior draws
object <- dfmpost(model)


# Load data
data("bem_dfmdata")

# Generate model data
model <- gen_dfm(x = bem_dfmdata, p = 1, n = 1,
                 iterations = 20, burnin = 10)
# Number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model,
                    lambda = list(v_i = .01),
                    sigma_u = list(shape = 5, rate = 4),
                    a = list(v_i = .01),
                    sigma_v = list(shape = 5, rate = 4))

# Obtain posterior draws
object <- draw_posterior(model)

# Plot factors
plot(object)

Posterior Simulation for Dynamic Factor Models

Description

Produces draws from the posterior distributions of Bayesian dynamic factor models.

Usage

dfmpost(object)

Arguments

object

an object of class "dfmodel", usually, a result of a call to gen_dfm in combination with add_priors.

Details

The function implements the posterior simulation algorithm for Bayesian dynamic factor models.

The implementation follows the description in Chan et al. (2019) and C++ is used to reduce calculation time.

Value

An object of class "dfm".

References

Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.

Examples

# Load data
data("bem_dfmdata")

# Generate model data
model <- gen_dfm(x = bem_dfmdata, p = 1, n = 1,
                 iterations = 20, burnin = 10)
# Number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model,
                    lambda = list(v_i = .01),
                    sigma_u = list(shape = 5, rate = 4),
                    a = list(v_i = .01),
                    sigma_v = list(shape = 5, rate = 4))

# Obtain posterior draws
object <- dfmpost(model)

Posterior Simulation

Description

Forwards model input to posterior simulation functions. This is a generic function.

Usage

draw_posterior(object, ...)

Arguments

object

a list of model specifications. Usually, the output of a call to gen_var, gen_vec or gen_dfm in combination with add_priors.

...

arguments passed forward to method.


Posterior Simulation

Description

Forwards model input to posterior simulation functions.

Usage

## S3 method for class 'bvarmodel'
draw_posterior(object, FUN = NULL, mc.cores = NULL, ...)

Arguments

object

a list of model specifications, which should be passed on to function FUN. Usually, the output of a call to gen_var in combination with add_priors.

FUN

the function to be applied to each model in argument object. If NULL (default), the internal functions bvarpost is used.

mc.cores

the number of cores to use, i.e. at most how many child processes will be run simultaneously. The option is initialized from environment variable MC_CORES if set. Must be at least one, and parallelization requires at least two cores.

...

further arguments passed to or from other methods.

Value

For multiple models a list of objects of class bvarlist. For a single model the object has the class of the output of the applied posterior simulation function. In case the package's own functions are used, this will result in an object of class "bvar".

Examples

# Load data 
data("e1")
e1 <- diff(log(e1)) * 100

# Generate model
model <- gen_var(e1, p = 1:2, deterministic = 2,
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burn-in should be much higher.

# Add priors
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

Posterior Simulation for Vector Error Correction Models

Description

Forwards model input to posterior simulation functions for vector error correction models.

Usage

## S3 method for class 'bvecmodel'
draw_posterior(object, FUN = NULL, mc.cores = NULL, ...)

Arguments

object

a list of model specifications, which should be passed on to function FUN. Usually, the output of a call to gen_vec in combination with add_priors.

FUN

the function to be applied to each list element in argument object. If NULL (default), the internal function bvecpost is used.

mc.cores

the number of cores to use, i.e. at most how many child processes will be run simultaneously. The option is initialized from environment variable MC_CORES if set. Must be at least one, and parallelization requires at least two cores.

...

further arguments passed to or from other methods.

Value

For multiple models a list of objects of class bvarlist. For a single model the object has the class of the output of the applied posterior simulation function. In case the package's own functions are used, this will be "bvec".

References

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

Examples

# Load data 
data("e6")
e6 <- e6 * 100

# Generate model
model <- gen_vec(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)

# Obtain posterior draws
object <- draw_posterior(model)

Posterior Simulation

Description

Forwards model input to posterior simulation functions.

Usage

## S3 method for class 'dfmodel'
draw_posterior(object, FUN = NULL, mc.cores = NULL, ...)

Arguments

object

a list of model specifications, which should be passed on to function FUN. Usually, the output of a call to gen_var, gen_vec or gen_dfm in combination with add_priors.

FUN

the function to be applied to each list element in argument object. If NULL (default), the internal functions bvarpost is used for VAR model, bvecpost for VEC models and dfmpost for dynamic factor models.

mc.cores

the number of cores to use, i.e. at most how many child processes will be run simultaneously. The option is initialized from environment variable MC_CORES if set. Must be at least one, and parallelization requires at least two cores.

...

further arguments passed to or from other methods.

Value

For multiple models a list of objects of class bvarlist. For a single model the object has the class of the output of the applied posterior simulation function. In case the package's own functions are used, this will be "bvar", "bvec" or "dfm".

Examples

# Load data 
data("e1")
e1 <- diff(log(e1)) * 100

# Generate model
model <- gen_var(e1, p = 1:2, deterministic = 2,
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burn-in should be much higher.

# Add priors
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

West German economic time series data

Description

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 (2007). Raw data are available at http://www.jmulti.de/download/datasets/e1.dat and were originally obtained from Deutsche Bundesbank.

Usage

data("e1")

Format

A named time-series object with 92 rows and 3 variables:

invest

fixed investment.

income

disposable income.

cons

consumption expenditures.

References

Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.


German interest and inflation rate data

Description

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

Usage

data("e6")

Format

A named time-series object with 107 rows and 2 variables:

R

nominal long-term interest rate (Umlaufsrendite).

Dp

Δ\Delta log of GDP deflator.

Details

The data cover West Germany until 1990Q2 and all of Germany aferwards. The values refer to the last month of a quarter.

References

Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.


Forecast Error Variance Decomposition A generic function used to calculate forecast error varianc decompositions.

Description

A plot function for objects of class "bvarfevd".

Usage

fevd(object, ...)

## S3 method for class 'bvarfevd'
plot(x, ...)

Arguments

object

an object of class "bvar".

...

further graphical parameters.

x

an object of class "bvarfevd", usually, a result of a call to fevd.

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Generate model data
model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Obtain FEVD
vd <- fevd(object, response = "cons")

# Plot
plot(vd)

Forecast Error Variance Decomposition

Description

Produces the forecast error variance decomposition of a Bayesian VAR model.

Usage

## S3 method for class 'bvar'
fevd(
  object,
  response = NULL,
  n.ahead = 5,
  type = "oir",
  normalise_gir = FALSE,
  period = NULL,
  ...
)

Arguments

object

an object of class "bvar", usually, a result of a call to bvar or bvec_to_bvar.

response

name of the response variable.

n.ahead

number of steps ahead.

type

type of the impulse responses used to calculate forecast error variable decompositions. Possible choices are orthogonalised oir (default) and generalised gir impulse responses.

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 NULL, so that the posterior draws of the last time period are used.

...

further arguments passed to or from other methods.

Details

The function produces forecast error variance decompositions (FEVD) for the VAR model

A0yt=i=1pAiyti+ut,A_0 y_t = \sum_{i = 1}^{p} A_{i} y_{t-i} + u_t,

with utN(0,Σ)u_t \sim N(0, \Sigma). For non-structural models matrix A0A_0 is set to the identiy matrix and can therefore be omitted, where not relevant.

If the FEVD is based on the orthogonalised impulse resonse (OIR), the FEVD will be calculated as

ωjk,hOIR=i=0h1(ejΦiPek)2i=0h1(ejΦiΣΦiej),\omega^{OIR}_{jk, h} = \frac{\sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i P e_k )^2}{\sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i \Sigma \Phi_i^{\prime} e_j )},

where Φi\Phi_i is the forecast error impulse response for the iith period, PP is the lower triangular Choleski decomposition of the variance-covariance matrix Σ\Sigma, eje_j is a selection vector for the response variable and eke_k a selection vector for the impulse variable.

If type = "sir", the structural FEVD will be calculated as

ωjk,hSIR=i=0h1(ejΦiA01ek)2i=0h1(ejΦiA01A01Φiej),\omega^{SIR}_{jk, h} = \frac{\sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i A_0^{-1} e_k )^2}{\sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i A_0^{-1} A_0^{-1\prime} \Phi_i^{\prime} e_j )},

where σjj\sigma_{jj} is the diagonal element of the jjth variable of the variance covariance matrix.

If type = "gir", the generalised FEVD will be calculated as

ωjk,hGIR=σjj1i=0h1(ejΦiΣek)2i=0h1(ejΦiΣΦiej),\omega^{GIR}_{jk, h} = \frac{\sigma^{-1}_{jj} \sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i \Sigma e_k )^2}{\sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i \Sigma \Phi_i^{\prime} e_j )},

where σjj\sigma_{jj} is the diagonal element of the jjth variable of the variance covariance matrix.

If type = "sgir", the structural generalised FEVD will be calculated as

ωjk,hSGIR=σjj1i=0h1(ejΦiA01Σek)2i=0h1(ejΦiA01ΣA01Φiej)\omega^{SGIR}_{jk, h} = \frac{\sigma^{-1}_{jj} \sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i A_0^{-1} \Sigma e_k )^2}{\sum_{i = 0}^{h-1} (e_j^{\prime} \Phi_i A_0^{-1} \Sigma A_0^{-1\prime} \Phi_i^{\prime} e_j )}

.

Since GIR-based FEVDs do not add up to unity, they can be normalised by setting normalise_gir = TRUE.

Value

A time-series object of class "bvarfevd".

References

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.

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Generate models
model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)

# Add priors
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Obtain FEVD
vd <- fevd(object, response = "cons")

# Plot FEVD
plot(vd)

Dynamic Factor Model Input

Description

gen_dfm produces the input for the estimation of a dynamic factor model (DFM).

Usage

gen_dfm(x, p = 2, n = 1, iterations = 50000, burnin = 5000)

Arguments

x

a time-series object of stationary endogenous variables.

p

an integer vector of the lag order of the measurement equation. See 'Details'.

n

an integer vector of the number of factors. See 'Details'.

iterations

an integer of MCMC draws excluding burn-in draws (defaults to 50000).

burnin

an integer of MCMC draws used to initialize the sampler (defaults to 5000). These draws do not enter the computation of posterior moments, forecasts etc.

Details

The function produces the variable matrices of dynamic factor models (DFM) with measurement equation

xt=λft+ut,x_t = \lambda f_t + u_t,

where xtx_t is an M×1M \times 1 vector of observed variables, ftf_t is an N×1N \times 1 vector of unobserved factors and λ\lambda is the corresponding M×NM \times N matrix of factor loadings. utu_t is an M×1M \times 1 error term.

The transition equation is

ft=i=1pAifti+vt,f_t = \sum_{i=1}^{p} A_i f_{t - i} + v_t,

where AiA_i is an N×NN \times N coefficient matrix and vtv_t is an N×1N \times 1 error term.

If integer vectors are provided as arguments p or n, the function will produce a distinct model for all possible combinations of those specifications.

Value

An object of class 'dfmodel', which contains the following elements:

data

A list of data objects, which can be used for posterior simulation. Element X is a time-series object of normalised observable variables, i.e. each column has zero mean and unity variance.

model

A list of model specifications.

References

Chan, J., Koop, G., Poirier, D. J., & Tobias, J. L. (2019). Bayesian Econometric Methods (2nd ed.). Cambridge: University Press.

Lütkepohl, H. (2007). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.

Examples

# Load data
data("bem_dfmdata")

# Generate model data
model <- gen_dfm(x = bem_dfmdata, p = 1, n = 1,
                 iterations = 5000, burnin = 1000)

Vector Autoregressive Model Input

Description

gen_var produces the input for the estimation of a vector autoregressive (VAR) model.

Usage

gen_var(
  data,
  p = 2,
  exogen = NULL,
  s = NULL,
  deterministic = "const",
  seasonal = FALSE,
  structural = FALSE,
  tvp = FALSE,
  sv = FALSE,
  fcst = NULL,
  iterations = 50000,
  burnin = 5000
)

Arguments

data

a time-series object of endogenous variables.

p

an integer vector of the lag order (default is p = 2).

exogen

an optional time-series object of external regressors.

s

an optional integer vector of the lag order of the external regressors (default is s = 2).

deterministic

a character specifying which deterministic terms should be included. Available values are "none", "const" (default) for an intercept, "trend" for a linear trend, and "both" for an intercept with a linear trend.

seasonal

logical. If TRUE, seasonal dummy variables are generated as additional deterministic terms. The amount of dummies depends on the frequency of the time-series object provided in data.

structural

logical indicating whether data should be prepared for the estimation of a structural VAR model.

tvp

logical indicating whether the model parameters are time varying.

sv

logical indicating whether time varying error variances should be estimated by employing a stochastic volatility algorithm.

fcst

integer. Number of observations saved for forecasting evaluation.

iterations

an integer of MCMC draws excluding burn-in draws (defaults to 50000).

burnin

an integer of MCMC draws used to initialize the sampler (defaults to 5000). These draws do not enter the computation of posterior moments, forecasts etc.

Details

The function produces the data matrices for vector autoregressive (VAR) models, which can also include unmodelled, non-deterministic variables:

A0yt=i=1pAiyti+i=0sBixti+CDt+ut,A_0 y_t = \sum_{i=1}^{p} A_i y_{t - i} + \sum_{i=0}^{s} B_i x_{t - i} + C D_t + u_t,

where yty_t is a K-dimensional vector of endogenous variables, A0A_0 is a K×KK \times K coefficient matrix of contemporaneous endogenous variables, AiA_i is a K×KK \times K coefficient matrix of endogenous variables, xtx_t is an M-dimensional vector of exogenous regressors and BiB_i its corresponding K×MK \times M coefficient matrix. DtD_t is an N-dimensional vector of deterministic terms and CC its corresponding K×NK \times N coefficient matrix. pp is the lag order of endogenous variables, ss is the lag order of exogenous variables, and utu_t is an error term.

If an integer vector is provided as argument p or s, the function will produce a distinct model for all possible combinations of those specifications.

If tvp is TRUE, the respective coefficients of the above model are assumed to be time varying. If sv is TRUE, the error covariance matrix is assumed to be time varying.

Value

An object of class 'bvarmodel', which contains the following elements:

data

A list of data objects, which can be used for posterior simulation. Element Y is a time-series object of dependent variables. Element Z is a time-series object of the regressors and element SUR is the corresponding matrix of regressors in SUR form.

model

A list of model specifications.

References

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.

Examples

# Load data
data("e1") 
e1 <- diff(log(e1))

# Generate model data
data <- gen_var(e1, p = 0:2, deterministic = "const")

Vector Error Correction Model Input

Description

gen_vec produces the input for the estimation of a vector error correction (VEC) model.

Usage

gen_vec(
  data,
  p = 2,
  exogen = NULL,
  s = 2,
  r = NULL,
  const = NULL,
  trend = NULL,
  seasonal = NULL,
  structural = FALSE,
  tvp = FALSE,
  sv = FALSE,
  fcst = NULL,
  iterations = 50000,
  burnin = 5000
)

Arguments

data

a time-series object of endogenous variables.

p

an integer vector of the lag order of the series in the (levels) VAR. Thus, the resulting model's lag will be p1p - 1. See 'Details'.

exogen

an optional time-series object of external regressors.

s

an optional integer vector of the lag order of the exogenous variables of the series in the (levels) VAR. Thus, the resulting model's lag will be s1s - 1. See 'Details'.

r

an integer vector of the cointegration rank. See 'Details'.

const

a character specifying whether a constant term enters the error correction term ("restricted") or the non-cointegration term as an "unrestricted" variable. If NULL (default) no constant term will be added.

trend

a character specifying whether a trend term enters the error correction term ("restricted") or the non-cointegration term as an "unrestricted" variable. If NULL (default) no constant term will be added.

seasonal

a character specifying whether seasonal dummies should be included in the error correction term ("restricted") or in the non-cointegreation term as "unrestricted" variables. If NULL (default) no seasonal terms will be added. The amount of dummy variables will be automatically detected and depends on the frequency of the time-series object provided in data.

structural

logical indicating whether data should be prepared for the estimation of a structural VAR model.

tvp

logical indicating whether the model parameters are time varying.

sv

logical indicating whether time varying error variances should be estimated by employing a stochastic volatility algorithm.

fcst

integer. Number of observations saved for forecasting evaluation.

iterations

an integer of MCMC draws excluding burn-in draws (defaults to 50000).

burnin

an integer of MCMC draws used to initialize the sampler (defaults to 5000). These draws do not enter the computation of posterior moments, forecasts etc.

Details

The function produces the variable matrices of vector error correction (VEC) models, which can also include exogenous variables:

Δyt=Πwt+i=1p1ΓiΔyti+i=0s1ΥiΔxti+CURdtUR+ut,\Delta y_t = \Pi w_t + \sum_{i=1}^{p-1} \Gamma_{i} \Delta y_{t - i} + \sum_{i=0}^{s-1} \Upsilon_{i} \Delta x_{t - i} + C^{UR} d^{UR}_t + u_t,

where Δyt\Delta y_t is a K×1K \times 1 vector of differenced endogenous variables, wtw_t is a (K+M+NR)×1(K + M + N^{R}) \times 1 vector of cointegration variables, Π\Pi is a K×(K+M+NR)K \times (K + M + N^{R}) matrix of cointegration parameters, Γi\Gamma_i is a K×KK \times K coefficient matrix of endogenous variables, Δxt\Delta x_t is a M×1M \times 1 vector of differenced exogenous regressors, Υi\Upsilon_i is a K×MK \times M coefficient matrix of exogenous regressors, dtURd^{UR}_t is a N×1N \times 1 vector of deterministic terms, and CURC^{UR} is a K×NURK \times N^{UR} coefficient matrix of deterministic terms that do not enter the cointegration term. pp is the lag order of endogenous variables and ss is the lag order of exogenous variables of the corresponding VAR model. utu_t is a K×1K \times 1 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.

If tvp is TRUE, the respective coefficients of the above model are assumed to be time varying. If sv is TRUE, the error covariance matrix is assumed to be time varying.

Value

An object of class 'bvecmodel', which contains the following elements:

data

A list of data objects, which can be used for posterior simulation. Element Y is a time-series object of dependent variables. Element W is a timer-series object of variables in the cointegration term and element X is a time-series object of variables that do not enter the cointegration term. Element SUR contains a matrix of element X in its SUR form.

model

A list of model specifications.

References

Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.

Examples

# Load data
data("e6")

# Generate model data
data <- gen_vec(e6, p = 4, const = "unrestricted", season = "unrestricted")

Prior Inclusion Probabilities

Description

Prior inclusion probabilities as required for stochastic search variable selection (SSVS) à la George et al. (2008) and Bayesian variable selection (BVS) à la Korobilis (2013).

Usage

inclusion_prior(
  object,
  prob = 0.5,
  exclude_deterministics = TRUE,
  minnesota_like = FALSE,
  kappa = c(0.8, 0.5, 0.5, 0.8)
)

Arguments

object

an object of class "bvarmodel", usually, a result of a call to gen_var or gen_vec.

prob

a numeric specifying the prior inclusion probability of all model parameters.

exclude_deterministics

logical. If TRUE (default), the vector of the positions of included variables does not include the positions of deterministic terms.

minnesota_like

logical. If TRUE, the prior inclusion probabilities of the parameters are calculated in a similar way as the Minnesota prior. See 'Details'.

kappa

a numeric vector of four elements containing the prior inclusion probabilities of coefficients that correspond to own lags of endogenous variables, to endogenous variables, which do not correspond to own lags, to exogenous variables and deterministic terms, respectively. Only used if minnesota_like = TRUE. See 'Details'.

Details

If minnesota_like = TRUE, prior inclusion probabilities π1\underline{\pi}_1 are calculated as

κ1r\frac{\kappa_1}{r} for own lags of endogenous variables,
κ2r\frac{\kappa_2}{r} for other endogenous variables,
κ31+r\frac{\kappa_3}{1 + r} for exogenous variables,
κ4\kappa_{4} for deterministic variables,

for lag rr with κ1\kappa_1, κ2\kappa_2, κ3\kappa_3, κ4\kappa_4 as the first, second, third and forth element in kappa, respectively.

For vector error correction models the function generates prior inclusion probabilities for differenced variables and unrestricted deterministc terms as described above. For variables in the error correction term prior inclusion probabilites are calculated as

κ1\kappa_1 fow own levels of endogenous variables,
κ2\kappa_2 for levels of other endogenous variables,
κ3\kappa_3 for levels of exogenous variables,
κ4\kappa_4 for deterministic variables.

Value

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 selction algorithm.

References

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

Examples

# Prepare data
data("e1")

# Generate model input
object <- gen_var(e1)

# Obtain inclusion prior
pi_prior <- inclusion_prior(object)

Impulse Response Function A generic function used to calculate impulse response functions.

Description

A plot function for objects of class "bvarirf".

Usage

irf(x, ...)

## S3 method for class 'bvarirf'
plot(x, ...)

Arguments

x

an object of class "bvarirf", usually, a result of a call to irf.

...

further graphical parameters.

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Generate model data
model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)
# Number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model)

# Optain posterior draws
object <- draw_posterior(model)

# Calculate IR
ir <- irf(object, impulse = "invest", response = "cons")

# Plot IR
plot(ir)

Impulse Response Function

Description

Computes the impulse response coefficients of an object of class "bvar" for n.ahead steps.

Usage

## S3 method for class 'bvar'
irf(
  x,
  impulse = NULL,
  response = NULL,
  n.ahead = 5,
  ci = 0.95,
  shock = 1,
  type = "feir",
  cumulative = FALSE,
  keep_draws = FALSE,
  period = NULL,
  ...
)

Arguments

x

an object of class "bvar", usually, a result of a call to bvar or bvec_to_bvar.

impulse

name of the impulse variable.

response

name of the response variable.

n.ahead

number of steps ahead.

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.

type

type of the impulse response. Possible choices are forecast error "feir" (default), orthogonalised "oir", structural "sir", generalised "gir", and structural generalised "sgir" impulse responses.

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 FALSE so that the median and the credible intervals of the posterior draws are returned.

period

integer. Index of the period, for which the IR should be generated. Only used for TVP or SV models. Default is NULL, so that the posterior draws of the last time period are used.

...

further arguments passed to or from other methods.

Details

The function produces different types of impulse responses for the VAR model

A0yt=i=1pAiyti+ut,A_0 y_t = \sum_{i = 1}^{p} A_{i} y_{t-i} + u_t,

with utN(0,Σ)u_t \sim N(0, \Sigma).

Forecast error impulse responses Φi\Phi_i are obtained by recursions

Φi=j=1iΦijAj,i=1,2,...,h\Phi_i = \sum_{j = 1}^{i} \Phi_{i-j} A_j, i = 1, 2,...,h

with Φ0=IK\Phi_0 = I_K.

Orthogonalised impulse responses Θio\Theta^o_i are calculated as Θio=ΦiP\Theta^o_i = \Phi_i P, where P is the lower triangular Choleski decomposition of Σ\Sigma.

Structural impulse responses Θis\Theta^s_i are calculated as Θis=ΦiA01\Theta^s_i = \Phi_i A_0^{-1}.

(Structural) Generalised impulse responses for variable jj, i.e. Θjgi\Theta^g_ji are calculated as Θjig=σjj1/2ΦiA01Σej\Theta^g_{ji} = \sigma_{jj}^{-1/2} \Phi_i A_0^{-1} \Sigma e_j, where σjj\sigma_{jj} is the variance of the jthj^{th} diagonal element of Σ\Sigma and eie_i is a selection vector containing one in its jthj^{th} element and zero otherwise. If the "bvar" object does not contain draws of A0A_0, it is assumed to be an identity matrix.

Value

A time-series object of class "bvarirf" and if keep_draws = TRUE a simple matrix.

References

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.

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Generate model data
model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Obtain IR
ir <- irf(object, impulse = "invest", response = "cons")

# Plot IR
plot(ir)

Durbin and Koopman Simulation Smoother

Description

An implementation of the Kalman filter and backward smoothing algorithm proposed by Durbin and Koopman (2002).

Usage

kalman_dk(y, z, sigma_u, sigma_v, B, a_init, P_init)

Arguments

y

a K×TK \times T matrix of endogenous variables.

z

a KT×MKT \times M matrix of explanatory variables.

sigma_u

the constant K×KK \times K error variance-covariance matrix. For time varying variance-covariance matrices a KT×KKT \times K can be specified.

sigma_v

the constant M×MM \times M coefficient variance-covariance matrix. For time varying variance-covariance matrices a MT×MMT \times M can be specified.

B

an M×MM \times M autocorrelation matrix of the transition equation.

a_init

an M-dimensional vector of initial states.

P_init

an M×MM \times M variance-covariance matrix of the initial states.

Details

The function uses algorithm 2 from Durbin and Koopman (2002) to produce a draw of the state vector ata_t for t=1,...,Tt = 1,...,T for a state space model with measurement equation

yt=Ztat+uty_t = Z_t a_t + u_t

and transition equation

at+1=Btat+vt,a_{t + 1} = B_t a_{t} + v_t,

where utN(0,Σu,t)u_t \sim N(0, \Sigma_{u,t}) and vtN(0,Σv,t)v_t \sim N(0, \Sigma_{v,t}). yty_t is a K-dimensional vector of endogenous variables and Zt=ztIKZ_t = z_t^{\prime} \otimes I_K is a K×MK \times M matrix of regressors with ztz_t 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.

Value

A M×T+1M \times T+1 matrix of state vector draws.

References

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

Examples

# Load data
data("e1")
data <- diff(log(e1))

# Generate model data
temp <- gen_var(data, p = 2, deterministic = "const")
y <- t(temp$data$Y)
z <- temp$data$SUR
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_dk(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)

Calculates the log-likelihood of a multivariate normal distribution.

Description

Calculates the log-likelihood of a multivariate normal distribution.

Usage

loglik_normal(u, sigma)

Arguments

u

a K×TK \times T matrix of residuals.

sigma

a K×KK \times K or KT×KKT \times K variance-covariance matrix.

Details

The log-likelihood is calculated for each vector in period tt as

K2ln2π12lnΣt12utΣt1ut-\frac{K}{2} \ln 2\pi - \frac{1}{2} \ln |\Sigma_t| -\frac{1}{2} u_t^\prime \Sigma_t^{-1} u_t

, where ut=ytμtu_t = y_t - \mu_t.

Examples

# Load data
data("e1")
e1 <- diff(log(e1))

# Generate VAR model
data <- gen_var(e1, p = 2, deterministic = "const")
y <- t(data$data$Y)
x <- t(data$data$Z)

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

Minnesota Prior

Description

Calculates the Minnesota prior for a VAR model.

Usage

minnesota_prior(
  object,
  kappa0 = 2,
  kappa1 = 0.5,
  kappa2 = NULL,
  kappa3 = 5,
  max_var = NULL,
  coint_var = FALSE,
  sigma = "AR"
)

Arguments

object

an object of class "bvarmodel", usually, a result of a call to gen_var or gen_vec.

kappa0

a numeric specifying the prior variance of coefficients that correspond to own lags of endogenous variables.

kappa1

a numeric specifying the size of the prior variance of endogenous variables, which do not correspond to own lags, relative to argument kappa0.

kappa2

a numeric specifying the size of the prior variance of non-deterministic exogenous variables relative to argument kappa0. Default is NULL, which indicates that the formula for the calculation of the prior variance of deterministic terms is used for all exogenous variables.

kappa3

a numeric specifying the size of the prior variance of deterministic terms relative to argument kappa0.

max_var

a positive numeric specifying the maximum prior variance that is allowed for coefficients of non-deterministic variables. If NULL (default), the prior variances are not limited.

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 "AR" (default) or "VAR" indicating that the variances of the endogenous variables σ2\sigma^2 are calculated based on a univariate AR regression or a least squares estimate of the VAR form, respectively. In both cases all deterministic variables are used in the regressions, if they appear in the model.

Details

The function calculates the Minnesota prior of a VAR model. For the endogenous variable ii the prior variance of the llth lag of regressor jj is obtained as

κ0l2 for own lags of endogenous variables,\frac{\kappa_{0}}{l^2} \textrm{ for own lags of endogenous variables,}

κ0κ1l2σi2σj2 for endogenous variables other than own lags,\frac{\kappa_{0} \kappa_{1}}{l^2} \frac{\sigma_{i}^2}{\sigma_{j}^2} \textrm{ for endogenous variables other than own lags,}

κ0κ2(l+1)2σi2σj2 for exogenous variables,\frac{\kappa_{0} \kappa_{2}}{(l + 1)^2} \frac{\sigma_{i}^2}{\sigma_{j}^2} \textrm{ for exogenous variables,}

κ0κ3σi2 for deterministic terms,\kappa_{0} \kappa_{3} \sigma_{i}^2 \textrm{ for deterministic terms,}

where σi\sigma_{i} is the residual standard deviation of variable ii of an unrestricted LS estimate. For exogenous variables σi\sigma_{i} is the sample standard deviation.

For VEC models the function only provides priors for the non-cointegration part of the model. The residual standard errors σi\sigma_i are based on an unrestricted LS regression of the endogenous variables on the error correction term and the non-cointegration regressors.

Value

A list containing a matrix of prior means and the precision matrix of the cofficients and the inverse variance-covariance matrix of the error term, which was obtained by an LS estimation.

References

Chan, J., Koop, G., Poirier, D. J., & Tobias, J. L. (2020). Bayesian Econometric Methods (2nd ed.). Cambridge: University Press.

Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.

Examples

# Load data
data("e1")
data <- diff(log(e1))

# Generate model input
object <- gen_var(data)

# Obtain Minnesota prior
prior <- minnesota_prior(object)

Plotting Posterior Draws of Bayesian VAR or VEC Models

Description

A plot function for objects of class "bvarlist".

Usage

## S3 method for class 'bvarlist'
plot(x, ci = 0.95, type = "hist", model = NULL, ...)

Arguments

x

an object of class "bvarlist", usually, a result of a call to draw_posterior.

ci

interval used to calculate credible bands for time-varying parameters.

type

either "hist" (default) for histograms, "trace" for a trace plot, or "boxplot" for a boxplot. Only used for parameter draws of constant coefficients.

model

numeric or integer indicating for which models in argument "x" plots should be produced.

...

further graphical parameters.


Plotting Forecasts of BVAR Models

Description

A plot function for objects of class "bvarprd".

Usage

## S3 method for class 'bvarprd'
plot(x, n.pre = NULL, ...)

Arguments

x

an object of class "bvarprd", usually, a result of a call to predict.bvar.

n.pre

number of plotted observations that precede the forecasts. If NULL (default), all available obervations will be plotted.

...

further graphical parameters.

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Generate model data
model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)

# Add prior specifications
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Calculate forecasts
pred <- predict(object, new_d = rep(1, 10))

# Plot forecasts
plot(pred)

Posterior Draw for Cointegration Models

Description

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.

Usage

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
)

Arguments

y

a K×TK \times T matrix of differenced endogenous variables.

beta

a M×rM \times r cointegration matrix β\beta.

w

a M×TM \times T matrix of variables in the cointegration term.

sigma_i

an inverse of the K×KK \times K variance-covariance matrix.

v_i

a numeric between 0 and 1 specifying the shrinkage of the cointegration space prior.

p_tau_i

an inverted M×MM \times M matrix specifying the central location of the cointegration space prior of sp(β)sp(\beta).

g_i

a K×KK \times K matrix.

x

a N×TN \times T matrix of differenced regressors and unrestricted deterministic terms.

gamma_mu_prior

a KN×1KN \times 1 prior mean vector of non-cointegration coefficients.

gamma_v_i_prior

an inverted KN×KNKN \times KN prior covariance matrix of non-cointegration coefficients.

Details

The function produces posterior draws of the coefficient matrices α\alpha, β\beta and Γ\Gamma for the model

yt=αβwt1+Γzt+ut,y_{t} = \alpha \beta^{\prime} w_{t-1} + \Gamma z_{t} + u_{t},

where yty_{t} is a K-dimensional vector of differenced endogenous variables. wtw_{t} is an M×1M \times 1 vector of variables in the cointegration term, which include lagged values of endogenous and exogenous variables in levels and restricted deterministic terms. ztz_{t} is an N-dimensional vector of differenced endogenous and exogenous explanatory variabes as well as unrestricted deterministic terms. The error term is utΣu_t \sim \Sigma.

Draws of the loading matrix α\alpha are obtained using the prior on the cointegration space as proposed in Koop et al. (2010). The posterior covariance matrix is

Vα=[(v1(βPτ1β)G1)+(ZZΣ1)]1\overline{V}_{\alpha} = \left[\left(v^{-1} (\beta^{\prime} P_{\tau}^{-1} \beta) \otimes G_{-1}\right) + \left(ZZ^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}

and the posterior mean by

α=Vα+vec(Σ1YZ),\overline{\alpha} = \overline{V}_{\alpha} + vec(\Sigma^{-1} Y Z^{\prime}),

where YY is a K×TK \times T matrix of differenced endogenous variables and Z=βWZ = \beta^{\prime} W with WW as an M×TM \times T matrix of variables in the cointegration term.

For a given prior mean vector Γ\underline{\Gamma} and prior covariance matrix VΓ\underline{V_{\Gamma}} the posterior covariance matrix of non-cointegration coefficients in Γ\Gamma is obtained by

VΓ=[VΓ1+(XXΣ1)]1\overline{V}_{\Gamma} = \left[ \underline{V}_{\Gamma}^{-1} + \left(X X^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}

and the posterior mean by

Γ=VΓ[VΓ1Γ+vec(Σ1YX)],\overline{\Gamma} = \overline{V}_{\Gamma} \left[ \underline{V}_{\Gamma}^{-1} \underline{\Gamma} + vec(\Sigma^{-1} Y X^{\prime}) \right],

where XX is an M×TM \times T matrix of explanatory variables, which do not enter the cointegration term.

Draws of the cointegration matrix β\beta 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 BB is

VB=[(AG1Av1Pτ1)+(AΣ1AWW)]1\overline{V}_{B} = \left[\left(A^{\prime} G^{-1} A \otimes v^{-1} P_{\tau}^{-1} \right) + \left(A^{\prime} \Sigma^{-1} A \otimes WW^{\prime} \right) \right]^{-1}

and the posterior mean by

B=VB+vec(WYB1Σ1A),\overline{B} = \overline{V}_{B} + vec(W Y_{B}^{-1} \Sigma^{-1} A),

where YB=YΓXY_{B} = Y - \Gamma X and A=α(αα)12A = \alpha (\alpha^{\prime} \alpha)^{-\frac{1}{2}}.

The final draws of α\alpha and β\beta are calculated using β=B(BB)12\beta = B (B^{\prime} B)^{-\frac{1}{2}} and α=A(BB)12\alpha = A (B^{\prime} B)^{\frac{1}{2}}.

Value

A named list containing the following elements:

alpha

a draw of the K×rK \times r loading matrix.

beta

a draw of the M×rM \times r cointegration matrix.

Pi

a draw of the K×MK \times M cointegration matrix Π=αβ\Pi = \alpha \beta^{\prime}.

Gamma

a draw of the K×NK \times N coefficient matrix for non-cointegration parameters.

References

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

Examples

# Load data
data("e6")

# Generate model data
temp <- gen_vec(e6, p = 1, r = 1)
y <- t(temp$data$Y)
ect <- t(temp$data$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(y = y, beta = beta, w = ect, sigma_i = sigma_i,
                        v_i = 0, p_tau_i = diag(1, k), g_i = sigma_i)

Posterior Draw for Cointegration Models

Description

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.

Usage

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
)

Arguments

y

a K×TK \times T matrix of differenced endogenous variables.

beta

a M×rM \times r cointegration matrix β\beta, where ββ=I\beta^{\prime} \beta = I.

w

a M×TM \times T matrix of variables in the cointegration term.

sigma_i

the inverse of the constant K×KK \times K error variance-covariance matrix. For time varying variance-covariance matrics a KT×KKT \times K can be provided.

v_i

a numeric between 0 and 1 specifying the shrinkage of the cointegration space prior.

p_tau_i

an inverted M×MM \times M matrix specifying the central location of the cointegration space prior of sp(β)sp(\beta).

g_i

a K×KK \times K or KT×KKT \times K matrix. If the matrix is KT×KKT \times K, the function will automatically produce a K×KK \times K matrix containing the means of the time varying K×KK \times K covariance matrix.

x

a KT×NKKT \times NK matrix of differenced regressors and unrestricted deterministic terms.

gamma_mu_prior

a KN×1KN \times 1 prior mean vector of non-cointegration coefficients.

gamma_v_i_prior

an inverted KN×KNKN \times KN prior covariance matrix of non-cointegration coefficients.

svd

logical. If TRUE the singular value decomposition is used to determine the root of the posterior covariance matrix. Default is FALSE which means that the eigenvalue decomposition is used.

Details

The function produces posterior draws of the coefficient matrices α\alpha, β\beta and Γ\Gamma for the model

yt=αβwt1+Γzt+ut,y_{t} = \alpha \beta^{\prime} w_{t-1} + \Gamma z_{t} + u_{t},

where yty_{t} is a K-dimensional vector of differenced endogenous variables. wtw_{t} is an M×1M \times 1 vector of variables in the cointegration term, which include lagged values of endogenous and exogenous variables in levels and restricted deterministic terms. ztz_{t} is an N-dimensional vector of differenced endogenous and exogenous explanatory variabes as well as unrestricted deterministic terms. The error term is utΣu_t \sim \Sigma.

Draws of the loading matrix α\alpha are obtained using the prior on the cointegration space as proposed in Koop et al. (2010). The posterior covariance matrix is

Vα=[(v1(βPτ1β)G1)+(ZZΣ1)]1\overline{V}_{\alpha} = \left[\left(v^{-1} (\beta^{\prime} P_{\tau}^{-1} \beta) \otimes G_{-1}\right) + \left(ZZ^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}

and the posterior mean by

α=Vα+vec(Σ1YZ),\overline{\alpha} = \overline{V}_{\alpha} + vec(\Sigma^{-1} Y Z^{\prime}),

where YY is a K×TK \times T matrix of differenced endogenous variables and Z=βWZ = \beta^{\prime} W with WW as an M×TM \times T matrix of variables in the cointegration term.

For a given prior mean vector Γ\underline{\Gamma} and prior covariance matrix VΓ\underline{V_{\Gamma}} the posterior covariance matrix of non-cointegration coefficients in Γ\Gamma is obtained by

VΓ=[VΓ1+(XXΣ1)]1\overline{V}_{\Gamma} = \left[ \underline{V}_{\Gamma}^{-1} + \left(X X^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}

and the posterior mean by

Γ=VΓ[VΓ1Γ+vec(Σ1YX)],\overline{\Gamma} = \overline{V}_{\Gamma} \left[ \underline{V}_{\Gamma}^{-1} \underline{\Gamma} + vec(\Sigma^{-1} Y X^{\prime}) \right],

where XX is an M×TM \times T matrix of explanatory variables, which do not enter the cointegration term.

Draws of the cointegration matrix β\beta 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 BB is

VB=[(AG1Av1Pτ1)+(AΣ1AWW)]1\overline{V}_{B} = \left[\left(A^{\prime} G^{-1} A \otimes v^{-1} P_{\tau}^{-1} \right) + \left(A^{\prime} \Sigma^{-1} A \otimes WW^{\prime} \right) \right]^{-1}

and the posterior mean by

B=VB+vec(WYB1Σ1A),\overline{B} = \overline{V}_{B} + vec(W Y_{B}^{-1} \Sigma^{-1} A),

where YB=YΓXY_{B} = Y - \Gamma X and A=α(αα)12A = \alpha (\alpha^{\prime} \alpha)^{-\frac{1}{2}}.

The final draws of α\alpha and β\beta are calculated using β=B(BB)12\beta = B (B^{\prime} B)^{-\frac{1}{2}} and α=A(BB)12\alpha = A (B^{\prime} B)^{\frac{1}{2}}.

Value

A named list containing the following elements:

alpha

a draw of the K×rK \times r loading matrix.

beta

a draw of the M×rM \times r cointegration matrix.

Pi

a draw of the K×MK \times M cointegration matrix Π=αβ\Pi = \alpha \beta^{\prime}.

Gamma

a draw of the K×NK \times N coefficient matrix for non-cointegration parameters.

References

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

Examples

# Load data
data("e6")

# Generate model data
temp <- gen_vec(e6, p = 1, r = 1)
y <- t(temp$data$Y)
ect <- t(temp$data$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)

Posterior Draw from a Normal Distribution

Description

Produces a draw of coefficients from a normal posterior density.

Usage

post_normal(y, x, sigma_i, a_prior, v_i_prior)

Arguments

y

a K×TK \times T matrix of endogenous variables.

x

an M×TM \times T matrix of explanatory variables.

sigma_i

the inverse of the K×KK \times K variance-covariance matrix.

a_prior

a KM×1KM \times 1 numeric vector of prior means.

v_i_prior

the inverse of the KM×KMKM \times KM prior covariance matrix.

Details

The function produces a vectorised posterior draw aa of the K×MK \times M coefficient matrix AA for the model

yt=Axt+ut,y_{t} = A x_{t} + u_{t},

where yty_{t} is a K-dimensional vector of endogenous variables, xtx_{t} is an M-dimensional vector of explanatory variabes and the error term is utΣu_t \sim \Sigma.

For a given prior mean vector a\underline{a} and prior covariance matrix V\underline{V} the posterior covariance matrix is obtained by

V=[V1+(XXΣ1)]1\overline{V} = \left[ \underline{V}^{-1} + \left(X X^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}

and the posterior mean by

a=V[V1a+vec(Σ1YX)],\overline{a} = \overline{V} \left[ \underline{V}^{-1} \underline{a} + vec(\Sigma^{-1} Y X^{\prime}) \right],

where YY is a K×TK \times T matrix of the endogenous variables and XX is an M×TM \times T matrix of the explanatory variables.

Value

A vector.

References

Lütkepohl, H. (2006). New introduction to multiple time series analysis (2nd ed.). Berlin: Springer.

Examples

# Load data
data("e1")
data <- diff(log(e1))

# Generate model data
temp <- gen_var(data, p = 2, deterministic = "const")
y <- t(temp$data$Y)
x <- t(temp$data$Z)
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)

Posterior Simulation of Error Covariance Coefficients

Description

Produces posterior draws of constant error covariance coefficients.

Usage

post_normal_covar_const(y, u_omega_i, prior_mean, prior_covariance_i)

Arguments

y

a K×TK \times T matrix of data with KK as the number of endogenous variables and TT the number of observations.

u_omega_i

matrix of error variances of the measurement equation. Either a K×KK \times K matrix for constant variances or a KT×KTKT \times KT matrix for time varying variances.

prior_mean

vector of prior means. In case of TVP, this vector is used as initial condition.

prior_covariance_i

inverse prior covariance matrix. In case of TVP, this matrix is used as initial condition.

Details

For the multivariate model A0yt=utA_0 y_t = u_t with utN(0,Ωt)u_t \sim N(0, \Omega_t) the function produces a draw of the lower triangular part of A0A_0 similar as in Primiceri (2005), i.e., using

yt=Ztψ+ut,y_t = Z_t \psi + u_t,

where

Zt=[00y1,t000y[1,2],t000y[1,...,K1],t]Z_{t} = \begin{bmatrix} 0 & \dotsm & \dotsm & 0 \\ -y_{1, t} & 0 & \dotsm & 0 \\ 0 & -y_{[1,2], t} & \ddots & \vdots \\ \vdots & \ddots & \ddots & 0 \\ 0 & \dotsm & 0 & -y_{[1,...,K-1], t} \end{bmatrix}

and y[1,...,K1],ty_{[1,...,K-1], t} denotes the first to (K1)(K-1)th elements of the vector yty_t.

Value

A matrix.

References

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

Examples

# Load example data
data("e1")
y <- log(t(e1))

# Generate artificial draws of other matrices
u_omega_i <- diag(1, 3)
prior_mean <- matrix(0, 3)
prior_covariance_i <- diag(0, 3)

# Obtain posterior draw
post_normal_covar_const(y, u_omega_i, prior_mean, prior_covariance_i)

Posterior Simulation of Error Covariance Coefficients

Description

Produces posterior draws of time varying error covariance coefficients.

Usage

post_normal_covar_tvp(y, u_omega_i, v_sigma_i, psi_init)

Arguments

y

a K×TK \times T matrix of data with KK as the number of endogenous variables and TT the number of observations.

u_omega_i

matrix of error variances of the measurement equation. Either a K×KK \times K matrix for constant variances or a KT×KTKT \times KT matrix for time varying variances.

v_sigma_i

matrix of error variances of the state equation. Either an M×MM \times M matrix for constant variances or an MT×MTMT \times MT matrix for time varying variances, where MM is the number of estimated variables.

psi_init

a vector of inital values of the state equation.

Details

For the multivariate model A0,tyt=utA_{0,t} y_t = u_t with utN(0,Ωt)u_t \sim N(0, \Omega_t) the function produces a draw of the lower triangular part of A0,tA_{0,t} similar as in Primiceri (2005), i.e., using

yt=Ztψt+ut,y_t = Z_t \psi_t + u_t,

where

Zt=[00y1,t000y[1,2],t000y[1,...,K1],t]Z_{t} = \begin{bmatrix} 0 & \dotsm & \dotsm & 0 \\ -y_{1, t} & 0 & \dotsm & 0 \\ 0 & -y_{[1,2], t} & \ddots & \vdots \\ \vdots & \ddots & \ddots & 0 \\ 0 & \dotsm & 0 & -y_{[1,...,K-1], t} \end{bmatrix}

and y[1,...,K1],ty_{[1,...,K-1], t} denotes the first to (K1)(K-1)th elements of the vector yty_t.

The algorithm of Chan and Jeliazkov (2009) is used to obtain time varying coefficients.

Value

A matrix.

References

Chan, J., & Jeliazkov, I. (2009). Efficient simulation and integrated likelihood estimation in state space models. International Journal of Mathematical Modelling and Numerical Optimisation, 1(1/2), 101–120. doi:10.1504/IJMMNO.2009.030090

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

Examples

# Load example data
data("e1")
y <- log(t(e1))

# Generate artificial draws of other matrices
u_omega_i <- diag(1, 3)
v_sigma_i <- diag(1000, 3)
psi_init <- matrix(0, 3)

# Obtain posterior draw
post_normal_covar_tvp(y, u_omega_i, v_sigma_i, psi_init)

Posterior Draw from a Normal Distribution

Description

Produces a draw of coefficients from a normal posterior density for a model with seemingly unrelated regresssions (SUR).

Usage

post_normal_sur(y, z, sigma_i, a_prior, v_i_prior, svd = FALSE)

Arguments

y

a K×TK \times T matrix of endogenous variables.

z

a KT×MKT \times M matrix of explanatory variables.

sigma_i

the inverse of the constant K×KK \times K error variance-covariance matrix. For time varying variance-covariance matrics a KT×KKT \times K can be provided.

a_prior

a Mx1M x 1 numeric vector of prior means.

v_i_prior

the inverse of the MxMM x M prior covariance matrix.

svd

logical. If TRUE the singular value decomposition is used to determine the root of the posterior covariance matrix. Default is FALSE which means that the eigenvalue decomposition is used.

Details

The function produces a posterior draw of the coefficient vector aa for the model

yt=Zta+ut,y_{t} = Z_{t} a + u_{t},

where utN(0,Σt)u_t \sim N(0, \Sigma_{t}). yty_t is a K-dimensional vector of endogenous variables and Zt=ztIKZ_t = z_t^{\prime} \otimes I_K is a K×KMK \times KM matrix of regressors with ztz_t as a vector of regressors.

For a given prior mean vector a\underline{a} and prior covariance matrix V\underline{V} the posterior covariance matrix is obtained by

V=[V1+t=1TZtΣt1Zt]1\overline{V} = \left[ \underline{V}^{-1} + \sum_{t=1}^{T} Z_{t}^{\prime} \Sigma_{t}^{-1} Z_{t} \right]^{-1}

and the posterior mean by

a=V[V1a+t=1TZtΣt1yt].\overline{a} = \overline{V} \left[ \underline{V}^{-1} \underline{a} + \sum_{t=1}^{T} Z_{t}^{\prime} \Sigma_{t}^{-1} y_{t} \right].

Value

A vector.

Examples

# Load data
data("e1")
data <- diff(log(e1))

# Generate model data
temp <- gen_var(data, p = 2, deterministic = "const")
y <- t(temp$data$Y)
z <- temp$data$SUR
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)

Stochastic Search Variable Selection

Description

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.

Usage

ssvs(a, tau0, tau1, prob_prior, include = NULL)

Arguments

a

an M-dimensional vector of coefficient draws.

tau0

an M-dimensional vector of prior standard deviations for restricted coefficients in vector a.

tau1

an M-dimensional vector of prior standard deviations for unrestricted coefficients in vector a.

prob_prior

an M-dimensional vector of prior inclusion probabilites for the coefficients in vector a.

include

an integer vector specifying the positions of coefficients in vector a, which should be included in the SSVS algorithm. If NULL (default), SSVS will be applied to all coefficients.

Details

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 V1\underline{V}^{-1} and the corresponding vector of inclusion parameters λ\lambda of the vectorised coefficient matrix a=vec(A)a = vec(A) for the VAR model

yt=Axt+ut,y_t = A x_t + u_t,

where yty_{t} is a K-dimensional vector of endogenous variables, xtx_{t} is a vector of explanatory variabes and the error term is utΣu_t \sim \Sigma.

Value

A named list containing two components:

v_i

an M×MM \times M inverse prior covariance matrix.

lambda

an M-dimensional vector of inclusion parameters.

References

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

Examples

# Load data
data("e1")
data <- diff(log(e1))

# Generate model data
temp <- gen_var(data, p = 2, deterministic = "const")
y <- t(temp$data$Y)
x <- t(temp$data$Z)
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)

Stochastic Search Variable Selection Prior

Description

Calculates the priors for a Bayesian VAR model, which employs stochastic search variable selection (SSVS).

Usage

ssvs_prior(object, tau = c(0.05, 10), semiautomatic = NULL)

Arguments

object

an object of class "bvarmodel", usually, a result of a call to gen_var or gen_vec.

tau

a numeric vector of two elements containing the prior standard errors of restricted variables (τ0\tau_0) as its first element and unrestricted variables (τ1\tau_1) as its second. Default is c(0.05, 10).

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 (τ0\tau_0) and unrestricted (τ1\tau_1) variables. This is the semiautomatic approach described in George et al. (2008).

Value

A list containing the vectors of prior standard deviations for restricted and unrestricted variables, respectively.

References

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

Examples

# Prepare data
data("e1")
data <- diff(log(e1))

# Generate model input
object <- gen_var(data)

# Obtain SSVS prior
prior <- ssvs_prior(object, semiautomatic = c(.1, 10))

Stochastic Volatility

Description

Produces a draw of log-volatilities.

Usage

stoch_vol(y, h, sigma, h_init, constant)

Arguments

y

a T×1T \times 1 vector containing the time series.

h

a T×1T \times 1 vector of log-volatilities.

sigma

a numeric of the variance of the log-volatilites.

h_init

a numeric of the initial state of log-volatilities.

constant

a numeric of the constant that should be added to y2y^2 before taking the natural logarithm.

Details

The function is a wrapper for function stochvol_ksc1998.

Value

A vector of log-volatility draws.

References

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

Examples

data("us_macrodata")
y <- matrix(us_macrodata[, "r"])

# Initialise log-volatilites
h_init <- matrix(log(var(y)))
h <- matrix(rep(h_init, length(y)))

# Obtain draw
stoch_vol(y - mean(y), h, matrix(.05), h_init, matrix(0.0001))

Stochastic Volatility

Description

Produces a draw of log-volatilities.

Usage

stochvol_ksc1998(y, h, sigma, h_init, constant)

Arguments

y

a T×KT \times K matrix containing the time series.

h

a T×KT \times K vector of the current draw of log-volatilities.

sigma

a K×1K \times 1 vector of variances of log-volatilities, where the iith element corresponds to the iith column in y.

h_init

a K×1K \times 1 vector of the initial states of log-volatilities, where the iith element corresponds to the iith column in y.

constant

a K×1K \times 1 vector of constants that should be added to y2y^2 before taking the natural logarithm. The iith element corresponds to the iith column in y. See 'Details'.

Details

For each column in y the function produces a posterior draw of the log-volatility hh for the model

yt=e12htϵt,y_{t} = e^{\frac{1}{2}h_t} \epsilon_{t},

where ϵtN(0,1)\epsilon_t \sim N(0, 1) and hth_t is assumed to evolve according to a random walk

ht=ht1+ut,h_t = h_{t - 1} + u_t,

with utN(0,σ2)u_t \sim N(0, \sigma^2).

The implementation is based on the algorithm of Kim, Shephard and Chip (1998) and performs the following steps:

  1. Perform the transformation yt=ln(yt2+constant)y_t^* = ln(y_t^2 + constant).

  2. Obtain a sample from the seven-component normal mixture for approximating the log-χ12\chi_1^2 distribution.

  3. Obtain a draw of log-volatilities.

The implementation follows the code provided on the website to the textbook by Chan, Koop, Poirier, and Tobias (2019).

Value

A vector of log-volatility draws.

References

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

Examples

data("us_macrodata")
y <- matrix(us_macrodata[, "r"])

# Initialise log-volatilites
h_init <- matrix(log(var(y)))
h <- matrix(rep(h_init, length(y)))

# Obtain draw
stochvol_ksc1998(y - mean(y), h, matrix(.05), h_init, matrix(0.0001))

Stochastic Volatility

Description

Produces a draw of log-volatilities based on Omori, Chib, Shephard and Nakajima (2007).

Usage

stochvol_ocsn2007(y, h, sigma, h_init, constant)

Arguments

y

a T×KT \times K matrix containing the time series.

h

a T×KT \times K vector of the current draw of log-volatilities.

sigma

a K×1K \times 1 vector of variances of log-volatilities, where the iith element corresponds to the iith column in y.

h_init

a K×1K \times 1 vector of the initial states of log-volatilities, where the iith element corresponds to the iith column in y.

constant

a K×1K \times 1 vector of constants that should be added to y2y^2 before taking the natural logarithm. The iith element corresponds to the iith column in y. See 'Details'.

Details

For each column in y the function produces a posterior draw of the log-volatility hh for the model

yt=e12htϵt,y_{t} = e^{\frac{1}{2}h_t} \epsilon_{t},

where ϵtN(0,1)\epsilon_t \sim N(0, 1) and hth_t is assumed to evolve according to a random walk

ht=ht1+ut,h_t = h_{t - 1} + u_t,

with utN(0,σ2)u_t \sim N(0, \sigma^2).

The implementation follows the algorithm of Omori, Chib, Shephard and Nakajima (2007) and performs the following steps:

  1. Perform the transformation yt=ln(yt2+constant)y_t^* = ln(y_t^2 + constant).

  2. Obtain a sample from the ten-component normal mixture for approximating the log-χ12\chi_1^2 distribution.

  3. Obtain a draw of log-volatilities.

The implementation is an adaption of the code provided on the website to the textbook by Chan, Koop, Poirier, and Tobias (2019).

Value

A vector of log-volatility draws.

References

Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.

Omori, Y., Chib, S., Shephard, N., & Nakajima, J. (2007). Stochastic volatiltiy with leverage. Fast and efficient likelihood inference. Journal of Econometrics 140(2), 425–449. doi:10.1016/j.jeconom.2006.07.008

Examples

data("us_macrodata")
y <- matrix(us_macrodata[, "r"])

# Initialise log-volatilites
h_init <- matrix(log(var(y)))
h <- matrix(rep(h_init, length(y)))

# Obtain draw
stochvol_ocsn2007(y - mean(y), h, matrix(.05), h_init, matrix(0.0001))

Summarising Bayesian VAR Coefficients

Description

summary method for class "bvar".

Usage

## S3 method for class 'bvar'
summary(object, ci = 0.95, period = NULL, ...)

## S3 method for class 'summary.bvar'
print(x, digits = max(3L, getOption("digits") - 3L), ...)

Arguments

object

an object of class "bvar", usually, a result of a call to bvar or bvec_to_bvar.

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 NULL, so that the posterior draws of the last time period are used.

...

further arguments passed to or from other methods.

x

an object of class "summary.bvar", usually, a result of a call to summary.bvar.

digits

the number of significant digits to use when printing.

Value

summary.bvar returns a list of class "summary.bvar", 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.


Summarising Bayesian VAR or VEC Models

Description

summary method for class "bvarlist".

Usage

## S3 method for class 'bvarlist'
summary(object, ...)

Arguments

object

an object of class "bvar", usually, a result of a call to draw_posterior.

...

further arguments passed to or from other methods.

Details

The log-likelihood for the calculation of the information criteria is obtained by

LL=1Ri=1R(t=1TK2ln2π12lnΣt(i)12(ut(i)(Σt(i))1ut(i))LL = \frac{1}{R} \sum_{i = 1}^{R} \left( \sum_{t = 1}^{T} -\frac{K}{2} \ln 2\pi - \frac{1}{2} \ln |\Sigma_t^{(i)}| -\frac{1}{2} (u_t^{{(i)}\prime} (\Sigma_t^{(i)})^{-1} u_t^{(i)} \right)

, where ut=ytμtu_t = y_t - \mu_t. The Akaike, Bayesian and Hannan–Quinn (HQ) information criteria are calculated as

AIC=2(Kp+Ms+N)2LLAIC = 2 (Kp + Ms + N) - 2 LL

,

BIC=(Kp+Ms+N)ln(T)2LLBIC = (Kp + Ms + N) ln(T) - 2 LL

and

HQ=2(Kp+Ms+N)ln(ln(T))2LLHQ = 2 (Kp + Ms + N) ln(ln(T)) - 2 LL

, respectively, where KK is the number of endogenous variables, pp the number of lags of endogenous variables, MM the number of exogenous variables, ss the number of lags of exogenous variables, NN the number of deterministic terms and TT the number of observations.

Value

summary.bvarlist returns a table of class "summary.bvarlist".


Summarising Bayesian VEC Coefficients

Description

summary method for class "bvec".

Usage

## S3 method for class 'bvec'
summary(object, ci = 0.95, period = NULL, ...)

## S3 method for class 'summary.bvec'
print(x, digits = max(3L, getOption("digits") - 3L), ...)

Arguments

object

an object of class "bvec", usually, a result of a call to bvec.

ci

a numeric between 0 and 1 specifying the probability of the credible band. Defaults to 0.95.

period

integer. Index of the period of a TVP VEC, for which a summary should be generated. Only used for TVP models. Default is NULL so that only the most recent time period is used.

...

further arguments passed to or from other methods.

x

an object of class "summary.bvec", usually, a result of a call to summary.bvec.

digits

the number of significant digits to use when printing.

Value

summary.bvec returns a list of class "summary.bvec", 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.


Summarising Bayesian Dynamic Factor Models

Description

summary method for class "dfm".

Usage

## S3 method for class 'dfm'
summary(object, ci = 0.95, ...)

Arguments

object

an object of class "dfm", usually, a result of a call to dfm.

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.

Value

summary.dfm returns a list of class "summary.dfm", which contains the following components:

lambda

A list of various summary statistics of the posterior draws of the factor loadings.

factor

A list of various summary statistics of the posterior draws of the factors.

sigma_u

A list of various summary statistics of the posterior draws of the variance matrix of the measurement equation.

a

A list of various summary statistics of the posterior draws of the factor loadings.

sigma_v

A list of various summary statistics of the posterior draws of the variance matrix of the transition equation.

specifications

a list containing information on the model specification.


Thinning Posterior Draws

Description

Thins the MCMC posterior draws in an object of class "bvar".

Usage

## S3 method for class 'bvar'
thin(x, thin = 10, ...)

Arguments

x

an object of class "bvar".

thin

an integer specifying the thinning interval between successive values of posterior draws.

...

further arguments passed to or from other methods.

Value

An object of class "bvar".

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Obtain data matrices
model <- gen_var(e1, p = 2, deterministic = 2,
                 iterations = 100, burnin = 10)
# Chosen number of iterations and burn-in draws should be much higher.

# Add prior specifications
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

object <- thin(object)

Thinning Posterior Draws

Description

Thins the MCMC posterior draws in an object of class "bvarlist".

Usage

## S3 method for class 'bvarlist'
thin(x, thin = 10, ...)

Arguments

x

an object of class "bvarlist".

thin

an integer specifying the thinning interval between successive values of posterior draws.

...

further arguments passed to or from other methods.

Value

An object of class "bvarlist".

Examples

# Load data
data("e1")
e1 <- diff(log(e1)) * 100

# Generate multiple model matrices
model <- gen_var(e1, p = 1:2, deterministic = 2,
                 iterations = 100, burnin = 10)

# Add prior specifications
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Thin
object <- thin(object)

Thinning Posterior Draws

Description

Thins the MCMC posterior draws in an object of class "bvec".

Usage

## S3 method for class 'bvec'
thin(x, thin = 10, ...)

Arguments

x

an object of class "bvec".

thin

an integer specifying the thinning interval between successive values of posterior draws.

...

further arguments passed to or from other methods.

Value

An object of class "bvec".

Examples

# Load data
data("e6")

# Generate model data
model <- gen_vec(e6, p = 2, r = 1,
                 const = "unrestricted", seasonal = "unrestricted",
                 iterations = 100, burnin = 10)

# Add prior specifications
model <- add_priors(model)

# Obtain posterior draws
object <- draw_posterior(model)

# Thin
object <- thin(object)

Thinning Posterior Draws

Description

Thins the MCMC posterior draws in an object of class "dfm".

Usage

## S3 method for class 'dfm'
thin(x, thin = 10, ...)

Arguments

x

an object of class "dfm".

thin

an integer specifying the thinning interval between successive values of posterior draws.

...

further arguments passed to or from other methods.

Value

An object of class "dfm".

Examples

# Load data
data("bem_dfmdata")

# Generate model data
model <- gen_dfm(x = bem_dfmdata, p = 1, n = 1,
                 iterations = 20, burnin = 10)
# Number of iterations and burnin should be much higher.

# Add prior specifications
model <- add_priors(model,
                    lambda = list(v_i = .01),
                    sigma_u = list(shape = 5, rate = 4),
                    a = list(v_i = .01),
                    sigma_v = list(shape = 5, rate = 4))

# Obtain posterior draws
object <- draw_posterior(model)

# Plot factors
object <- thin(object, thin = 2)

US macroeconomic data

Description

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.

Usage

data("us_macrodata")

Format

A named time-series object with 195 rows and 3 variables:

Dp

CPI inflation rate.

u

unemployment rate.

r

Fed Funds rate.

References

Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). Bayesian econometric methods (2nd ed.). Cambridge: Cambridge University Press.