Algorithmic Health Checks, Autocorrelation, and Effective Sample Size

Code
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(dplyr)
library(ggplot2)
library(gt)
library(posterior)
library(reactable)
library(scales)
library(tidyverse)

source("R/generate_data.R")
source("R/metropolis_sampler.R")
source("R/risk_functions.R")
source("R/plots.R")
source("R/diagnostics.R")
source("R/analysis.R")

# Run the shared 10-factor analysis (four chains, risk table, exact benchmark, diagnostics)
res <- run_analysis()
n_iter         <- res$settings$n_iter
burn_in        <- res$settings$burn_in
proposal_sd    <- res$settings$proposal_sd
start_sd       <- res$settings$start_sd
rhat_threshold <- res$settings$rhat_threshold
ess_target     <- res$settings$ess_target

d            <- res$d
asset_names  <- res$asset_names
n_obs        <- res$n_obs
n_keep       <- res$n_keep
all_chains   <- res$chains
n_chains     <- res$n_chains
draws_clean  <- res$draws_clean
draws1_clean <- res$post_burn
chain1       <- all_chains[[1]]
post_center  <- res$post_center
post_sd      <- res$post_sd

ess_tech  <- res$ess_chain1[["Tech_Growth"]]
ess_treas <- res$ess_chain1[["US_Treas_10Y"]]
ess_large <- res$ess_chain1[["US_LargeCap"]]

# Inline values for the text
fmt_pct <- function(x, digits = 1) sprintf(paste0("%.", digits, "f%%"), x * 100)
txt_acc_c1 <- fmt_pct(chain1$acceptance_rate)

gen <- synthetic_params()
gen_cor <- gen$Rho[upper.tri(gen$Rho)]
txt_gen_ret <- paste(fmt_pct(min(gen$ann_returns)), "and", fmt_pct(max(gen$ann_returns)))
txt_gen_vol <- paste(fmt_pct(min(gen$ann_vols)), "and", fmt_pct(max(gen$ann_vols)))
txt_gen_cor <- sprintf("%.2f to %+.2f", min(gen_cor), max(gen_cor))
treas_vol   <- fmt_pct(gen$ann_vols[gen$asset_names == "US_Treas_10Y"], 0)
txt_se_treas <- fmt_pct(post_sd[["US_Treas_10Y"]], 2)
txt_se_tech  <- fmt_pct(post_sd[["Tech_Growth"]], 2)

# Chain 3 (the "all low" start): first iteration at which its 100-iteration
# rolling mean of Tech Growth is within one posterior SD of the posterior center
z3 <- (all_chains[[3]]$draws$Tech_Growth - post_center[["Tech_Growth"]]) / post_sd[["Tech_Growth"]]
roll3 <- stats::filter(z3, rep(1 / 100, 100), sides = 1)
chain3_reach <- which(abs(roll3) < 1)[1]

Introduction

In institutional risk management, stochastic simulation models must be transparent and auditable. When using Markov Chain Monte Carlo to evaluate high-dimensional portfolio distributions, point estimates alone are insufficient. Because MCMC generates a sequence of dependent parameter proposals rather than independent samples, model validation requires empirical verification of convergence, parameter space exploration, and statistical sample efficiency.

This audit page examines the algorithmic health checks for the 10-dimensional Gaussian random walk. We evaluate multi-chain convergence, measure autocorrelation decay across factor lags, and apply Geyer’s initial sequence estimator to compute robust Effective Sample Size (ESS). This diagnostic audit outlines both the utility of Random-Walk Metropolis and the operational limitations encountered when isotropic proposals are applied to correlated factor distributions.

Dataset Architecture & Methodological Rationale

The analysis utilizes a fixed synthetic fixture of 250 trading days across 10 correlated asset classes (data/synthetic_returns.csv), generated from a known multivariate normal distribution \(\mathcal{N}(\boldsymbol{\mu}, \mathbf{\Sigma})\) calibrated to realistic risk levels: annualized returns between 3.5% and 11.0%, volatilities between 8.0% and 26.0%, and correlations from -0.30 to +0.78.

Using a synthetic baseline provides a controlled ground truth. In empirical market feeds, true data-generating distributions are obscured by regime shifts, structural breaks, and survivorship bias. By defining a synthetic population, we establish an explicit benchmark to test whether the sampler recovers sample parameters. Evaluating 10 factors illustrates the scaling challenge where uniform grid search (\(10^{10}\) points) becomes computationally impractical, while 250 observations preserve realistic parameter standard errors for downside modeling.

Code
synthetic_data_returns <- as_tibble(read_csv("data/synthetic_returns.csv", show_col_types = FALSE))

reactable(synthetic_data_returns,
  defaultPageSize = 10,
  highlight   = TRUE,
  striped     = TRUE,
  resizable   = TRUE,
  defaultColDef = colDef(
    align = "left",
    format = colFormat(digits = 7),
    width = 110
  ),
  columns = list(
    trading_day = colDef(align = "center", format = colFormat(digits = 0))
  ),
  class = ".react_table",
  theme = reactableTheme(
    borderColor = "#dfe2e5",
    stripedColor = "#f6f8fa",
    style = list(fontSize = "13px", fontFamily = "Roboto, Helvetica, Arial, sans-serif"),
    searchInputStyle = list(width = "100%")
  )
)

The Diagnostic Framework

In quantitative validation workflows, evaluating an MCMC sampler involves three core criteria:

  1. Stationarity: The chain has converged to the target distribution and is invariant to initialization coordinates.

  2. Mixing Across Dimensions: The chain traverses parameter space without prolonged freezing or sluggish diffusion.

  3. Effective Sample Size (ESS): Autocorrelation decays rapidly enough to provide sufficient independent information for quantile estimation (Vehtari et al., 2021).

Multi-Chain Mixing Verification

To evaluate convergence, four independent chains are run: one from \(\boldsymbol{\theta}^{(0)} = \mathbf{0}\) and three from overdispersed starting points at \(\pm 3\) posterior standard deviations from the posterior center (all high, all low, and mixed).

Code
trace_df <- bind_rows(lapply(seq_along(all_chains), function(i)
  all_chains[[i]]$draws %>% select(iteration, Tech_Growth) %>%
    mutate(Chain = paste("Chain", i))))


ggplot(trace_df, aes(x = iteration, y = Tech_Growth, color = Chain)) +
  geom_line(alpha = 0.75, linewidth = 0.5) +
  geom_vline(xintercept = burn_in, linetype = "dashed", color = "#c0392b", linewidth = 0.8) +
  annotate("text", x = burn_in + 20, y = max(trace_df$Tech_Growth) * 0.9, label = sprintf("End of Burn-In (%d)", burn_in), fontface = "bold", color = "#c0392b", hjust = 0, size = 3.5) +
  scale_color_manual(values = c("#1b4f72", "#e67e22", "#27ae60", "#8e44ad")) +
  scale_y_continuous(labels = label_percent(accuracy = 0.01)) +
  labs(
    title = "Multi-Chain Stationarity Diagnostic: Tech Growth Exposure",
    subtitle = sprintf(
      "%s chains from overdispersed starts; Chain 3 %s the posterior center by the end of burn-in",
      stringr::str_to_sentence(xfun::numbers_to_words(n_chains)), if (chain3_reach > burn_in) "has not reached" else "has reached"
    ),
    x = "Iteration Step",
    y = "Daily Expected Return",
    color = "Sampler Execution"
  ) +
  theme_mcmc()

Figure 1: Four chains with ±3 SD starts

Figure 1: Four chains with ±3 SD starts
Table 1
Split-R̂ Convergence Audit (4 Chains)
Threshold: split-R̂ < 1.01 (Vehtari et al., 2021)
Factor Split-R̂ Status
US_LargeCap 1.030 Not converged
US_SmallCap 1.019 Not converged
Tech_Growth 1.057 Not converged
EU_Equity 1.014 Not converged
EM_Equity 1.044 Not converged
US_Treas_10Y 1.010 Not converged
US_Corp_Credit 1.019 Not converged
Commodities 1.027 Not converged
Gold 1.012 Not converged
Real_Estate 1.039 Not converged

Diagnostic Review: Multi-Chain Trace and Split-\(\hat{R}\)

Four chains were run: one from \(\mathbf{0}\) and three from starting points \(\pm 3\) posterior standard deviations from the posterior center (all high, all low, and mixed). All 10 factors fail the \(\hat{R} < 1.01\) threshold, with a maximum split-\(\hat{R}\) of 1.057 (Tech Growth). The lowest is US Treasuries (10Y) at 1.010.

The trace also shows that the 500-iteration burn-in is insufficient: Chain 3, started at \(-3\) posterior SDs, does not reach the posterior center (100-iteration rolling mean within one posterior SD) until iteration 680.

Chains started far apart have not fully mixed within 3,000 iterations, which is consistent with the low ESS reported below.


Autocorrelation Decay Analysis

Because Metropolis-Hastings operates via local proposals, consecutive draws exhibit positive serial dependence.

Code
calc_acf_df <- function(vec, factor_name, max_lag = 35) {
  res <- acf(vec, lag.max = max_lag, plot = FALSE)
  tibble(
    lag = as.numeric(res$lag),
    autocorrelation = as.numeric(res$acf),
    factor = factor_name
  )
}

acf_combined <- bind_rows(
  calc_acf_df(draws1_clean$Tech_Growth, "Tech Growth"),
  calc_acf_df(draws1_clean$US_Treas_10Y, "US Treasuries (10Y)"),
  calc_acf_df(draws1_clean$US_LargeCap, "US Large Cap")
)

ggplot(acf_combined, aes(x = lag, y = autocorrelation, fill = factor)) +
  geom_col(position = "dodge", width = 0.7) +
  geom_hline(yintercept = 0.10, linetype = "dashed", color = "#7f8c8d") +
  scale_fill_manual(values = c("#2c3e50", "#2980b9", "#27ae60")) +
  labs(
    title = "Autocorrelation Decay by Factor",
    subtitle = "Autocorrelation decay profiles highlight the impact of isotropic proposal scaling on correlated parameters",
    x = "Lag Step",
    y = "Autocorrelation Coefficient",
    fill = "Risk Factor"
  ) +
  theme_mcmc()

Figure 2: Autocorrelation decay across consecutive MCMC lags for selected portfolio risk factors

Figure 2: Autocorrelation decay across consecutive MCMC lags for selected portfolio risk factors

Diagnostic Analysis: The Proposal-Geometry Mismatch

The autocorrelation profiles highlight an operational challenge when using an unscaled, isotropic proposal (\(\sigma_\epsilon \mathbf{I}\)) across correlated dimensions:

  1. Treasuries (10Y): Autocorrelation decays fastest of the three, dropping below 0.50 at lag 8, though it is still 0.23 at lag 35. With low return volatility (8%), the parameter space is compact.
  2. Equity Beta (Tech Growth): Autocorrelation exhibits high persistence, remaining at 0.66 at lag 35. Because the scalar proposal step (\(\sigma_\epsilon = 0.00032\)) is applied identically across all dimensions, it does not account for the differing scales (Treasuries \(\text{SE} \approx\) 0.03% vs. Tech \(\text{SE} \approx\) 0.10%) or the correlated geometry of the target density. As a result, the chain traverses the principal variance axes slowly, leading to persistent serial correlation.

Robust Effective Sample Size (ESS) Audit

To avoid truncation bias in persistent chains, Effective Sample Size is computed using Geyer’s initial sequence estimator across all post-burn draws:

Code
# Pooled ESS across all chains (posterior::ess_bulk / ess_tail), computed in R/analysis.R
ess_pooled_bulk <- res$ess_bulk
ess_pooled_tail <- res$ess_tail

n_total <- nrow(draws1_clean) * length(draws_clean)


tibble(
  Asset_Class = c("Equity Beta (Tech Growth)", "Duration Hedge (10Y Treasuries)", "Core Market (US Large Cap)"),
  Total_Post_Burn_Draws = rep(nrow(draws1_clean), 3),
  Effective_Sample_Size = c(ess_tech, ess_treas, ess_large),
    Pooled_Bulk_ESS = ess_pooled_bulk,
  Pooled_Tail_ESS = ess_pooled_tail,
  Sampling_Efficiency = c(ess_tech, ess_treas, ess_large) / nrow(draws1_clean),
  Autocorrelation_Lag10 = c(
    acf(draws1_clean$Tech_Growth, plot = FALSE)$acf[11],
    acf(draws1_clean$US_Treas_10Y, plot = FALSE)$acf[11],
    acf(draws1_clean$US_LargeCap, plot = FALSE)$acf[11]
  )
) %>%
  gt() %>%
  tab_header(
    title = md("**MCMC Chain Efficiency & Effective Sample Size Audit**"),
    subtitle = "Robust Geyer initial-sequence evaluation of chain correlation and sampling capacity"
  ) %>%
  cols_label(
    Asset_Class = "Risk Factor Asset",
    Total_Post_Burn_Draws = "Post-Burn Draws",
    Effective_Sample_Size = "ESS (Chain 1)",
    Pooled_Bulk_ESS = "Bulk ESS (4 chains)",
    Pooled_Tail_ESS = "Tail ESS (4 chains)",
    Sampling_Efficiency = "Efficiency Ratio",
    Autocorrelation_Lag10 = "Lag-10 Autocorr"
  ) %>%
  fmt_integer(columns = c(Total_Post_Burn_Draws, Effective_Sample_Size)) %>%
  fmt_percent(columns = Sampling_Efficiency, decimals = 1) %>%
  fmt_number(columns = Autocorrelation_Lag10, decimals = 3) %>%
  tab_options(table.font.size = 12)
MCMC Chain Efficiency & Effective Sample Size Audit
Robust Geyer initial-sequence evaluation of chain correlation and sampling capacity
Risk Factor Asset Post-Burn Draws ESS (Chain 1) Bulk ESS (4 chains) Tail ESS (4 chains) Efficiency Ratio Lag-10 Autocorr
Equity Beta (Tech Growth) 2,500 16 65 132 0.6% 0.874
Duration Hedge (10Y Treasuries) 2,500 65 316 640 2.6% 0.441
Core Market (US Large Cap) 2,500 22 93 244 0.9% 0.722

Pooled across all four chains (10,000 draws), bulk ESS for Tech Growth is 65 and tail ESS is 132, still well below the recommended 400, consistent with the split-\(\hat{R}\) results above. Only the Treasury tail ESS (640) clears the threshold.

Model Validation Findings
A model validation review of the ESS diagnostics yields four key takeaways:

  1. Sampling Efficiency Reflects Correlation Drag: Out of 2,500 post-burn iterations in Chain 1, Tech Growth yields only 16 effective independent draws, a sampling efficiency of 0.6%. Across the three audited factors, single-chain ESS ranges from 16 to 65; pooled across four chains (10,000 draws), bulk ESS is 65–316, still below the recommended 400 for every factor. The acceptance rate of 28.9% falls within the conventional range, which shows that a healthy acceptance rate does not guarantee good mixing. The single, isotropic proposal step is too small for high-variance factors such as Tech Growth, so the chain crosses their posterior range slowly.

  2. Independent Verification of the Estimator: ESS values from compute_ess_robust() (Geyer initial monotone sequence) were cross-checked against posterior::ess_basic(), which returned 14.5, 55.2, and 20.5 for Tech Growth, Treasuries, and US Large Cap. The two estimators agree closely. The reference package reads slightly lower because it uses split chains and a more conservative truncation rule.

  3. Quantile Precision Considerations: Vehtari et al. (2021) recommend an ESS of at least 400 for reliable posterior summaries, and more for tail quantiles. Current ESS values of 16–65 fall well short. Even the posterior mean is imprecise: with an ESS of 16, the Monte Carlo standard error for Tech Growth is about 25% of a posterior standard deviation. The 5th and 95th percentiles that define the VaR and Expected Shortfall credible intervals are less stable still. The exact-posterior benchmark on the Portfolio Risk page shows the practical result: the MCMC credible intervals are too narrow, understating parameter risk.

  4. Paths to Algorithmic Improvement: This diagnostic shows the trade-offs of first-principles isotropic Random-Walk Metropolis. In production risk environments, sampling efficiency can be improved by:

    • Proposal Covariance Preconditioning: Scaling jumps to the posterior geometry using \(\boldsymbol{\Sigma}_{\text{prop}} = \frac{2.38^2}{d}\hat{\boldsymbol{\Sigma}}_{\text{post}}\) (Roberts & Rosenthal, 2001).
    • Adaptive Sampling: Adaptive Metropolis algorithms that learn the posterior covariance during the run (Haario et al., 2001).
    • Gradient-Based Methods: Hamiltonian Monte Carlo (HMC) or NUTS, which use gradient information to move efficiently through high-dimensional, correlated posteriors.

See the exact-posterior benchmark on the Portfolio Risk page for the effect of low ESS on credible-interval width.

See the Reproducibility page for how to rebuild these results and the session information.