Skip to contents

Bayesian Estimation of Conditional Autoregressive Value at Risk (CAViaR) Models via Adaptive MCMC

High-performance implementation of the CAViaR framework (Engle & Manganelli, 2004) using C++17 and Armadillo linear algebra. This package provides efficient posterior sampling for quantile regression models with autoregressive dynamics, using Robust Adaptive Metropolis (RAM) and Adaptive Random Walk Metropolis-Hastings (ARWMH) algorithms.

[[TOC]]

Features

Component Summary
Models SAV, AS, GARCH, Adaptive, T-CAViaR (5 specifications)
Samplers Robust Adaptive Metropolis (RAM), Adaptive RWMH (ARWMH)
Core C++17 / Armadillo for vectorized log-likelihood evaluation
Forecast get_forecast() for one-step-ahead VaR prediction
Testing Diagnostic suite (load_diagnostics)
Data Included datasets: gerlach (9 assets), manganelli (3 assets)

Note: Production-grade diagnostics (100k+ iterations) are available but excluded from standard CRAN checks to ensure rapid CI feedback.

Quick Start

Installation

Install the latest version of this package with:

remotes::install_gitlab("cacsfre/caviarma")
# Or
devtools::install_gitlab("cacsfre/caviarma")

Development

This project prioritizes reproducibility via a containerized docker development environment (compatible with VS Code).

💡 Create a .devcontainer/.env file to set defaults.

Recommended .devcontainer/.env
CONTAINER_IMAGE=rocker/r-ver:4.5.2
CONTAINER_NAME=caviarma-dev
CONTAINER_DIR=/caviarma
CONTAINER_USER=${USER}
CONTAINER_HOST=${HOSTNAME}

1. Initialize Environment (Host)

After cloning the project, you can use the existing make rules to build, start and attach to a docker devcontainer through a terminal.

git clone https://gitlab.com/cacsfre/caviarma.git
cd caviarma
make devcontainer-build      # Build Docker images
make devcontainer-start      # Start container service
make devcontainer-attach     # Attach shell
ℹ️ VS Code instructions
  1. Launch throuh VS code instead of the above make rules:
git clone https://gitlab.com/cacsfre/caviarma.git
cd caviarma
code .
  1. Launch the Command Palette with Ctrl/Cmd+Shift+P and select Dev Containers: Reopen in Container.

2. Development Tasks (Container)

make check        # R CMD check (CRAN strictness)
make test         # Run unit tests (testthat)
make quick-test   # Run fast diagnostic suite (5k iterations)
make benchmark    # Run performance comparison vs adaptMCMC
make docs         # Build pkgdown documentation site
💡 Make Targets Overview
Host (Container Mgmt) Development (Inside Container)
make devcontainer-build make check
make devcontainer-start make test
make devcontainer-attach make quick-test
make devcontainer-stop make prod-test
make rstudio-start make benchmark
make rstudio-stop make docs
make coverage
make clean

Usage

Estimation

library(caviarma)
data(gerlach)

# Estimate T-CAViaR model (Threshold Autoregressive Quantile)
# Using Robust Adaptive Metropolis (Vihola 2012)
fit <- caviar(
  y       = gerlach[, "USD"],
  q_alpha = 0.05,
  model   = 5,        # T-CAViaR specification
  nsim    = 1e5,      # MCMC iterations
  burn_in = 0.5,      # Burn-in fraction
  method  = "ram"     # Sampler: 'ram' or 'amcmc'
)

# Posterior summary
print(colMeans(fit$theta_hat))

Forecasting

# One-step-ahead Value at Risk prediction
fc <- get_forecast(gerlach[, "USD"], fit)

print(fc$step_1)
# [1] -2.341

Multi-chain Convergence

# Run multiple chains (sequentially) to assess mixing via Gelman-Rubin diagnostics
fit_multi <- caviar(
  y        = gerlach[, "USD"],
  model    = 1,       # Symmetric Absolute Value
  nsim     = 20000,
  n_chains = 4,
  method   = "ram"
)

coda::gelman.diag(fit_multi$chain)

Model Specifications

ID Model Parameters Description
1 SAV 3 Symmetric Absolute Value
2 AS 4 Asymmetric Slope
3 GARCH 3 GARCH-type VaR dynamics
4 Adaptive 1 Logistic smooth transition
5 T-CAViaR 6 Threshold regime switching

Samplers: * RAM: Robust Adaptive Metropolis (Vihola 2012). Coerces acceptance rate to target (0.234). Recommended for high-dimensional or correlated posteriors. * ARWMH: Adaptive Random Walk Metropolis-Hastings (Atchadé & Rosenthal 2005).

Testing

The package’s testing strategy aims to ensure both software correctness and statistical validity.

Automated Unit Tests (CI/CD)

Standard testthat suite designed for Continuous Integration and CRAN compliance. These tests verify function signatures, error handling, and basic numerical correctness without running long MCMC chains.

  • Run via: make test or make check (inside devcontainer)
  • Scope: Input validation, C++ interface stability, helper function logic.

Interactive Diagnostics

An interactive harness built with cli for statistical validation of the MCMC samplers. This suite provides visual feedback (spinners, progress bars, colored status) and is designed for human-in-the-loop verification of convergence.

To launch the interactive suite:

💡 An isolated rstudio container with pre-installed dependencies is available at http://localhost:8787 with make rstudio-start.

# Load the diagnostic harness
load_diagnostics("tests")

# Option A: Quick Validation (Development)
# Runs 5,000 iterations per model to check basic stability
res <- quick_test()

# Option B: Production Validation (Release)
# Runs 100,000 iterations to verify convergence properties
res <- production_test()

# Results summary
summary(res)

# Interactive Visualization
# Generates trace plots, ACF plots, and Geweke diagnostics
# Pauses between models for inspection
plot_test_results(res)

Key Features: * Real-time Feedback: Uses cli for status updates and progress tracking. * Visual Diagnostics: ggplot2 trace plots and autocorrelation analysis. * Statistical Checks: Automated validation of Effective Sample Size (ESS) and Gelman-Rubin statistics. * Interactive Mode: Pauses execution between model checks to allow user inspection of plots.

Data

Dataset Rows Cols Description
gerlach 1105 9 Daily returns: USD, GBP, JPY, CAD, CHF, AUD, etc.
manganelli 2392 3 Daily returns: GM, IBM, S&P500

Requirements

💡 All requirements are pre-installed in the recommended docker devcontainer.

Category Details
R Version ≥ 4.0.0
Compiler C++17 compliant (GCC ≥ 9 / Clang ≥ 12)
Dependencies Rcpp, RcppArmadillo, coda
Suggests testthat, bench, lintr, adaptMCMC, mvtnorm, ggplot2, dplyr, covr
Container Base image: rocker/r-ver:4.5.2

References

  • Engle, R. F., & Manganelli, S. (2004). CAViaR: Conditional Autoregressive Value at Risk by Regression Quantiles. Journal of Business & Economic Statistics, 22(4), 367–381.
  • Vihola, M. (2012). Robust adaptive Metropolis algorithm with coerced acceptance rate. Statistics and Computing, 22(5), 997–1008.
  • Atchadé, Y. F., & Rosenthal, J. S. (2005). On adaptive Markov chain Monte Carlo algorithms. Bernoulli, 11(5), 815–828.