---
title: "Audit & Diagnostics"
subtitle: "Algorithmic Health Checks, Autocorrelation, and Effective Sample Size"
---
```{r setup, echo = TRUE, message = FALSE, warning = FALSE}
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 `r d`-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 `r n_obs` trading days across `r d` 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 `r txt_gen_ret`, volatilities between `r txt_gen_vol`, and correlations from `r txt_gen_cor`.
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 `r d` factors illustrates the scaling challenge where uniform grid search ($10^{`r d`}$ points) becomes computationally impractical, while `r n_obs` observations preserve realistic parameter standard errors for downside modeling.
```{r retrieve-data}
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, `r xfun::numbers_to_words(n_chains)` independent chains are run: one from
\\(\\boldsymbol{\\theta}^{(0)} = \\mathbf{0}\\) and `r xfun::numbers_to_words(n_chains - 1)` from overdispersed
starting points at \\(\\pm `r start_sd`\\) posterior standard deviations from the
posterior center (all high, all low, and mixed).
```{r multi-chain-trace, fig.cap = sprintf("Figure 1: %s chains with ±%d SD starts", stringr::str_to_sentence(xfun::numbers_to_words(n_chains)), start_sd)}
#| fig-width: 10
#| fig-height: 8
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()
```
```{r}
#| label: tbl-rhat
#| echo: false
rhat_tbl <- tibble(
Factor = asset_names,
Split_Rhat = unname(res$rhat[asset_names])
) %>%
mutate(Status = if_else(Split_Rhat < rhat_threshold, "Converged", "Not converged"))
n_fail <- sum(rhat_tbl$Split_Rhat >= rhat_threshold)
max_rhat <- sprintf("%.3f", max(rhat_tbl$Split_Rhat))
factor_names <- c(US_LargeCap = "US Large Cap", US_SmallCap = "US Small Cap", Tech_Growth = "Tech Growth",
EU_Equity = "EU Equity", EM_Equity = "EM Equity", US_Treas_10Y = "US Treasuries (10Y)",
US_Corp_Credit = "US Corporate Credit", Commodities = "Commodities", Gold = "Gold",
Real_Estate = "Real Estate")
max_rhat_factor <- factor_names[[rhat_tbl$Factor[which.max(rhat_tbl$Split_Rhat)]]]
min_rhat <- sprintf("%.3f", min(rhat_tbl$Split_Rhat))
min_rhat_factor <- factor_names[[rhat_tbl$Factor[which.min(rhat_tbl$Split_Rhat)]]]
rhat_tbl %>%
gt() %>%
tab_header(
title = md(sprintf("**Split-R̂ Convergence Audit (%d Chains)**", n_chains)),
subtitle = md(sprintf("Threshold: split-R̂ < %.2f (Vehtari et al., 2021)", rhat_threshold))
) %>%
cols_label(Split_Rhat = md("Split-R̂")) %>%
fmt_number(columns = Split_Rhat, decimals = 3) %>%
tab_options(table.font.size = 12)
```
**Diagnostic Review: Multi-Chain Trace and Split-\\(\\hat{R}\\)**
`r stringr::str_to_sentence(xfun::numbers_to_words(n_chains))` chains were run: one from \\(\\mathbf{0}\\) and `r xfun::numbers_to_words(n_chains - 1)` from starting
points \\(\\pm `r start_sd`\\) posterior standard deviations from the posterior center
(all high, all low, and mixed). `r if (n_fail == d) paste("All", d, "factors fail") else paste(n_fail, "of", d, "factors fail")` the \\(\\hat{R} < `r rhat_threshold`\\) threshold, with a maximum
split-\\(\\hat{R}\\) of `r max_rhat` (`r max_rhat_factor`). The lowest is `r min_rhat_factor` at `r min_rhat`.
The trace also shows that the `r comma(burn_in)`-iteration burn-in is `r if (chain3_reach > burn_in) "insufficient" else "just sufficient"`:
Chain 3, started at \\(-`r start_sd`\\) posterior SDs, does not reach the posterior
center (100-iteration rolling mean within one posterior SD) until iteration `r comma(chain3_reach)`.
Chains started far apart have not fully mixed within `r comma(n_iter)` 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.
```{r acf-plot, fig.cap = "Figure 2: Autocorrelation decay across consecutive MCMC lags for selected portfolio risk factors"}
#| fig-width: 10
#| fig-height: 8
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()
```
```{r}
#| label: acf-stats
#| echo: false
acf_max_lag <- max(acf_combined$lag)
acf_at <- function(f, l) acf_combined$autocorrelation[acf_combined$factor == f & acf_combined$lag == l]
treas_acf <- acf_combined |> filter(factor == "US Treasuries (10Y)", lag > 0)
treas_lag_half <- treas_acf$lag[treas_acf$autocorrelation < 0.5][1]
treas_acf_end <- sprintf("%.2f", acf_at("US Treasuries (10Y)", acf_max_lag))
tech_acf_end <- sprintf("%.2f", acf_at("Tech Growth", acf_max_lag))
```
**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 `r treas_lag_half`, though it is still `r treas_acf_end` at lag `r acf_max_lag`. With low return volatility (`r treas_vol`), the parameter space is compact.
2. **Equity Beta (Tech Growth):** Autocorrelation exhibits high persistence, remaining at `r tech_acf_end` at lag `r acf_max_lag`. Because the scalar proposal step ($\sigma_\epsilon = `r format(proposal_sd, scientific = FALSE)`$) is applied identically across all dimensions, it does not account for the differing scales (Treasuries $\text{SE} \approx$ `r txt_se_treas` vs. Tech $\text{SE} \approx$ `r txt_se_tech`) 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:
```{r ess-table}
# 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)
```
```{r}
#| label: ess-findings-stats
#| echo: false
ess_ref <- unname(res$ess_basic)
eff_tech <- sprintf("%.1f%%", ess_tech / nrow(draws1_clean) * 100)
ess_min <- min(ess_tech, ess_treas, ess_large)
ess_max <- max(ess_tech, ess_treas, ess_large)
# Monte Carlo SE of the posterior mean, as a share of the posterior SD
mcse_share_tech <- sprintf("%.0f%%", 100 / sqrt(ess_tech))
tail_pass <- names(ess_pooled_tail)[ess_pooled_tail >= ess_target]
factor_label <- c(Tech_Growth = "Tech Growth", US_Treas_10Y = "Treasury", US_LargeCap = "US Large Cap")
txt_tail_pass <- if (length(tail_pass) == 0) {
"No factor's tail ESS clears the threshold."
} else {
sprintf("Only the %s tail ESS (%s) clears the threshold.",
paste(factor_label[tail_pass], collapse = " and "),
paste(ess_pooled_tail[tail_pass], collapse = " and "))
}
```
Pooled across all `r xfun::numbers_to_words(n_chains)` chains (`r format(n_total, big.mark=",")` draws), bulk ESS for Tech
Growth is `r ess_pooled_bulk[1]` and tail ESS is `r ess_pooled_tail[1]`,
still well below the recommended `r ess_target`, consistent with the split-\\(\\hat{R}\\)
results above. `r txt_tail_pass`
**Model Validation Findings** <br/>
A model validation review of the ESS diagnostics yields four key takeaways:
1. **Sampling Efficiency Reflects Correlation Drag:** Out of `r comma(n_keep)` post-burn
iterations in Chain 1, Tech Growth yields only `r ess_tech` effective independent draws,
a sampling efficiency of `r eff_tech`. Across the three audited factors, single-chain
ESS ranges from `r ess_min` to `r ess_max`; pooled across `r xfun::numbers_to_words(n_chains)` chains (`r comma(n_total)` draws), bulk ESS
is `r min(ess_pooled_bulk)`–`r max(ess_pooled_bulk)`, `r if (all(ess_pooled_bulk < ess_target)) "still below the recommended" else "compared with the recommended"` `r ess_target` `r if (all(ess_pooled_bulk < ess_target)) "for every factor" else ""`. The acceptance rate of `r txt_acc_c1` 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
`r ess_ref[1]`, `r ess_ref[2]`, and `r ess_ref[3]` 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 `r ess_target` for reliable posterior summaries,
and more for tail quantiles. Current ESS values of `r ess_min`–`r ess_max`
fall well short. Even the posterior mean is imprecise: with an ESS of
`r ess_tech`, the Monte Carlo standard error for Tech Growth is about
`r mcse_share_tech` 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](04-reproducibility.qmd) page for how to rebuild these results and the session information.
```{css, echo = FALSE}
.react_table {
padding-top: 5px;
padding-bottom: 5px;
padding-left: 5px;
padding-right: 5px;
max-height: 600px;
}
```