Git Product home page Git Product logo

bsvarsigns's Introduction

bsvarSIGNs bsvarSIGNs website

An R package for Bayesian Estimation of Structural Vector Autoregressions Identified by Sign, Zero, and Narrative Restrictions

R-CMD-check

Implements state-of-the-art algorithms for the Bayesian analysis of Structural Vector Autoregressions identified by sign, zero, and narrative restrictions. The core model is based on a flexible Vector Autoregression with estimated hyper-parameters of the Minnesota prior and the dummy observation priors as in Giannone, Lenza, Primiceri (2015). The sign restrictions are implemented employing the methods proposed by Rubio-Ramírez, Waggoner & Zha (2010), while identification through sign and zero restrictions follows the approach developed by Arias, Rubio-Ramírez, & Waggoner (2018). Furthermore, our tool provides algorithms for identification via sign and narrative restrictions, in line with the methods introduced by Antolín-Díaz and Rubio-Ramírez (2018). Users can also estimate a model with sign, zero, and narrative restrictions imposed at once. The package facilitates predictive and structural analyses using impulse responses, forecast error variance and historical decompositions, forecasting and conditional forecasting, as well as analyses of structural shocks and fitted values. All this is complemented by colourful plots, user-friendly summary functions, and comprehensive documentation. The bsvarSIGNs package is aligned regarding objects, workflows, and code structure with the R package bsvars by Woźniak (2024), and they constitute an integrated toolset.

Features

Structural Vector Autoregressions

  • All the models in the bsvarSIGNs package consist of the Vector Autoregressive equation, with autoregressive parameters A and error terms E, and the structural equation with a structural matrix B and shocks U
    Y = AX + E           (VAR equation)
   BE = U                (structural equation)
  • All the models feature a hierarchical Minnesota prior following the specification proposed by Giannone, Lenza, Primiceri (2015)
  • The identification of the SVAR model is achieved by imposing:
    • sign restrictions on the structural matrix $\mathbf{B}$,
    • sign and zero restrictions on the zero-horizon impulse responses $\mathbf{\Theta}_0 = \mathbf{B}^{-1}$,
    • sign restrictions on the impulse responses at other horizons $\mathbf{\Theta}_i$ for $i = 1, 2, \ldots$,
    • sign restrictions on selected structural shocks $\mathbf{u}_t$,
    • two types of sign restrictions on the historical decompositions.

Simple workflows

  • Specify the models using specify_bsvarSIGN$new() function
  • Estimate the models using the estimate() method
  • Predict the future using the forecast() method
  • Provide structural analyses using impulse responses, forecast error variance decompositions, historical decompositions, and structural shocks using functions compute_impulse_responses(), compute_variance_decompositions(), compute_historical_decompositions(), and compute_structural_shocks() respectively
  • Analyse the fitted values, time-varying volatility using functions compute_fitted_values() and compute_conditional_sd() respectively
  • Use plot() and summary() methods to gain the insights into the core of the empirical problem.

Fast and efficient computations

  • Blazingly fast computations are obtained by combining
    • the application of frontier econometric and numerical techniques, and
    • the implementation using compiled code written in cpp
  • It combines the best of two worlds: the ease of data analysis with R and fast cpp algorithms
  • The algorithms used here are very fast. But still, Bayesian estimation might take a little time. Look at our beautiful progress bar in the meantime:
**************************************************|
 bsvarSIGNs: Bayesian Structural VAR with sign,   |
             zero and narrative restrictions      |
**************************************************|
 Progress of simulation for 1000 independent draws
 Press Esc to interrupt the computations
**************************************************|
0%   10   20   30   40   50   60   70   80   90   100%
[----|----|----|----|----|----|----|----|----|----|
***********************************

The hexagonal logo

This beautiful logo can be reproduced in R using this file.

bsvars website

Examples

Replication of the results by Arias, Rubio-Ramírez, & Waggoner (2018).

# investigate the effects of the optimism shock
data(optimism)

# specify identifying restrictions:
# + no effect on productivity (zero restriction)
# + positive effect on stock prices (positive sign restriction)
sign_irf       = matrix(c(0, 1, rep(NA, 23)), 5, 5)

# specify the model
specification  = specify_bsvarSIGN$new(optimism * 100,
                                       p        = 4,
                                       sign_irf = sign_irf)

# estimate the model
posterior      = estimate(specification, S = 100)

# compute and plot impulse responses
irf            = compute_impulse_responses(posterior, horizon = 40)
plot(irf, probability = 0.68)

Replication of the results by Antolín-Díaz and Rubio-Ramírez (2018).

# investigate the effects of the contractionary monetary policy shock
data(monetary)

# specify identifying restrictions:
# + sign restrictions on the impulse responses at horizons from 0 to 5
sign_irf       = matrix(NA, 6, 6)
sign_irf[, 1]  = c(NA, -1, -1, NA, -1, 1)
sign_irf       = array(sign_irf, dim = c(6, 6, 6))

# + narrative sign restriction: the shock is positive in October 1979
sign_narrative = list(
  specify_narrative(start = 166, periods = 1, type = "S", sign = 1, shock = 1),
  specify_narrative(start = 166, periods = 1, type = "B", sign = 1, shock = 1, var = 6)
)

# specify the model
specification  = specify_bsvarSIGN$new(monetary       * 100,
                                       p              = 12,
                                       sign_irf       = sign_irf,
                                       sign_narrative = sign_narrative)

# estimate the model
posterior      = estimate(specification, S = 100)

# compute and plot impulse responses
irf            = compute_impulse_responses(posterior, horizon = 60)
plot(irf, probability = 0.68)

Installation

The first time you install the package

You must have a cpp compiler. Follow the instructions from Section 1.3. by Eddelbuettel & François (2023). In short, for Windows: install RTools, for macOS: install Xcode Command Line Tools, and for Linux: install the standard development packages.

Once that’s done:

Just open your R and type:

install.packages("bsvarSIGNs")

The developer’s version of the package with the newest features can be installed by typing:

devtools::install_github("bsvars/bsvarSIGNs")

Development

The package is under intensive development. Your help is most welcome! Please, have a look at the roadmap and report a bug. Thank you!

About the authors

Xiaolei is a PhD candidate at the University of Melbourne. He is interested in Bayesian econometrics and time series analysis and is the author and maintainer of the bsvarSIGNs package.

Tomasz is a Bayesian econometrician and a Senior Lecturer at the University of Melbourne. He develops methodology for empirical macroeconomic analyses and programs in R and cpp using Rcpp.

bsvarsigns's People

Contributors

adamwang15 avatar donotdespair avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

bsvarsigns's Issues

Release bsvarSIGNs 1.0

First release:

Prepare for release:

  • git pull
  • usethis::use_github_links()
  • urlchecker::url_check()
  • devtools::build_readme()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • git push
  • Draft blog post bsvars/bsvars_social#2

Submit to CRAN:

  • usethis::use_version('major')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • Finish & publish blog post
  • Add link to blog post in pkgdown news menu
  • usethis::use_github_release()
  • usethis::use_dev_version(push = TRUE)
  • Tweet

problems with estimate generic and menthods

@donotdespair got the WARNNING:

❯ checking S3 generic/method consistency ... WARNING
  estimate:
    function(specification, S, thin, show_progress)
  estimate.BSVARSIGN:
    function(specification, S, thin, show_progress, max_tries)
  
  estimate:
    function(specification, S, thin, show_progress)
  estimate.PosteriorBSVARSIGN:
    function(specification, S, thin, show_progress, max_tries)
  See section ‘Generic functions and methods’ in the ‘Writing R
  Extensions’ manual.
  • make the list of arguments of estimate.BSVARSIGN and estimate the same
  • argument max_tries should be provided by specify_*()

Can't build on my laptop

You @adamwang15 could not compile first, now I cannot. We need to work this out

> Rcpp::compileAttributes()
> devtools::document()            # to build documentation form roxygen headers
ℹ Updating bsvarSIGNs documentation
ℹ Loading bsvarSIGNs
Error in dyn.load(dll_copy_file) : 
  unable to load shared object '/var/folders/_d/j7rqc71x2y54_69_6v6q33fr0000gn/T//Rtmpc6FN7L/pkgload101312d7656/bsvarSIGNs.so':

Release bsvarSIGNs 1.0.1

Prepare for release:

  • git pull
  • Check current CRAN check results
  • Polish NEWS
  • usethis::use_github_links()
  • urlchecker::url_check()
  • devtools::build_readme()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • revdepcheck::revdep_check(num_workers = 4)
  • Update cran-comments.md
  • git push

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • usethis::use_github_release()
  • usethis::use_dev_version(push = TRUE)

update the forecast method

expand method forecast to allow conditional forecasting

Following the practice from bsvars/bvarPANELs#8

  • develop cpp forecasting function (not bsvars::forecast_bsvars as we can compute Sigma differently)
  • use bsvars::mnorm_cond
  • expand R method
  • documentation
  • testing
  • NEWS

full revision of specify_*()

  • revise its working in general (should be OK)
  • revise its working wrt identification (especially for narrative)
  • inner documentation - good explanations
  • inner documentation - examples
  • tests based on testthatv3.0

Implement Normal-Inverse-Wishart sampler

  • sample sigma from inverse Wishart
  • sample A given sigma from normal
  • DONE: check the IW sampler
  • NOPE: correct the cpp implementation of the algo from 10 mxcs.pdf slide 13 @donotdespair
  • NOPE: implement the algo from BRL1999 (it's different) @donotdespair

future considerations:

  • NOPE WE'RE NOT DOING THIS test other ways for sampling sigma, e.g. equation-by-equation with chol(sigma)

other SVARs to be considered

Papers we should implement

SVARs

BVARs

Papers that are useful

Parallel computing

  • parallelize with OpenMP
  • progress bar with parallelization

Let's go!

  • fix the bug in cpp code for running bsvar_sign_cpp: as_scalar() WTF
  • get rid of normalisation from estimate
  • update the documentation on specify_bsvarSIGN and estimate.BSVARSIGN #4

bsvarSIGNs v1.0 CRAN submission plan

Todos agreed on in conversation on 2024-06-11

  • finalise cpp code for GLP model #13
  • NOT DOING THIS! prepare a separate specify_* function and estimate method for the particular models by #13
  • import generics from bsvars #21 and write bsvarSIGNs-specific methods:
    • estimate
    • #25
    • forecast including conditional forecast #23
    • correct forecast once #27 is done

Final round-up

  • documentation
  • tests
  • NEWS file
  • DONE BY THE PACKAGE NO NEED TO DO ANYTHING: CITATION file
  • data reproduction files
  • logo
  • pkgdown website
  • final checks

Standardized IRFs cannot be obtained

In the example of the Replication of the results by Arias, Rubio-Ramírez, & Waggoner (2018) and in any other case, when setting the standardise argument to TRUE in the compute_impulse_responses() function you get this error if you try to plot the respective irf object:

Error in quantile.default(newX[, i], ...) :
missing values and NaN's not allowed if 'na.rm' is FALSE

work on `estimate` generic help file in **bsvars**

  • Work on estimate generic help file in bsvars. The problem is that when one uses bsvarSIGNs and types ?estimate They see the bsvars-specific description. It should be made more general for the family of bsvars packages.
  • adjusted the help file!
  • work on the checks for compute_*() functions to allow PosteriorBSVARSIGN. Just check for PosteriorBSVAR

coherent bsvars notation

Notations in R should be coherent with bsvars and notations in C++ should be coherent with original papers.

  • transpose Y, X, Ysoc, Ysur, Xsoc, Xsur, V matrices
  • change B in prior to A
  • remove Vp, Vd in prior

more user-friendly things

  • combine sign_irf and zero_irf (0 for zero restriction, NA for no restrictions)
  • allow inputs of matrices for restrictions on irf0 only (instead of arrays)
  • rename sign_B
  • progress bar
  • specify_narrative function
  • remove VB and other unnecessary parameters

Some theoretical concerns

  • The new function to compute historical decomposition hd1 compiles and works. Test if it is actually correct.
  • When draws of Q reach max_tries, we let the Gibbs sampler run one more iteration to get new A, B and hyper and try new draws of Q. Verify if this is valid, and if we need to draw new hyper. TW: hey @adamwang15 this is addressed in Arias, Rubio-Ramírez, Shin & Waggoner (2024, WP) that I linked at #13
  • When computing importance weight, can we keep using the same set of $M$ standard normal draws for approximation (algorithm 1 iii a)? And use the same draw for all restrictions (ignoring $t,t+h$)?
  • Verify if importance sampling can be applied directly when there is hyper-parameter.

revise cpp code

  • [SHALL WE DO THIS?] to try to replicate the examples from ADRR18 exactly
  • any other problems here?

notation change

Change notation from A (autoregressive matrix) and B (structural matrix) to (B, Sigma, Q) and (A0, Aplus) as in RRWZ (2010).

We're working with matrices B (KxN), Sigma (NxN), Q (NxN), and Theta0 = chol(Sigma, "lower") * Q (NxN)

  • cpp code in sample_Q
  • returned posterior parameters
  • revise cpp function for ir1_cpp
  • a new cpp function bsvarSIGNs_ir
  • revise cpp function for hd1_cpp
  • a new cpp function for fevd
  • a new cpp function for forecast

In help files and documentation

We need to use the following model notation (otherwise people will hate us!)

y_t = A_1 y_{t-1} + e_t  
e_t = Theta_0 u_t

Y = XB + E  
E = U Theta_0'

Difficulty drawing valid Q matrix

We have a minimum working example of sign restrictions on impulse response functions, but it is very difficult to have valid draws of Q, which is strange since only horizon 0 is considered.

set.seed(123)
data(oil)

sign_irf <-
  array(matrix(c(-1, -1, 1, 1, 1, 1, 1, -1, 1), nrow = 3), dim = c(3, 3, 1))
specification <-
  specify_bsvarSIGN$new(oil, p = 12, sign_irf = sign_irf)

burn_in <- estimate.BSVARSIGN(specification, 101, thin = 100)
posterior <- estimate.PosteriorBSVARSIGN(burn_in, 10, thin = 1)

# test
posterior$posterior$B # only one draw is valid
posterior$posterior$B[, , 1] |> solve()

#             [,1]      [,2]       [,3]
# [1,] -0.99836620 0.8753184  0.4946759
# [2,] -0.05624569 3.6964931 -6.0691198
# [3,]  4.72269479 4.7975231  1.4027944

Include dependencies on bsvars

Use bsvars exported code whenever possible

  • cpp files bsvars_sign.cpp: removed copy/pasted functions and included dependencies
  • included bsvars in LinkingTo in file DESCRIPTION
  • compiled
  • after recoding bsvars change the individual samplers in file bsvar_sign.cpp to fill by assignment
  • adjust specify_bsvarSIGN so that it inherits from specify_bsvar as much as possible
    • data_matrices
    • specify_identification

change examples

change the default examples to optimism, and update the corresponding tests

OpenMP on CRAN

Code for parallelization is available but does not pass the checks #13

  • read documentations about this
  • adjust Makevars

Just do it!

  • Think of how to modify specify_bsvarSIGN to accommodate sign restrictions on contemporaneous effects B and impulse responses at 0 horizon #4
  • Think of how to modify cpp function bsvar_sign_cpp for sign restrictions
  • add ADRR data
  • add help file for this data (hint: check out bsvars package)

README and pkgdown website

  • DESCRIPTION
  • CITATION
  • rewrite bsvarSIGNs-package.R
  • prepare a good README
  • include the logo
  • generate pkgdown website
  • include cran-comments.md

small corrections after v1.0

Hey @adamwang15,

I'm looking at our package and we need to improve some things:

  • update @references in documentation for estimate.BSVARSIGN
  • @adamwang15 I'm looking at the code below
spec$prior$estimate_hyper (mu = TRUE, delta = TRUE, lambda = TRUE, psi = TRUE)

and I think we should make this possible by running

spec$estimate_hyper (mu = TRUE, delta = TRUE, lambda = TRUE, psi = TRUE)

or both should be possible 😸

  • Shall we update the example in specify_narrative() so that the current one:
specify_narrative(start = 166, periods = 1, type = "S", sign = 1, shock = 1, var = 6)

was used in context:

narrative = specify_narrative(start = 166, periods = 1, type = "S", sign = 1, shock = 1, var = 6)
specification  = specify_bsvarSIGN$new(monetary, sign_narrative = list(narrative))

iwishrnd bug

multiplying data matrix by constants makes the scale matrix for inverse-Wishart not symmetric positive definite

data(optimism)
spec = specify_bsvarSIGN$new(optimism*10, p = 4)
post = estimate(spec, S = 2)

Error in estimate.BSVARSIGN(spec, S = 2) : 
  iwishrnd(): given matrix is not symmetric positive definite and/or df is too low

HEX logo

  • take one of the IRFs using oil data and bsvarSIGNs package
  • choose two crazy colours @adamwang15

develop compute_* methods

  • compute_structural_shocks
  • compute_fitted_values
  • compute_impulse_responses
  • compute_historical_decompositions
  • compute_variance_decompositions
  • compute_conditional_sd
  • documentation
  • tests
  • NEWS

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.