The Mechanics of Markov Chain Monte Carlo

Benchmarking First-Principles Parameter Exploration in Correlated Factor Spaces

Author

Patrick Lefler

Published

September 24, 2026


Introduction

Markov Chain Monte Carlo (MCMC) is a computational class of algorithms designed to sample from complex, high-dimensional probability distributions when analytical integration is intractable. In portfolio risk management, evaluating joint risk across multiple assets requires characterizing dependent parameters simultaneously—including factor means, volatilities, and cross-asset correlations. For non-standard priors or complex likelihoods, deterministic numerical grid integration scales exponentially with dimension (\(K^D\)), quickly exceeding practical computational limits.

MCMC bypasses deterministic grid mapping by replacing brute-force evaluation with an informed random walk. Guided by transition rules such as the Metropolis-Hastings criterion, the sampler proposes local moves, accepting higher-density coordinates and probabilistically accepting lower-density proposals. Over extended sampling runs, the chain visits parameter states in proportion to their underlying posterior density, mapping the target space without evaluating intractable normalizing constants.

This project builds a Random-Walk Metropolis sampler from first principles in R, with no MCMC libraries, and applies it to the expected returns of a 10-factor portfolio spanning equity, credit, duration, and commodity exposures. The focus is on isolating parameter estimation uncertainty. The model is deliberately chosen to have an exact answer: with multivariate normal returns and covariance fixed at its sample estimate, the posterior is \(\boldsymbol{\mu} \mid \mathbf{R}, \mathbf{\Sigma} \sim \mathcal{N}(\bar{\mathbf{x}}, \frac{1}{n}\mathbf{\Sigma})\). This lets every MCMC output be checked against closed-form truth, providing an auditable environment to examine convergence, proposal efficiency, and the propagation of parameter uncertainty into Value at Risk (VaR) and Expected Shortfall (ES).

The results show how a sampler can look healthy and still understate risk. At a 28.9% acceptance rate, well within conventional targets, the chain reproduces the exact posterior means of VaR (1.05%) and ES (1.33%). The diagnostics tell a different story. All ten factors are at or above the split-\(\hat{R}\) convergence threshold of 1.01 across four chains (maximum 1.057). Pooled across four chains (10,000 draws), bulk Effective Sample Size (ESS) is only 65–316, and tail ESS for Tech Growth is 132, well below the recommended 400. Most important for risk reporting, the MCMC credible interval for VaR is about 17% narrower than the exact interval, so the sampler understates parameter uncertainty.

The cause is a single isotropic proposal step applied to factors with very different scales and strong correlations. The findings show why acceptance rates alone are not sufficient evidence of convergence, and why production risk engines need covariance-preconditioned or gradient-based samplers, validated with multi-chain diagnostics and, where possible, exact benchmarks.

NoteScope & Limitations

This project is a methods demonstration and model-validation case study, not a production risk model. Its results should be read with these constraints in mind:

  • Synthetic data. All results use a simulated 250-day fixture drawn from a known multivariate normal distribution. Real returns show regime shifts, volatility clustering, and structural breaks that this dataset does not.
  • Covariance is fixed. \(\mathbf{\Sigma}\) is set to its sample estimate, so only uncertainty in the mean vector is modeled. Covariance uncertainty, usually the larger driver of VaR error, is excluded, and the reported credible intervals are therefore lower bounds on total parameter risk.
  • Gaussian tails. The normal likelihood cannot represent fat tails or skew. VaR and ES here are parametric Gaussian measures and will understate losses in stressed markets.
  • The sampler has not converged. All ten factors fail the split-\(\hat{R} < 1.01\) test, bulk ESS is 65–316 across four chains, and the VaR credible interval is about 17% too narrow. The chain’s tail estimates should not be used for decisions without a preconditioned or gradient-based sampler.
  • Short run and burn-in. The chains run 3,000 iterations with a 500-draw burn-in, which the trace plots show is insufficient for overdispersed starts.
  • Deliberately simple setting. The model is conjugate, so MCMC is not actually needed here; it is used so that results can be checked against an exact answer. Performance on non-conjugate models (for example, Student-t likelihoods or joint mean–covariance estimation) is untested.
  • Narrow portfolio specification. Results cover one equal-weighted portfolio at a 1-day horizon and a 95% confidence level. Other weights, horizons, or confidence levels are not assessed.
  • Illustrative scaling figures. The grid-versus-MCMC timings in the Dimensional Complexity table are illustrative estimates, not measured benchmarks.

Plain-Language Translation: How It Works

Imagine being placed on a large, pitch-black terrain with only a small flashlight, tasked with mapping the highest peaks and ridges. You cannot view the entire landscape at once, and pacing every square foot on a rigid grid would take an impractical amount of time. Instead, you take incremental random steps. When a step leads uphill toward higher ground, you take it; when a step heads downhill, you occasionally take it anyway to avoid staying confined to a single minor hill. Because you spend most of your time traversing higher ridges and pass quickly through low valleys, your path naturally traces the contours of the landscape. In financial modeling, algorithms like Markov Chain Monte Carlo deploy this sequential exploration to estimate portfolio risk. Rather than evaluating billions of arbitrary grid points across multiple correlated factors, the sampler concentrates computational effort directly in regions of high probability.


The Dimensional Scaling Challenge

When managing risk across multiple correlated factors—equity betas, credit spreads, duration, and commodities—quantifying joint parameter uncertainty is essential. In low dimensions, deterministic numerical quadratures or grid evaluations are trivial. However, as the parameter count (\(D\)) increases, Cartesian grid evaluations scale exponentially (\(K^D\)).

Code
generate_dimension_comparison() %>%
  gt() %>%
  tab_header(
    title = md("**Dimensional Complexity: Grid Search vs. Stochastic Sampling**"),
    subtitle = "Scaling behavior of uniform grid evaluation vs. stochastic simulation"
  ) %>%
  cols_label(
    Dimensions = "Factor Horizon",
    Grid_Points_Per_Axis = "Points / Axis",
    Total_Grid_Evaluations = html("Grid Evaluations (K<sup>D</sup>)"),
    Grid_Feasibility = "Grid Feasibility",
    MCMC_Iterations_Required = "Target MCMC Draws",
    MCMC_Solve_Time = "Observed MCMC Time"
  ) %>%
  text_transform(
  locations = cells_body(columns = Total_Grid_Evaluations),
  fn = function(x) gsub("10\\^(\\d+)", "10<sup>\\1</sup>", x)
) %>%
  tab_style(
    style = cell_text(weight = "bold", color = "#c0392b"),
    locations = cells_body(columns = Total_Grid_Evaluations, rows = 2:3)
  ) %>%
  tab_style(
    style = cell_text(weight = "bold", color = "#27ae60"),
    locations = cells_body(columns = MCMC_Solve_Time)
  ) %>%
  tab_options(table.font.size = 12)
Dimensional Complexity: Grid Search vs. Stochastic Sampling
Scaling behavior of uniform grid evaluation vs. stochastic simulation
Factor Horizon Points / Axis Grid Evaluations (KD) Grid Feasibility Target MCMC Draws Observed MCMC Time
2 Assets (simple model) 10 102 = 100 Instantaneous (<1 ms) 1,000 draws < 0.1 seconds
10 Assets (current model) 10 1010 = 10,000,000,000 Memory Overflow / Impractical 5,000 draws ~1.5 seconds
20 Assets (future model) 10 1020 = 100,000,000,000,000,000,000 Computationally Impossible 10,000 draws ~3.5 seconds

Low-Dimensional Space (\(D = 2\)): A coarse 10-point grid requires only \(10^2 = 100\) function evaluations, making numerical quadratures instantaneous.

Moderate Parameter Space (\(D = 10\)): Uniform evaluation along each axis requires \(10^{10}\) calculations (10 billion operations)—creating significant runtime bottlenecks in standard computing environments, whereas stochastic sampling traverses the distribution in seconds.

Full Covariance Horizon (\(D = 20\)): Modeling 20 factor means alongside full cross-asset covariances involves \(D + D(D+1)/2 = 230\) distinct parameters. Evaluating such spaces on uniform deterministic grids is computationally intractable, making stochastic simulation essential for non-conjugate structures.


The Random Walk Engine

Markov Chain Monte Carlo navigates probability distributions via sequential, localized transitions:

  1. Propose a Move: The chain samples a candidate coordinate \(\theta^*\) from a proposal distribution centered on the current state \(\theta^{(t)}\).
  2. Evaluate Density Ratio: It computes the target posterior probability ratio between candidate and current locations.
  3. Accept or Reject: Proposals into higher-density regions are accepted; lower-density moves are accepted probabilistically, enabling the chain to explore parameter tails.
NoteThe Metropolis-Hastings Random Walk

Evaluating joint portfolio risk across multiple interdependent assets presents substantial computational complexity when models deviate from simple analytical assumptions. Calculating every joint market permutation across a fine grid requires billions of evaluations, creating an operational bottleneck. The Metropolis-Hastings algorithm resolves this by deploying a sequential “digital scout.” Rather than attempting to evaluate the entire parameter space uniformly, the algorithm takes incremental steps through potential states. If a proposed move discovers a region of higher probability, the chain transitions there; if it steps toward a lower-probability scenario, it still accepts the move occasionally to ensure thorough exploration. Over thousands of iterations, the algorithm visits parameter combinations in proportion to their joint posterior probability. This produces an empirical distribution of parameter uncertainty. For executive decision-makers, this turns otherwise intractable high-dimensional estimation into a practical sampling process, providing an empirical baseline for setting risk capital and stress limits.

Code
#| fig-width: 10
#| fig-height: 10

plot_random_walk_2d(hero_chain$draws, n_steps = 180)

Figure 1: Metropolis-Hastings chain traversing a correlated bivariate parameter space.

Figure 1: Metropolis-Hastings chain traversing a correlated bivariate parameter space.

Traversal Mechanics

  • Stationary Convergence: Initializing from an arbitrary coordinate in the outer tail, the chain transitions toward the high-density contour core.
  • Proportional Dwell Time: Once stationary, the chain continues moving, spending time across regions in proportion to target posterior density.

Project Structure & Roadmap

This project demonstrates the implementation, diagnostic auditing, and tail-risk application of first-principles MCMC:

  • The Metropolis Engine: The R implementation from scratch (without MCMC libraries), detailing acceptance ratios and proposal step-size calibration.
  • Portfolio Risk Model: Sampling the 10-factor posterior under fixed covariance to evaluate Value at Risk (VaR) and Expected Shortfall (ES), benchmarked against the exact closed-form posterior.
  • Audit & Diagnostics: Four-chain convergence checks with split-\(\hat{R}\), autocorrelation decay, and Effective Sample Size (ESS) audits cross-checked against the posterior package.
  • Reproducibility: How to rebuild the site, the software environment, data checksum, seeds, and known limitations.