bvartools

Functions for Bayesian inference of vector autoregressive and vector error correction models

https://github.com/franzmohr/bvartools

Science Score: 13.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
  • .zenodo.json file
  • DOI references
    Found 14 DOI reference(s) in README
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (11.7%) to scientific vocabulary

Keywords

bayesian bayesian-inference bayesian-var bvar bvecm gibbs-sampling mcmc r-package vector-autoregression vector-error-correction-model
Last synced: 6 months ago · JSON representation

Repository

Functions for Bayesian inference of vector autoregressive and vector error correction models

Basic Info
  • Host: GitHub
  • Owner: franzmohr
  • Language: R
  • Default Branch: master
  • Homepage:
  • Size: 31.1 MB
Statistics
  • Stars: 33
  • Watchers: 3
  • Forks: 11
  • Open Issues: 4
  • Releases: 0
Topics
bayesian bayesian-inference bayesian-var bvar bvecm gibbs-sampling mcmc r-package vector-autoregression vector-error-correction-model
Created over 7 years ago · Last pushed over 1 year ago
Metadata Files
Readme

README.Rmd

---
output:
  github_document:
    html_preview: false
---

# bvartools

[![CRAN status](https://www.r-pkg.org/badges/version/bvartools)](https://cran.r-project.org/package=bvartools)
[![R-CMD-check](https://github.com/franzmohr/bvartools/workflows/R-CMD-check/badge.svg)](https://github.com/franzmohr/bvartools/actions)

## Overview

The package `bvartools` implements functions for Bayesian inference of linear vector autoregressive (VAR) models. It separates a typical BVAR analysis workflow into multiple steps:

* *Model set-up*: Produces data matrices for given lag orders and model types, which can be used for posterior simulation.
* *Prior specification*: Generates prior matrices for a given model.
* *Estimation*: Researchers can choose to use the posterior algorithms of the package or use their own algorithms.
* *Standardising model output*: Combines the output of the estimation step into standardised objects for subsequent steps of the analyis.
* *Evaluation*: Produces summary statistics, forecasts, impulse responses and forecast error variance decompositions.

In each step researchers are provided with the opportunitiy to fine-tune a model according to their specific requirements or to use the default framework for commonly used models and priors. Since version 0.1.0 the package comes with posterior simulation functions that do not require to implement any further simulation algorithms. For Bayesian inference of *stationary VAR models* the package covers

* Standard BVAR models with independent normal-Wishart priors
* BVAR models employing stochastic search variable selection à la Gerorge, Sun and Ni (2008)
* BVAR models employing Bayesian variable selection à la Korobilis (2013)
* Structural BVAR models, where the structural coefficients are estimated from contemporary endogenous variables (A-model)
* Stochastic volatility (SV) of the errors à la Kim, Shephard and Chip (1998)
* Time varying parameter models (TVP-VAR)

For Bayesian inference of *cointegrated VAR models* the package implements the algorithm of Koop, León-González and Strachan (2010) [KLS] -- which places identification restrictions on the cointegration space -- in the following variants

* The BVEC model as presented in Koop, León-González and Strachan (2010)
* The KLS model employing stochastic search variable selection à la Gerorge, Sun and Ni (2008)
* The KLS modol employing Bayesian variable selection à la Korobilis (2013)
* Structural BVEC models, where the structural coefficients are estimated from contemporaneous endogenous variables (A-model). However, no further restrictions are made regarding the cointegration term.
* Stochastic volatility (SV) of the errors à la Kim, Shephard and Chip (1998)
* Time varying parameter models (TVP-VEC) à la Koop, León-González and Strachan (2011)[^tvpvec]

For Bayesian inference of *dynamic factor models* the package implements the althorithm used in the textbook of Chan, Koop, Poirer and Tobias (2019).

Similar packages worth checking out are

- [BVAR](https://cran.r-project.org/package=BVAR)
- [bvarsv](https://cran.r-project.org/package=bvarsv)
- [bvar](https://github.com/nk027/bvar)
- [bvarr](https://github.com/bdemeshev/bvarr)
- [bvars](https://github.com/joergrieger/bvars)
- [mfbvar](https://github.com/ankargren/mfbvar)
- [BMR](https://github.com/kthohr/BMR)

## Installation

```{r cran, include = TRUE, eval = FALSE}
install.packages("bvartools")
```

### Development version

```{r github, eval = FALSE}
# install.packages("devtools")
devtools::install_github("franzmohr/bvartools")
```

## Usage

This example covers the estimation of a simple Bayesian VAR (BVAR) model. For further examples on time varying parameter (TVP), stochastic volatility (SV), and vector error correction (VEC) models as well as shrinkage methods like stochastic search variable selection (SSVS) or Bayesian variable selection (BVS) see the vignettes of the package and [r-econometrics.com](https://www.r-econometrics.com/timeseriesintro/).

### Data

To illustrate the estimation process the dataset E1 from Lütkepohl (2006) is used. It contains data on West German fixed investment, disposable income and consumption expenditures in billions of DM from 1960Q1 to 1982Q4. Like in the textbook only the first 73 observations of the log-differenced series are used.

```{r data, fig.align='center', fig.height=5, fig.width=4.5}
library(bvartools)

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

# Reduce number of oberservations
e1 <- window(e1, end = c(1978, 4))

# Plot the series
plot(e1)
```

### Setting up a model

The `gen_var` function produces an object, which contains information on the specification of the VAR model that should be estimated. The following code specifies a VAR(2) model with an intercept term. The number of iterations and burn-in draws is already specified at this stage.

```{r}
model <- gen_var(e1, p = 2, deterministic = "const",
                 iterations = 5000, burnin = 1000)
```

Note that the function is also capable of generating more than one model. For example, specifying `p = 0:2` would result in three models.

### Adding model priors

Function `add_priors` produces priors for the specified model(s) in object `model` and augments the object accordingly.
  
```{r}
model_with_priors <- add_priors(model,
                                coef = list(v_i = 0, v_i_det = 0),
                                sigma = list(df = 1, scale = .0001))
```

If researchers want to fine-tune individual prior specifications, this can be done by directly accessing the respective elements in object `model_with_priors`.

### Estimation

The output of `add_priors` can be used as the input for user-written algorithms for posterior simulation. However, `bvartools` also comes with built-in posterior simulation functions, which can be directly applied to the output of the prior specification step by using function `draw_posterior`:

```{r, eval = FALSE}
bvar_est <- draw_posterior(model_with_priors)
```

The following code sets up a simple Gibbs sampler algorithm.

```{r usage, message = FALSE, eval = TRUE}
# Reset random number generator for reproducibility
set.seed(1234567)

iterations <- 10000 # Number of saved iterations of the Gibbs sampler
burnin <- 5000 # Number of burn-in draws
draws <- iterations + burnin # Total number of MCMC draws

y <- t(model_with_priors$data$Y)
x <- t(model_with_priors$data$Z)

tt <- ncol(y) # Number of observations
k <- nrow(y) # Number of endogenous variables
m <- k * nrow(x) # Number of estimated coefficients

# Set (uninformative) priors
a_mu_prior <- model_with_priors$priors$coefficients$mu # Vector of prior parameter means
a_v_i_prior <- model_with_priors$priors$coefficients$v_i # Inverse of the prior covariance matrix

u_sigma_df_prior <- model_with_priors$priors$sigma$df # Prior degrees of freedom
u_sigma_scale_prior <- model_with_priors$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)
  u_sigma <- solve(u_sigma_i) # Invert Sigma_i to obtain Sigma
  
  # Store draws
  if (draw > burnin) {
    draws_a[, draw - burnin] <- a
    draws_sigma[, draw - burnin] <- u_sigma
  }
}
```

### `bvar` objects

Function `bvar` can be used to collect relevant output of the Gibbs sampler in a standardised object, which can be used by further applications such as `predict` to obtain forecasts or `irf` for impulse respons analysis.

```{r bvars-object}
bvar_est <- bvar(y = model_with_priors$data$Y,
                 x = model_with_priors$data$Z,
                 A = draws_a[1:18,],
                 C = draws_a[19:21, ],
                 Sigma = draws_sigma)
```

Summary statistics can be obained in the usual manner:

```{r summary}
summary(bvar_est)
```

The means of the posterior draws are very close to the results of the frequentist estimatior in Lütkepohl (2006).

### Inspect posterior draws

Posterior draws can be visually inspected by using the `plot` function. By default, it produces a series of histograms of all estimated coefficients.

```{r, message=FALSE, warning=FALSE, fig.align='center', fig.height=5, fig.width=10}
plot(bvar_est)
```

Alternatively, the trace plot of the post-burnin draws can be draws by adding the argument `type = "trace"`:

```{r, message=FALSE, warning=FALSE, fig.align='center', fig.height=5, fig.width=10}
plot(bvar_est, type = "trace")
```

### Summary statistics

Summary statistics can be obtained in the usual way using the `summary` method.

```{r}
summary(bvar_est)
```

### Thin results

The MCMC series in object `est_bvar` can be thinned using

```{r}
bvar_est <- thin(bvar_est, thin = 10)
```


### Forecasts

Forecasts can be obtained with the function `predict`. If the model contains deterministic terms, new values have to be provided in the argument `new_D`, which must be of the same length as the argument `n.ahead`.

```{r forecasts, fig.width=5.5, fig.height=5.5}
bvar_pred <- predict(bvar_est, n.ahead = 5, new_D = rep(1, 5))

plot(bvar_pred)
```

### Impulse response analysis

#### Forecast error impulse response

```{r feir, fig.width=5.5, fig.height=4.5}
IR <- irf(bvar_est, impulse = "income", response = "cons", n.ahead = 8)

plot(IR, main = "Forecast Error Impulse Response", xlab = "Period", ylab = "Response")
```

#### Orthogonalised impulse response

```{r oir, fig.width=5.5, fig.height=4.5}
OIR <- irf(bvar_est, impulse = "income", response = "cons", n.ahead = 8, type = "oir")

plot(OIR, main = "Orthogonalised Impulse Response", xlab = "Period", ylab = "Response")
```

#### Generalised impulse response

```{r gir, fig.width=5.5, fig.height=4.5}
GIR <- irf(bvar_est, impulse = "income", response = "cons", n.ahead = 8, type = "gir")

plot(GIR, main = "Generalised Impulse Response", xlab = "Period", ylab = "Response")
```

### Forecast error variance decomposition

```{r fevd, fig.width=5.5, fig.height=4.5}
bvar_fevd <- fevd(bvar_est, response = "cons")

plot(bvar_fevd, main = "FEVD of consumption")
```

## References

Eddelbuettel, D., & Sanderson C. (2014). RcppArmadillo: Accelerating R with high-performance C++ linear algebra. *Computational Statistics and Data Analysis, 71*, 1054-1063. 

George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model restrictions. *Journal of Econometrics, 142*(1), 553-580. 

Kim, S., Shephard, N., & Chib, S. (1998). Stochastic volatility: Likelihood inference and comparison with ARCH models. *Review of Economic Studies 65*(3), 361-396.

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. 

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. 

Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. *Journal of Applied Econometrics, 28*(2), 204-230. 

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. 

Sanderson, C., & Curtin, R. (2016). Armadillo: a template-based C++ library for linear algebra. *Journal of Open Source Software, 1*(2), 26. 

[^cpp]: `RcppArmadillo` is the `Rcpp` bridge to the open source 'Armadillo' library of Sanderson and Curtin (2016).

[^tvpvec]: In contrast to Koop et al. (2011) version 0.2.1 assumes a fixed value for the autocorrelation coefficient of the time varying cointegration space. A step for drawing this coefficient will be introduced in a future release.

Owner

  • Name: Franz Mohr
  • Login: franzmohr
  • Kind: user
  • Location: Vienna
  • Company: Austrian Financial Market Authority

GitHub Events

Total
  • Issues event: 1
  • Watch event: 4
Last Year
  • Issues event: 1
  • Watch event: 4

Committers

Last synced: over 1 year ago

All Time
  • Total Commits: 311
  • Total Committers: 2
  • Avg Commits per committer: 155.5
  • Development Distribution Score (DDS): 0.016
Past Year
  • Commits: 21
  • Committers: 1
  • Avg Commits per committer: 21.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Franz X. Mohr f****r@o****m 306
mohr f****r@f****t 5
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 8
  • Total pull requests: 0
  • Average time to close issues: 8 months
  • Average time to close pull requests: N/A
  • Total issue authors: 8
  • Total pull request authors: 0
  • Average comments per issue: 1.63
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 2
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 2
  • Pull request authors: 0
  • Average comments per issue: 0.0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • wenqiu24 (1)
  • dlalounta (1)
  • vestedinterests (1)
  • dcuoliveira (1)
  • simeonwilson (1)
  • franzmohr (1)
  • Rosavanderdrift (1)
  • RightHandOfDoom (1)
Pull Request Authors
Top Labels
Issue Labels
Pull Request Labels

Packages

  • Total packages: 1
  • Total downloads:
    • cran 655 last-month
  • Total docker downloads: 42,005
  • Total dependent packages: 1
  • Total dependent repositories: 1
  • Total versions: 9
  • Total maintainers: 1
cran.r-project.org: bvartools

Bayesian Inference of Vector Autoregressive and Error Correction Models

  • Versions: 9
  • Dependent Packages: 1
  • Dependent Repositories: 1
  • Downloads: 655 Last month
  • Docker Downloads: 42,005
Rankings
Docker downloads count: 0.6%
Forks count: 5.5%
Stargazers count: 10.6%
Average: 12.6%
Downloads: 17.0%
Dependent packages count: 18.2%
Dependent repos count: 24.0%
Maintainers (1)
Last synced: 6 months ago

Dependencies

.github/workflows/R-CMD-check.yaml actions
  • actions/checkout v3 composite
  • r-lib/actions/check-r-package v2 composite
  • r-lib/actions/setup-pandoc v2 composite
  • r-lib/actions/setup-r v2 composite
  • r-lib/actions/setup-r-dependencies v2 composite