Code Monkey home page Code Monkey logo

nk027 / bvar Goto Github PK

View Code? Open in Web Editor NEW
47.0 5.0 19.0 5.53 MB

Toolkit for the estimation of hierarchical Bayesian vector autoregressions. Implements hierarchical prior selection for conjugate priors in the fashion of Giannone, Lenza & Primiceri (2015). Allows for the computation of impulse responses and forecasts and provides functionality for assessing results.

Home Page: https://cran.r-project.org/package=BVAR

License: Other

R 83.43% Makefile 0.48% TeX 16.10%
bvar vector-autoregressions impulse-responses forecasts bayesian

bvar's Introduction

BVAR: Hierarchical Bayesian Vector Autoregression

CRAN codecov month total

Estimation of hierarchical Bayesian vector autoregressive models following Kuschnig & Vashold (2021). Implements hierarchical prior selection for conjugate priors in the fashion of Giannone, Lenza & Primiceri (2015). Functions to calculate forecasts, and compute and identify impulse responses and forecast error variance decompositions are available. Several methods to print, plot and summarise results facilitate analysis.

Installation

BVAR is available on CRAN. The development version can be installed from GitHub.

install.packages("BVAR")
devtools::install_github("nk027/BVAR")

Usage

The main function to perform hierarchical Bayesian VAR estimation is bvar(). Calls can be customised with regard to the sampling (e.g. via n_draw, or see bv_mh()) or with regard to the priors (see bv_priors()). Forecasts and impulse responses can be computed at runtime, or afterwards (see predict() and irf()). Identification of sign restrictions can be achieved recursively, via sign restrictions, or via zero and sign restrictions.

Analysis is facilitated by a variety of standard methods. The default plot() method provides trace and density plots of hyperparameters and optionally coefficients. Impulse responses and forecasts can easily be assessed with the provided plot() methods. Other available methods include summary(), fitted(), residuals(), coef(), vcov() and density(). Note that BVAR generates draws from the posterior -- all methods include functionality to access this distributional information. Information can be obtained directly or more conveniently using the BVARverse package.

BVAR comes with the FRED-MD and FRED-QD datasets (McCracken and Ng, 2016). They can be accessed using data("fred_md") or data("fred_qd") respectively. The dataset is licensed under a modified ODC-BY 1.0 license, that is available in the provided LICENSE file.

Demonstration

# Load the package
library("BVAR")

# Access a subset of the fred_qd dataset
data <- fred_qd[, c("GDPC1", "CPIAUCSL", "UNRATE", "FEDFUNDS")]
# Transform it to be stationary
data <- fred_transform(data, codes = c(5, 5, 5, 1), lag = 4)

# Estimate using default priors and MH step
x <- bvar(data, lags = 1)

# Check convergence via trace and density plots
plot(x)

# Calculate and store forecasts and impulse responses
predict(x) <- predict(x, horizon = 20)
irf(x) <- irf(x, horizon = 20, identification = TRUE)

# Plot forecasts and impulse responses
plot(predict(x))
plot(irf(x))

References

Nikolas Kuschnig and Lukas Vashold (2021). BVAR: Bayesian Vector Autoregressions with Hierarchical Prior Selection in R. Journal of Statistical Software, 14, 1-27, DOI: 10.18637/jss.v100.i14.

Domenico Giannone, Michele Lenza and Giorgio E. Primiceri (2015). Prior Selection for Vector Autoregressions. The Review of Economics and Statistics, 97:2, 436-451, DOI: 10.1162/REST_a_00483.

Michael W. McCracken and Serena Ng (2016). FRED-MD: A Monthly Database for Macroeconomic Research. Journal of Business & Economic Statistics, 34:4, 574-589, DOI: 10.1080/07350015.2015.1086655.

bvar's People

Contributors

nk027 avatar odnaudio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

bvar's Issues

Add psi's prior pdf to log ML

Psi is not yet added to log(ML) and does not yet have scale and shape parameters in the code. The prior is and inverse gamma with scale and shape defaulting to 0.02^2.

Wrap parallelised calculation

While running the code in parallel works nicely (and some outputs work well) the setup is a bit clunky. We should be straightforward to provide a wrapper for this.

Extend available methods

At the moment only plot() and print() exist for the bvar object.

Important standard methods are:

  • fitted(): Probably better to calculate ex-post.
  • predict(): This is currently done in the main chain, as it shouldn't necessitate too much additional effort. Allowing to calculate this ex-post should not be an issue, however.
  • summary(): This really needs to be readded.
  • residuals(): See fitted()

Further potential methods are:

  • coef(): Should be useful and rather straightforward. Optionally consider the vars implementation of Acoef() and Bcoef().
  • vcov(): Should also be straightforward.
  • logLik(): Might as well.
  • irf(): See predict().
  • fevd(): Nice shorthand.
  • stability(): Additional dependency, but might make sense.
  • Phi() & Psi(): Would address facilitating switches from and to vars.
  • The user interface of BVAR has bvar as the main fitting function
    returning an object that only has a plot() and a print() method. First,
    other standard methods like fitted(), predict(), residuals(), and
    summary() should be added. Second, methods that are typically available
    for frequentist models like coef(), vcov(), logLik() etc. might also make
    sense in this Bayesian setting. Third, the "vars" package defines generics
    and methods for a lot of VAR-specific functionality, e.g., Phi(), Psi(),
    fevd(), irf(), stability(). As already mentioned in the previous point it
    would be very natural to provide methods to these generics as well.

Consider VARX

There seems to be some interest for this and estimation-wise the implementation should be feasible. However, analysis and some potentially important details may diverge to the point where it does not make sense to add this feature. E.g. dummy-observation priors would probably not be compatible.

Adapt vignette from paper

Add the paper as vignette, maybe adapt a second, more concise demonstration from it (possibly in HTML).

Extend testing procedures

At the moment the core functionality is tested in the examples, with some (longer) parts only being run when requested specifically.
It makes sense to (a) split examples and tests to a certain extent and (b) extend the unit tests to as much functionality as possible and look more closely at the results.

To achieve this we have to rework the examples and add unit test scripts, possibly using testthat.

Include dataset

Include an interesting dataset to showcase the functionality in a "non-trivial way".

Consider naming scheme

The prefix bv_ makes it rather easy to find functions associated with the package and allows for some extra options without parameter-clutter. However, it is non-standard and might prove to be an entry-barrier, especially in conjunction with standard S3 methods.

Due to compatibility the functions need to stay anyway. It might make sense to move the standard functionalities to classic names and keep the naming scheme as shortcuts and for specific functions (e.g. prior creation and other settings).

R dependence on CRAN

CRAN reports dependences as R (>= 3.5.0). However, the package was tested on 3.3.0 and the DESCRIPTION file lists R (>= 3.3.0).

This appears to be some kind of bug (either of the package or on CRAN) and should be fixed in the future. Afaik the dependency should be taken straight from the DESCRIPTION.

Plotting functions

So far the following plots exist:

  • Trace
  • Density / Histogram
  • IRF / Forecast

Trace & Density are wrapped in the (presumably) default print method. However, both should probably be readily accessible on their own (i.e. provide a wrapper).
The IRF and Forecast functions are very similar and in their core they could be generalised and merged.

The naming scheme should also remain consistent (bv_ atm). Plots could be called bv_plot_trace, bv_plot_density, bv_plot_irf, etc.?

Assigning classes to elements of the main object might also be an option for plotting - e.g. one could call plot(object$irf) or plot(object$hyper).

More plotting improvements

The plotting method of our density class now supports plotting the coefficient densities. This should also be possible for the standard plotting method.

It might make sense to reconsider the naming scheme -- we currently have parameters vars, vars_impulse, vars_response, var_dep (dependent), vars_ind (independent).

I guess we should call all of the latter ones the same way (established one is preferable and interpretation of dependent and response variable is similar).
vars is a bit weird, as it is used for the variables to forecast and for hyperparameters to plot...

Update FRED-QD

FRED-QD is now available under a modified ODC-BY 1.0.
Some of the (so-far) excluded series are also in public domain and can be readded. Also notices and the license need to be added.

Methods

Several methods (e.g. summary, print, et cetera) need to be implemented for the following classes:

  • bvar
  • bv_priors
  • bv_metropolis
  • bv_fcast
  • bv_irf

CRAN comments #1

Thanks,

Please always write references in the form
authors (year) doi:...
authors (year) arXiv:...
authors (year, ISBN:...)
with no space after 'doi:', 'arXiv:' and angle brackets for auto-linking.

Please provide small executable examples in all your exported functions'
Rd files to illustrate the use of the exported function but also enable
automatic testing.

Please fix and resubmit.

Best,
Martina Schmirl

coda Dependency

Maybe we should wrap outputs into coda::mcmc objects and just drop the relevant methods from BVAR.

Rework drawing and storing handling

I got the feedback that it's a bit counterintuitive to specify the total number of draws and then the amount of them which are to be discarded instead of specifying the number of saved draws and the ones to burn.

Also, when n_draw == n_burn, an error message stemming from the integer check of n_thin pops up at the moment. Whether or not the specification of draws is changed, this should be fixed.

To-do v0.2.0

Add latest changes to NEWS and cran-comments.

Move formatted input and outputs to TEX.

Psi

  • As discussed there's the stationarity question
  • If a mode is provided we get an unnecessary warning: priors[["psi"]][["mode"]] == "auto". Should be an easy fix.

Plotting and other methods - naming

Accessing parameters and variables via vars, vars_impulse and vars_response is still quite weird and non-standard. This really needs to be unified.

Plotting of IRF and Fcast

Use a variable parameter to limit the variables plotted:

  • For impulse responses one might want to look at specific impulses and responses
  • Forecasts would jutst be limit to specific variables

Both functions could also use a parameter to limit the plotted horizon.

Fcast or irf via list with empty element not verbose

When doing:

> plot((x$fcast))
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf

this happens with no fcast computed and needs to fail in a nicer way.

Example Paper, SP500

In the paper we used the SP500, which is not under public domain and thus no longer included in the package.

Organise documentation

Functions and methods have slightly exploded.

We need to make sure that related functions and methods are documented together (e.g. print.bvar method probably fits better to bvar than on its own., irf may as well be grouped fevd, etc).

auto_psi

The auto_psi() function in the file 10_bvar.R, line 176, fit an AR(lags). However, the replication files of Giannone et al. (2015), fit only an AR(1). Wouldn't it be a good option to parametrize also the order of the AR model in the main function? Thanks

Issue with as.mcmc

as.mcmc.bvar() uses prep_data() to provide wither parameters or variables. In case variables are requested via name we are missing x[["variables"]] in the function.

as.mcmc(x, vars_response = "CPIAUCSL")
Error in get_var_set(vars_response, M = x[["meta"]][["M"]]) : 
  argument "variables" is missing, with no default

Elaborate on the FEVD

Right now we average over T, in the future we should provide them per horizon. Then it makes sense to offer some plotting methods (e.g. stacked bars).

Uninformative crash when data is non-stationary

When bvar() is run with problematic data it fails without any usable information - the message is just: Error in value[[3L]](cond) : unused argument (cond).

This absolutely needs to fail more gracefully as it would probably occur frequently.

Prettify prediction / irf plots

At the very least plots for prediction should include some of the time series itself.

Also we might add an option for shaded areas vs. lines. Note that there might be more than 3 quants?

CRAN comments #2

Thanks,

Please also write references in the description field of the description
file in the form
authors (year) doi:...
authors (year) arXiv:...
authors (year, ISBN:...)
with no space after 'doi:', 'arXiv:' and angle brackets for auto-linking.

\dontrun{} is supposed to be used for examples which should not be
called by the user. Please replace \dontrun{} with \donttest{} or unwrap
the examples if they are executable in < 5 sec.

Please fix and resubmit.

Best,
Martina Schmirl

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.