R/RcppExports.R

Defines functions .vardecomp ssvs stochvol_ocsn2007 stochvol_ksc1998 stoch_vol post_normal_sur post_normal post_coint_kls_sur post_coint_kls loglik_normal kalman_dk .ir .draw_forecast .dfmalg bvs .bvectvpalg .bvecalg .bvartvpalg .bvaralg

Documented in bvs kalman_dk loglik_normal post_coint_kls post_coint_kls_sur post_normal post_normal_sur ssvs stoch_vol stochvol_ksc1998 stochvol_ocsn2007

# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

.bvaralg <- function(object) {
    .Call(`_bvartools_bvaralg`, object)
}

.bvartvpalg <- function(object) {
    .Call(`_bvartools_bvartvpalg`, object)
}

.bvecalg <- function(object) {
    .Call(`_bvartools_bvecalg`, object)
}

.bvectvpalg <- function(object) {
    .Call(`_bvartools_bvectvpalg`, object)
}

#' Bayesian Variable Selection
#' 
#' \code{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.
#' 
#' @param y a \eqn{K \times T} matrix of the endogenous variables.
#' @param z a \eqn{KT \times M} matrix of explanatory variables.
#' @param a an M-dimensional vector of parameter draws. If time varying parameters are used,
#' an \eqn{M \times T} coefficient matrix can be provided.
#' @param lambda an \eqn{M \times M} inclusion matrix that should be updated.
#' @param sigma_i the inverse variance-covariance matrix. If the variance-covariance matrix
#' is time varying, a \eqn{KT \times K} matrix can be provided.
#' @param prob_prior an M-dimensional vector of prior inclusion probabilities.
#' @param include an integer vector specifying the positions of variables, which should be
#' included in the BVS algorithm. If \code{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 \eqn{\Lambda} for the VAR model
#' \deqn{y_t = Z_t \Lambda a_t + u_t,}
#' where \eqn{u_t \sim N(0, \Sigma_{t})}.
#' \eqn{y_t} is a K-dimensional vector of endogenous variables and
#' \eqn{Z_t = x_t^{\prime} \otimes I_K} is a \eqn{K \times M} matrix of regressors with
#' \eqn{x_t} as a vector of regressors.
#' 
#' @return A matrix of inclusion parameters on its diagonal.
#' 
#' @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)
#' 
#' @references
#' 
#' Korobilis, D. (2013). VAR forecasting using Bayesian variable selection. \emph{Journal of Applied Econometrics, 28}(2), 204--230. \doi{10.1002/jae.1271}
#' 
bvs <- function(y, z, a, lambda, sigma_i, prob_prior, include = NULL) {
    .Call(`_bvartools_bvs`, y, z, a, lambda, sigma_i, prob_prior, include)
}

.dfmalg <- function(object) {
    .Call(`_bvartools_dfmalg`, object)
}

.draw_forecast <- function(i, k, p, a0_i, use_a, a_, sigma, pred) {
    .Call(`_bvartools_draw_forecast`, i, k, p, a0_i, use_a, a_, sigma, pred)
}

.ir <- function(A, h, type, impulse, response) {
    .Call(`_bvartools_ir`, A, h, type, impulse, response)
}

#' Durbin and Koopman Simulation Smoother
#' 
#' An implementation of the Kalman filter and backward smoothing
#' algorithm proposed by Durbin and Koopman (2002).
#' 
#' @param y a \eqn{K \times T} matrix of endogenous variables.
#' @param z a \eqn{KT \times M} matrix of explanatory variables.
#' @param sigma_u the constant \eqn{K \times K} error variance-covariance matrix.
#' For time varying variance-covariance matrices a \eqn{KT \times K} can be specified.
#' @param sigma_v the constant \eqn{M \times M} coefficient variance-covariance matrix.
#' For time varying variance-covariance matrices a \eqn{MT \times M} can be specified.
#' @param B an \eqn{M \times M} autocorrelation matrix of the transition equation.
#' @param a_init an M-dimensional vector of initial states.
#' @param P_init an \eqn{M \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 \eqn{a_t} for \eqn{t = 1,...,T} for a state space model
#' with measurement equation
#' \deqn{y_t = Z_t a_t + u_t}
#' and transition equation 
#' \deqn{a_{t + 1} = B_t a_{t} + v_t,}
#' where \eqn{u_t \sim N(0, \Sigma_{u,t})} and \eqn{v_t \sim N(0, \Sigma_{v,t})}.
#' \eqn{y_t} is a K-dimensional vector of endogenous variables and
#' \eqn{Z_t = z_t^{\prime} \otimes I_K} is a \eqn{K \times M} matrix of regressors with
#' \eqn{z_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.
#' 
#' @return A \eqn{M \times T+1} matrix of state vector draws.
#' 
#' @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)
#' 
#' @references
#' 
#' Durbin, J., & Koopman, S. J. (2002). A simple and efficient simulation smoother for
#' state space time series analysis. \emph{Biometrika, 89}(3), 603--615.
#' 
#' Jarociński, M. (2015). A note on implementing the Durbin and Koopman simulation
#' smoother. \emph{Computational Statistics and Data Analysis, 91}, 1--3.
#' \doi{10.1016/j.csda.2015.05.001}
#' 
kalman_dk <- function(y, z, sigma_u, sigma_v, B, a_init, P_init) {
    .Call(`_bvartools_kalman_dk`, y, z, sigma_u, sigma_v, B, a_init, P_init)
}

#' Calculates the log-likelihood of a multivariate normal distribution.
#' 
#' @param u a \eqn{K \times T} matrix of residuals.
#' @param sigma a \eqn{K \times K} or \eqn{KT \times K} variance-covariance matrix.
#' 
#' @details The log-likelihood is calculated for each vector in period \eqn{t} as
#' \deqn{-\frac{K}{2} \ln 2\pi - \frac{1}{2} \ln |\Sigma_t| -\frac{1}{2} u_t^\prime \Sigma_t^{-1} u_t},
#' where \eqn{u_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)
#' 
loglik_normal <- function(u, sigma) {
    .Call(`_bvartools_loglik_normal`, u, sigma)
}

#' Posterior Draw for Cointegration Models
#' 
#' 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.
#' 
#' @param y a \eqn{K \times T} matrix of differenced endogenous variables.
#' @param beta a \eqn{M \times r} cointegration matrix \eqn{\beta}.
#' @param w a \eqn{M \times T} matrix of variables in the cointegration term.
#' @param x  a \eqn{N \times T} matrix of differenced regressors and unrestricted deterministic terms.
#' @param sigma_i an inverse of the \eqn{K \times K} variance-covariance matrix.
#' @param v_i a numeric between 0 and 1 specifying the shrinkage of the cointegration space prior.
#' @param p_tau_i an inverted \eqn{M \times M} matrix specifying the central location
#' of the cointegration space prior of \eqn{sp(\beta)}.
#' @param g_i a \eqn{K \times K} matrix.
#' @param gamma_mu_prior a \eqn{KN \times 1} prior mean vector of non-cointegration coefficients.
#' @param gamma_v_i_prior an inverted \eqn{KN \times KN} prior covariance matrix of non-cointegration coefficients.
#' 
#' @details The function produces posterior draws of the coefficient
#' matrices \eqn{\alpha}, \eqn{\beta} and \eqn{\Gamma} for the model
#' \deqn{y_{t} = \alpha \beta^{\prime} w_{t-1} + \Gamma z_{t} + u_{t},}
#' where \eqn{y_{t}} is a K-dimensional vector of differenced endogenous variables.
#' \eqn{w_{t}} is an \eqn{M \times 1} vector of variables in the cointegration term,
#' which include lagged values of endogenous and exogenous variables in levels and
#' restricted deterministic terms. \eqn{z_{t}} is an N-dimensional vector of
#' differenced endogenous and exogenous explanatory variabes as well as unrestricted
#' deterministic terms. The error term is \eqn{u_t \sim \Sigma}.
#' 
#' Draws of the loading matrix \eqn{\alpha} are obtained using the prior on the cointegration space
#' as proposed in Koop et al. (2010). The posterior covariance matrix is
#' \deqn{\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
#' \deqn{\overline{\alpha} = \overline{V}_{\alpha} + vec(\Sigma^{-1} Y Z^{\prime}),}
#' where \eqn{Y} is a \eqn{K \times T} matrix of differenced endogenous variables and
#' \eqn{Z = \beta^{\prime} W} with \eqn{W} as an \eqn{M \times T} matrix of
#' variables in the cointegration term.
#' 
#' For a given prior mean vector \eqn{\underline{\Gamma}} and prior covariance matrix \eqn{\underline{V_{\Gamma}}}
#' the posterior covariance matrix of non-cointegration coefficients in \eqn{\Gamma} is obtained by
#' \deqn{\overline{V}_{\Gamma} = \left[ \underline{V}_{\Gamma}^{-1} + \left(X X^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}}
#' and the posterior mean by
#' \deqn{\overline{\Gamma} = \overline{V}_{\Gamma} \left[ \underline{V}_{\Gamma}^{-1} \underline{\Gamma} + vec(\Sigma^{-1} Y X^{\prime}) \right],}
#' where \eqn{X} is an \eqn{M \times T} matrix of
#' explanatory variables, which do not enter the cointegration term.
#' 
#' Draws of the cointegration matrix \eqn{\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 \eqn{B} is
#' \deqn{\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
#' \deqn{\overline{B} = \overline{V}_{B} + vec(W Y_{B}^{-1} \Sigma^{-1} A),}
#' where \eqn{Y_{B} = Y - \Gamma X} and \eqn{A = \alpha (\alpha^{\prime} \alpha)^{-\frac{1}{2}}}.
#' 
#' The final draws of \eqn{\alpha} and \eqn{\beta} are calculated using
#' \eqn{\beta = B (B^{\prime} B)^{-\frac{1}{2}}} and
#' \eqn{\alpha = A (B^{\prime} B)^{\frac{1}{2}}}.
#' 
#' @return A named list containing the following elements:
#' \item{alpha}{a draw of the \eqn{K \times r} loading matrix.}
#' \item{beta}{a draw of the \eqn{M \times r} cointegration matrix.}
#' \item{Pi}{a draw of the \eqn{K \times M} cointegration matrix \eqn{\Pi = \alpha \beta^{\prime}}.}
#' \item{Gamma}{a draw of the \eqn{K \times N} coefficient matrix for non-cointegration parameters.}
#' 
#' @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)
#' 
#' @references
#' 
#' Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior
#' simulation for cointegrated models with priors on the cointegration space.
#' \emph{Econometric Reviews, 29}(2), 224-242. \doi{10.1080/07474930903382208}
#' 
post_coint_kls <- function(y, beta, w, sigma_i, v_i, p_tau_i, g_i, x = NULL, gamma_mu_prior = NULL, gamma_v_i_prior = NULL) {
    .Call(`_bvartools_post_coint_kls`, y, beta, w, sigma_i, v_i, p_tau_i, g_i, x, gamma_mu_prior, gamma_v_i_prior)
}

#' Posterior Draw for Cointegration Models
#' 
#' 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.
#' 
#' @param y a \eqn{K \times T} matrix of differenced endogenous variables.
#' @param beta a \eqn{M \times r} cointegration matrix \eqn{\beta}, where \eqn{\beta^{\prime} \beta = I}.
#' @param w a \eqn{M \times T} matrix of variables in the cointegration term.
#' @param x  a \eqn{KT \times NK} matrix of differenced regressors and unrestricted deterministic terms.
#' @param sigma_i the inverse of the constant \eqn{K \times K} error variance-covariance matrix.
#' For time varying variance-covariance matrics a \eqn{KT \times K} can be provided.
#' @param v_i a numeric between 0 and 1 specifying the shrinkage of the cointegration space prior.
#' @param p_tau_i an inverted \eqn{M \times M} matrix specifying the central location
#' of the cointegration space prior of \eqn{sp(\beta)}.
#' @param g_i a \eqn{K \times K} or \eqn{KT \times K} matrix. If the matrix is \eqn{KT \times K},
#' the function will automatically produce a \eqn{K \times K} matrix containing the means of the
#' time varying \eqn{K \times K} covariance matrix.
#' @param gamma_mu_prior a \eqn{KN \times 1} prior mean vector of non-cointegration coefficients.
#' @param gamma_v_i_prior an inverted \eqn{KN \times KN} prior covariance matrix of
#' non-cointegration coefficients.
#' @param svd logical. If \code{TRUE} the singular value decomposition is used to determine
#' the root of the posterior covariance matrix. Default is \code{FALSE} which means
#' that the eigenvalue decomposition is used.
#' 
#' @details The function produces posterior draws of the coefficient
#' matrices \eqn{\alpha}, \eqn{\beta} and \eqn{\Gamma} for the model
#' \deqn{y_{t} = \alpha \beta^{\prime} w_{t-1} + \Gamma z_{t} + u_{t},}
#' where \eqn{y_{t}} is a K-dimensional vector of differenced endogenous variables.
#' \eqn{w_{t}} is an \eqn{M \times 1} vector of variables in the cointegration term,
#' which include lagged values of endogenous and exogenous variables in levels and
#' restricted deterministic terms. \eqn{z_{t}} is an N-dimensional vector of
#' differenced endogenous and exogenous explanatory variabes as well as unrestricted
#' deterministic terms. The error term is \eqn{u_t \sim \Sigma}.
#' 
#' Draws of the loading matrix \eqn{\alpha} are obtained using the prior on the cointegration space
#' as proposed in Koop et al. (2010). The posterior covariance matrix is
#' \deqn{\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
#' \deqn{\overline{\alpha} = \overline{V}_{\alpha} + vec(\Sigma^{-1} Y Z^{\prime}),}
#' where \eqn{Y} is a \eqn{K \times T} matrix of differenced endogenous variables and
#' \eqn{Z = \beta^{\prime} W} with \eqn{W} as an \eqn{M \times T} matrix of
#' variables in the cointegration term.
#' 
#' For a given prior mean vector \eqn{\underline{\Gamma}} and prior covariance matrix \eqn{\underline{V_{\Gamma}}}
#' the posterior covariance matrix of non-cointegration coefficients in \eqn{\Gamma} is obtained by
#' \deqn{\overline{V}_{\Gamma} = \left[ \underline{V}_{\Gamma}^{-1} + \left(X X^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}}
#' and the posterior mean by
#' \deqn{\overline{\Gamma} = \overline{V}_{\Gamma} \left[ \underline{V}_{\Gamma}^{-1} \underline{\Gamma} + vec(\Sigma^{-1} Y X^{\prime}) \right],}
#' where \eqn{X} is an \eqn{M \times T} matrix of
#' explanatory variables, which do not enter the cointegration term.
#' 
#' Draws of the cointegration matrix \eqn{\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 \eqn{B} is
#' \deqn{\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
#' \deqn{\overline{B} = \overline{V}_{B} + vec(W Y_{B}^{-1} \Sigma^{-1} A),}
#' where \eqn{Y_{B} = Y - \Gamma X} and \eqn{A = \alpha (\alpha^{\prime} \alpha)^{-\frac{1}{2}}}.
#' 
#' The final draws of \eqn{\alpha} and \eqn{\beta} are calculated using
#' \eqn{\beta = B (B^{\prime} B)^{-\frac{1}{2}}} and
#' \eqn{\alpha = A (B^{\prime} B)^{\frac{1}{2}}}.
#' 
#' @return A named list containing the following elements:
#' \item{alpha}{a draw of the \eqn{K \times r} loading matrix.}
#' \item{beta}{a draw of the \eqn{M \times r} cointegration matrix.}
#' \item{Pi}{a draw of the \eqn{K \times M} cointegration matrix \eqn{\Pi = \alpha \beta^{\prime}}.}
#' \item{Gamma}{a draw of the \eqn{K \times N} coefficient matrix for non-cointegration parameters.}
#' 
#' @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)
#' 
#' @references
#' 
#' Koop, G., León-González, R., & Strachan R. W. (2010). Efficient posterior
#' simulation for cointegrated models with priors on the cointegration space.
#' \emph{Econometric Reviews, 29}(2), 224-242. \doi{10.1080/07474930903382208}
#' 
post_coint_kls_sur <- function(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) {
    .Call(`_bvartools_post_coint_kls_sur`, y, beta, w, sigma_i, v_i, p_tau_i, g_i, x, gamma_mu_prior, gamma_v_i_prior, svd)
}

#' Posterior Draw from a Normal Distribution
#' 
#' Produces a draw of coefficients from a normal posterior density.
#' 
#' @param y a \eqn{K \times T} matrix of endogenous variables.
#' @param x an \eqn{M \times T} matrix of explanatory variables.
#' @param sigma_i the inverse of the \eqn{K \times K} variance-covariance matrix.
#' @param a_prior a \eqn{KM \times 1} numeric vector of prior means.
#' @param v_i_prior the inverse of the \eqn{KM \times KM} prior covariance matrix.
#' 
#' @details The function produces a vectorised posterior draw \eqn{a} of the
#' \eqn{K \times M} coefficient matrix \eqn{A} for the model
#' \deqn{y_{t} = A x_{t} + u_{t},}
#' where \eqn{y_{t}} is a K-dimensional vector of endogenous variables,
#' \eqn{x_{t}} is an M-dimensional vector of explanatory variabes
#' and the error term is \eqn{u_t \sim \Sigma}.
#' 
#' For a given prior mean vector \eqn{\underline{a}} and prior covariance matrix \eqn{\underline{V}}
#' the posterior covariance matrix is obtained by
#' \deqn{\overline{V} = \left[ \underline{V}^{-1} + \left(X X^{\prime} \otimes \Sigma^{-1} \right) \right]^{-1}}
#' and the posterior mean by
#' \deqn{\overline{a} = \overline{V} \left[ \underline{V}^{-1} \underline{a} + vec(\Sigma^{-1} Y X^{\prime}) \right],}
#' where \eqn{Y} is a \eqn{K \times T} matrix of the endogenous variables and \eqn{X} is an \eqn{M \times T} matrix of
#' the explanatory variables.
#' 
#' @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)
#' 
#' @return A vector.
#' 
#' @references
#' 
#' Lütkepohl, H. (2006). \emph{New introduction to multiple time series analysis} (2nd ed.). Berlin: Springer.
#' 
post_normal <- function(y, x, sigma_i, a_prior, v_i_prior) {
    .Call(`_bvartools_post_normal`, y, x, sigma_i, a_prior, v_i_prior)
}

#' Posterior Draw from a Normal Distribution
#' 
#' Produces a draw of coefficients from a normal posterior density for
#' a model with seemingly unrelated regresssions (SUR).
#' 
#' @param y a \eqn{K \times T} matrix of endogenous variables.
#' @param z a \eqn{KT \times M} matrix of explanatory variables.
#' @param sigma_i the inverse of the constant \eqn{K \times K} error variance-covariance matrix.
#' For time varying variance-covariance matrics a \eqn{KT \times K} can be provided.
#' @param a_prior a \eqn{M x 1} numeric vector of prior means.
#' @param v_i_prior the inverse of the \eqn{M x M} prior covariance matrix.
#' @param svd logical. If \code{TRUE} the singular value decomposition is used to determine
#' the root of the posterior covariance matrix. Default is \code{FALSE} which means
#' that the eigenvalue decomposition is used.
#' 
#' @details The function produces a posterior draw of the coefficient vector \eqn{a} for the model
#' \deqn{y_{t} = Z_{t} a + u_{t},}
#' where \eqn{u_t \sim N(0, \Sigma_{t})}.
#' \eqn{y_t} is a K-dimensional vector of endogenous variables and
#' \eqn{Z_t = z_t^{\prime} \otimes I_K} is a \eqn{K \times KM} matrix of regressors with
#' \eqn{z_t} as a vector of regressors.
#' 
#' For a given prior mean vector \eqn{\underline{a}} and prior covariance matrix \eqn{\underline{V}}
#' the posterior covariance matrix is obtained by
#' \deqn{\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
#' \deqn{\overline{a} = \overline{V} \left[ \underline{V}^{-1} \underline{a} + \sum_{t=1}^{T} Z_{t}^{\prime} \Sigma_{t}^{-1} y_{t}  \right].}
#' 
#' @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)
#' 
#' @return A vector.
#' 
post_normal_sur <- function(y, z, sigma_i, a_prior, v_i_prior, svd = FALSE) {
    .Call(`_bvartools_post_normal_sur`, y, z, sigma_i, a_prior, v_i_prior, svd)
}

#' Stochastic Volatility
#' 
#' Produces a draw of log-volatilities.
#' 
#' @param y a \eqn{T \times 1} vector containing the time series.
#' @param h a \eqn{T \times 1} vector of log-volatilities.
#' @param sigma a numeric of the variance of the log-volatilites.
#' @param h_init a numeric of the initial state of log-volatilities.
#' @param constant a numeric of the constant that should be added to \eqn{y^2}
#' before taking the natural logarithm.
#' 
#' @details The function is a wrapper for function \code{\link{stochvol_ksc1998}}.
#' 
#' @return A vector of log-volatility draws.
#' 
#' @examples
#' data("us_macrodata")
#' y <- us_macrodata[, "r"]
#' 
#' # Initialise log-volatilites
#' h_init <- log(var(y))
#' h <- rep(h_init, length(y))
#' 
#' # Obtain draw
#' stoch_vol(y - mean(y), h, .05, h_init, 0.0001)
#' 
#' @references
#' 
#' Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). \emph{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. \emph{Review of Economic Studies 65}(3), 361--393. \doi{10.1111/1467-937X.00050}
#' 
stoch_vol <- function(y, h, sigma, h_init, constant) {
    .Call(`_bvartools_stoch_vol`, y, h, sigma, h_init, constant)
}

#' Stochastic Volatility
#' 
#' Produces a draw of log-volatilities.
#' 
#' @param y a \eqn{T \times 1} vector containing the time series.
#' @param h a \eqn{T \times 1} vector of log-volatilities.
#' @param sigma a numeric of the variance of the log-volatilites.
#' @param h_init a numeric of the initial state of log-volatilities.
#' @param constant a numeric of the constant that should be added to \eqn{y^2}
#' before taking the natural logarithm. See 'Details'.
#' 
#' @details The function produces a posterior draw of the log-volatility \eqn{h} for the model
#' \deqn{y_{t} = e^{\frac{1}{2}h_t} \epsilon_{t},}
#' where \eqn{\epsilon_t \sim N(0, 1)} and \eqn{h_t} is assumed to evolve according to a random walk
#' \deqn{h_t = h_{t - 1} + u_t,}
#' with \eqn{u_t \sim N(0, \sigma^2)}.
#' 
#' The implementation follows the algorithm of Kim, Shephard and Chip (1998) and performs the
#' following steps:
#' \enumerate{
#'   \item Perform the transformation \eqn{y_t^* = ln(y_t^2 + constant)}.
#'   \item Obtain a sample from the seven-component normal mixture for
#'   approximating the log-\eqn{\chi_1^2} distribution.
#'   \item 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).
#' 
#' @return A vector of log-volatility draws.
#' 
#' @examples
#' data("us_macrodata")
#' y <- us_macrodata[, "r"]
#' 
#' # Initialise log-volatilites
#' h_init <- log(var(y))
#' h <- rep(h_init, length(y))
#' 
#' # Obtain draw
#' stochvol_ksc1998(y - mean(y), h, .05, h_init, 0.0001)
#' 
#' @references
#' 
#' Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). \emph{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. \emph{Review of Economic Studies 65}(3), 361--393. \doi{10.1111/1467-937X.00050}
#' 
stochvol_ksc1998 <- function(y, h, sigma, h_init, constant) {
    .Call(`_bvartools_stochvol_ksc1998`, y, h, sigma, h_init, constant)
}

#' Stochastic Volatility
#' 
#' Produces a draw of log-volatilities based on Omori, Chib, Shephard and Nakajima (2007).
#' 
#' @param y a \eqn{T \times 1} vector containing the time series.
#' @param h a \eqn{T \times 1} vector of log-volatilities.
#' @param sigma a numeric of the variance of the log-volatilites.
#' @param h_init a numeric of the initial state of log-volatilities.
#' @param constant a numeric of the constant that should be added to \eqn{y^2}
#' before taking the natural logarithm. See 'Details'.
#' 
#' @details The function produces a posterior draw of the log-volatility \eqn{h} for the model
#' \deqn{y_{t} = e^{\frac{1}{2}h_t} \epsilon_{t},}
#' where \eqn{\epsilon_t \sim N(0, 1)} and \eqn{h_t} is assumed to evolve according to a random walk
#' \deqn{h_t = h_{t - 1} + u_t,}
#' with \eqn{u_t \sim N(0, \sigma^2)}.
#' 
#' The implementation follows the algorithm of Omori, Chib, Shephard and Nakajima (2007) and performs the
#' following steps:
#' \enumerate{
#'   \item Perform the transformation \eqn{y_t^* = ln(y_t^2 + constant)}.
#'   \item Obtain a sample from the ten-component normal mixture for
#'   approximating the log-\eqn{\chi_1^2} distribution.
#'   \item Obtain a draw of log-volatilities.
#' }
#' 
#' @return A vector of log-volatility draws.
#' 
#' @examples
#' data("us_macrodata")
#' y <- us_macrodata[, "r"]
#' 
#' # Initialise log-volatilites
#' h_init <- log(var(y))
#' h <- rep(h_init, length(y))
#' 
#' # Obtain draw
#' stochvol_ocsn2007(y - mean(y), h, .05, h_init, 0.0001)
#' 
#' @references
#' 
#' Chan, J., Koop, G., Poirier, D. J., & Tobias J. L. (2019). \emph{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.
#' \emph{Journal of Econometrics 140}(2), 425--449. \doi{10.1016/j.jeconom.2006.07.008}
#' 
stochvol_ocsn2007 <- function(y, h, sigma, h_init, constant) {
    .Call(`_bvartools_stochvol_ocsn2007`, y, h, sigma, h_init, constant)
}

#' Stochastic Search Variable Selection
#' 
#' \code{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.
#' 
#' @param a an M-dimensional vector of coefficient draws.
#' @param tau0 an M-dimensional vector of prior standard deviations for restricted
#' coefficients in vector \code{a}.
#' @param tau1 an M-dimensional vector of prior standard deviations for unrestricted
#' coefficients in vector \code{a}.
#' @param prob_prior an M-dimensional vector of prior inclusion probabilites for the coefficients
#' in vector \code{a}.
#' @param include an integer vector specifying the positions of coefficients in vector \code{a}, which should be
#' included in the SSVS algorithm. If \code{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
#' \eqn{\underline{V}^{-1}} and the corresponding vector of inclusion parameters \eqn{\lambda}
#' of the vectorised coefficient matrix \eqn{a = vec(A)} for the VAR model
#' \deqn{y_t = A x_t + u_t,}
#' where \eqn{y_{t}} is a K-dimensional vector of endogenous variables,
#' \eqn{x_{t}} is a vector of explanatory variabes
#' and the error term is \eqn{u_t \sim \Sigma}.
#' 
#' @return A named list containing two components:
#' \item{v_i}{an \eqn{M \times M} inverse prior covariance matrix.}
#' \item{lambda}{an M-dimensional vector of inclusion parameters.}
#' 
#' @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)
#' 
#' @references
#' 
#' George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR model
#' restrictions. \emph{Journal of Econometrics, 142}(1), 553--580.
#' \doi{10.1016/j.jeconom.2007.08.017}
#' 
ssvs <- function(a, tau0, tau1, prob_prior, include = NULL) {
    .Call(`_bvartools_ssvs`, a, tau0, tau1, prob_prior, include)
}

.vardecomp <- function(A, h, type, response) {
    .Call(`_bvartools_vardecomp`, A, h, type, response)
}

# Register entry points for exported C++ functions
methods::setLoadAction(function(ns) {
    .Call(`_bvartools_RcppExport_registerCCallable`)
})

Try the bvartools package in your browser

Any scripts or data that you put into this service are public.

bvartools documentation built on Aug. 31, 2023, 1:09 a.m.