---
title: "10-Factor Portfolio Risk & Tail Estimation"
subtitle: "Evaluating Parameter Uncertainty in Expected Returns Against Analytical Benchmarks"
---
```{r setup}
#| include: false
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(dplyr)
library(gt)
library(scales)
library(ggplot2)
source("R/generate_data.R")
source("R/metropolis_sampler.R")
source("R/risk_functions.R")
source("R/diagnostics.R")
source("R/plots.R")
source("R/analysis.R")
# Run the shared 10-factor analysis (four chains, risk table, exact benchmark, diagnostics)
res <- run_analysis()
s <- res$settings
model_fixture <- res$fixture
post_burn_draws <- res$post_burn
risk_table <- res$risk_table
gen <- synthetic_params()
# Pre-formatted text variables for inline reporting
pct2 <- function(x, digits = 2) sprintf(paste0("%.", digits, "f%%"), x * 100)
alpha_lbl <- sprintf("%.0f\\%%", s$alpha * 100)
acc_rate_txt <- pct2(res$acceptance_rate, 1)
n_draws_txt <- comma(res$n_keep)
prior_exp <- round(-log10(model_fixture$inv_prior_var))
```
### Introduction
This chapter transitions from two-dimensional toy mechanics to a multi-asset portfolio comprising `r xfun::numbers_to_words(res$d)` correlated risk factor exposures—spanning core equity betas, corporate credit carry, duration hedges, and commodities.
To provide a mathematically rigorous audit baseline, we formulate a Bayesian return model with a known closed-form solution. We model daily returns as multivariate normal $\mathbf{R} \sim \mathcal{N}(\boldsymbol{\mu}, \mathbf{\Sigma})$ with a diffuse Gaussian prior on the mean vector $\boldsymbol{\mu} \sim \mathcal{N}(\mathbf{0}, 10^{`r prior_exp`} \mathbf{I})$ and condition the covariance matrix on the empirical sample estimate $\mathbf{\Sigma} = \hat{\mathbf{\Sigma}}_{\text{emp}}$. Under this conjugate structure, the joint posterior distribution of expected returns is analytically known:
$$\boldsymbol{\mu} \mid \mathbf{R}, \mathbf{\Sigma} \sim \mathcal{N}\left(\bar{\mathbf{x}}, \frac{1}{n} \mathbf{\Sigma}\right)$$
While a closed-form solution exists for this specific Gaussian model, using it as our target allows us to directly benchmark MCMC performance. We can compare the empirical draws, standard errors, and credible intervals from our first-principles Metropolis sampler directly against the analytical truth.
### Sampling the 10-Factor Joint Posterior
The sampler processes `r res$n_obs` trading days of observed returns across all `r res$d` assets simultaneously. Starting cold at $\boldsymbol{\mu}_0 = \mathbf{0}$, the chain completes `r comma(s$n_iter)` iterations, discarding the first `r comma(s$burn_in)` iterations to eliminate initialization bias.
The chain operates at an empirical acceptance rate of `{r} acc_rate_txt`.
```{r factor-risk-table, echo = TRUE}
risk_table %>%
gt() %>%
tab_header(
title = md("**10-Asset Portfolio Tail Risk Estimates (1-Day Horizon)**"),
subtitle = "Posterior mean risk metrics and 90% Bayesian credible intervals under parameter uncertainty"
) %>%
cols_label(
metric = "Tail Risk Measure",
mean_estimate = "Posterior Mean",
ci_05 = "5th Percentile",
ci_95 = "95th Percentile"
) %>%
fmt_percent(columns = c(mean_estimate, ci_05, ci_95), decimals = 2) %>%
tab_options(table.font.size = 12)
```
```{r}
#| label: tail-context-stats
#| echo: false
pct_tex <- function(x) sprintf("%.2f\\%%", x * 100)
var_lo_txt <- pct_tex(risk_table$ci_05[1])
var_hi_txt <- pct_tex(risk_table$ci_95[1])
var_spread_bp <- round((risk_table$ci_95[1] - risk_table$ci_05[1]) * 1e4)
var_mean_tex <- pct_tex(risk_table$mean_estimate[1])
es_mean_tex <- pct_tex(risk_table$mean_estimate[2])
es_var_ratio <- sprintf("%.2f", risk_table$mean_estimate[2] / risk_table$mean_estimate[1])
k_var_txt <- sprintf("%.3f", res$exact$k_var)
k_es_txt <- sprintf("%.3f", res$exact$k_es)
z_ci_txt <- sprintf("%.3f", res$exact$z_ci)
```
#### Context: Isolating Parameter Risk in the Mean Vector
Because the return distribution is modeled as multivariate normal and $\mathbf{\Sigma}$ is fixed at the sample estimate, the portfolio tail metrics reflect the properties of Gaussian loss distributions under estimation uncertainty:
1. **Mean Uncertainty Bounds ($\text{VaR}_{`r alpha_lbl`}$):** For an equal-weighted portfolio, parametric Value at Risk is governed by $\text{VaR}_{`r alpha_lbl`} \approx -\mathbf{w}'\boldsymbol{\mu} + `r k_var_txt` \cdot \sigma_p$. Because covariance is held constant, the `r var_spread_bp` basis point spread between the 5th and 95th percentiles ($`r var_lo_txt`$ to $`r var_hi_txt`$) reflects the estimation uncertainty of the portfolio mean alone ($\pm `r z_ci_txt` \cdot \sigma_p / \sqrt{n}$), setting aside covariance uncertainty.
2. **Expected Shortfall Ratio ($\text{ES}_{`r alpha_lbl`}$):** The ratio of Expected Shortfall to Value at Risk ($`r es_mean_tex` / `r var_mean_tex` \approx `r es_var_ratio`$) reflects standard Gaussian tail expectation constants ($\approx `r k_es_txt` / `r k_var_txt`$), adjusted for the portfolio drift. Under a normal likelihood, this metric captures linear downside expectation rather than excess kurtosis or heavy-tailed structural shocks.
### Benchmarking MCMC Against the Exact Posterior
Because this model is conjugate, the exact posterior is known. With the
diffuse prior \\(\\boldsymbol{\\mu} \\sim \\mathcal{N}(\\mathbf{0}, 10^{`r prior_exp`}\\mathbf{I})\\),
the posterior is Gaussian with covariance
\\(\\mathbf{V} = (n\\hat{\\Sigma}^{-1} + 10^{-`r prior_exp`}\\mathbf{I})^{-1}\\). Portfolio VaR and
ES are linear in \\(\\boldsymbol{\\mu}\\), so their exact posteriors are also normal.
That lets us check every MCMC output against the true answer.
```{r}
#| label: exact-benchmark
#| echo: false
ex <- res$exact
fmt_ci <- function(ci) sprintf("%.2f%% – %.2f%%", ci[1] * 100, ci[2] * 100)
```
```{r}
#| label: tbl-tail-benchmark
#| echo: false
tail_bench <- tibble(
Metric = c(sprintf("VaR %.0f%% — mean", s$alpha * 100), sprintf("VaR %.0f%% — 90%% interval", s$alpha * 100),
sprintf("ES %.0f%% — mean", s$alpha * 100), sprintf("ES %.0f%% — 90%% interval", s$alpha * 100)),
MCMC = c(
sprintf("%.3f%%", risk_table$mean_estimate[1] * 100),
fmt_ci(c(risk_table$ci_05[1], risk_table$ci_95[1])),
sprintf("%.3f%%", risk_table$mean_estimate[2] * 100),
fmt_ci(c(risk_table$ci_05[2], risk_table$ci_95[2]))
),
Exact = c(
sprintf("%.3f%%", ex$var * 100),
fmt_ci(ex$var_ci),
sprintf("%.3f%%", ex$es * 100),
fmt_ci(ex$es_ci)
)
)
width_ratio <- res$width_ratio
tail_bench %>%
gt() %>%
tab_header(
title = md("**Tail Risk: MCMC vs. Exact Posterior**"),
subtitle = "Equal-weighted portfolio, 1-day horizon"
) %>%
tab_options(table.font.size = 12)
```
```{r}
#| label: tbl-factor-benchmark
#| echo: false
factor_bench <- res$factor_bench
under <- factor_bench |> filter(SD_Ratio < 1)
n_under <- nrow(under)
sd_rng <- sprintf("%.2f–%.2f", min(under$SD_Ratio), max(under$SD_Ratio))
factor_bench %>%
gt() %>%
tab_header(
title = md("**Per-Factor Posterior: MCMC vs. Exact**"),
subtitle = "Daily expected returns; SD Ratio < 1 means MCMC under-disperses"
) %>%
fmt_percent(columns = c(MCMC_Mean, Exact_Mean, MCMC_SD, Exact_SD), decimals = 3) %>%
fmt_number(columns = c(SD_Ratio, Mean_Error_SD), decimals = 2) %>%
cols_label(
MCMC_Mean = "MCMC Mean", Exact_Mean = "Exact Mean",
MCMC_SD = "MCMC SD", Exact_SD = "Exact SD",
SD_Ratio = "SD Ratio", Mean_Error_SD = "Mean Error (SDs)"
) %>%
tab_options(table.font.size = 12)
```
### What the Benchmark Shows
The MCMC point estimates match the exact posterior: portfolio VaR and ES
means agree to the second decimal place. The **credible intervals** are
narrower than they should be. The MCMC VaR interval is about
`r sprintf("%.0f%%", width_ratio * 100)` of the exact width, so the
sampler understates parameter uncertainty.
`r stringr::str_to_sentence(xfun::numbers_to_words(n_under))` of `r xfun::numbers_to_words(res$d)` factors under-disperse (SD ratio `r sd_rng`). The pattern is
broad-based rather than concentrated in the lowest-ESS factors, consistent
with chains that have explored only part of the posterior.
**Implication for risk reporting:** a poorly mixed sampler can report
the right central estimate while producing credible intervals that are
too narrow, which understates parameter risk. Without a closed-form
benchmark or proper diagnostics, this failure would go unnoticed.
**Parameter Distributions vs. Generative Ground Truth**
Because the fixture was simulated from known parameters, we can compare the sampled MCMC distributions against both the generative population values and the analytical sample estimates.
```{r marginal-plot-tech, fig.cap = "Figure 1: Marginal posterior distribution for Tech Growth expected daily returns."}
plot_posterior_marginals(
draws_df = post_burn_draws,
asset_name = "Tech_Growth",
true_val = gen$ann_returns[gen$asset_names == "Tech_Growth"] / 252
)
```
```{r marginal-plot-treas, fig.cap = "Figure 2: Marginal posterior distribution for 10Y US Treasury returns(Duration hedge)."}
plot_posterior_marginals(
draws_df = post_burn_draws,
asset_name = "US_Treas_10Y",
true_val = gen$ann_returns[gen$asset_names == "US_Treas_10Y"] / 252
)
```
```{r}
#| label: marginal-stats
#| echo: false
# Helper: format a daily return as a percentage string
pct <- function(x, digits = 2) sprintf("%+.*f%%", digits, x * 100)
# Flat-prior posterior SD (sample mean and sigma / sqrt(n))
n_obs <- res$n_obs
x_bar <- res$post_center
post_sd <- res$post_sd
# True values used to generate the data (from synthetic_params() in R/generate_data.R)
true_ann <- setNames(gen$ann_returns, gen$asset_names)
true_tech <- true_ann[["Tech_Growth"]] / 252
true_treas <- true_ann[["US_Treas_10Y"]] / 252
# --- Tech Growth ---
tech_mean <- mean(post_burn_draws$Tech_Growth) # MCMC posterior mean
tech_ci <- quantile(post_burn_draws$Tech_Growth, c(0.05, 0.95))
tech_sd <- post_sd["Tech_Growth"]
tech_z <- (x_bar["Tech_Growth"] - true_tech) / tech_sd
tech_ann <- x_bar["Tech_Growth"] * 252 # annualized sample drift
# --- US Treasuries ---
treas_mean <- mean(post_burn_draws$US_Treas_10Y)
treas_ci <- quantile(post_burn_draws$US_Treas_10Y, c(0.05, 0.95))
treas_sd <- post_sd["US_Treas_10Y"]
treas_z <- (x_bar["US_Treas_10Y"] - true_treas) / treas_sd
# Days of data needed to shrink Tech's posterior SD to the target below
target_sd <- 0.0001
days_needed <- ceiling((sqrt(diag(model_fixture$cov_emp))["Tech_Growth"] / target_sd)^2)
tech_sd_to_mean <- tech_sd / true_tech
```
**Understanding the Marginal Density Plots**
**Tech Growth:** The posterior centers on the sample mean,
approximately `r sprintf("%.2f%%", tech_mean*100)` daily, with a posterior standard
deviation of about `r sprintf("%.2f%%", tech_sd*100)`. The 90% credible interval runs
from `r pct(tech_ci[1])` to `r pct(tech_ci[2])`. The true value used
to generate the data, `r pct(true_tech, 3)` daily (`r sprintf("%+.1f%%", true_ann[["Tech_Growth"]] * 100)` annualized),
lies about `r sprintf("%.1f", tech_z)` posterior standard deviations
below the center.
This is not a sampler error. By chance, this `r n_obs`-day sample
shows a Tech Growth drift of roughly `r sprintf("%.0f%%", tech_ann * 100)`
annualized. The posterior correctly reports what the data support;
the data simply don't support the true value.
**US Treasuries (10Y):** The posterior centers near `r sprintf("%.2f%%", treas_mean*100)`
daily, with a standard deviation of about `r sprintf("%.2f%%", treas_sd*100)` and a 90%
credible interval of `r pct(treas_ci[1])` to `r pct(treas_ci[2])`.
The true value (`r pct(true_treas, 3)` daily) lies about
`r sprintf("%.1f", abs(treas_z))` standard deviations from the center.
Narrowing Tech Growth's uncertainty to `r pct2(target_sd)` daily would take about
`r format(days_needed, big.mark = ",")` trading days of data.
::: {.callout-important icon=false}
## Key Takeaway: Parameter Recovery Is a Data Problem, Not a Sampler Problem
MCMC recovers the **posterior**, not the **truth**. With `r n_obs` daily observations, mean returns are poorly identified: Tech Growth's posterior standard deviation (≈`r pct2(tech_sd)` daily) is `r sprintf("%.1f", tech_sd_to_mean)` times its true mean. Narrowing that uncertainty to about `r pct2(target_sd)` daily would take roughly `r format(days_needed, big.mark=",")` trading days of data. For risk managers, a year of history can't reliably tell a high-drift asset from a low-drift one. That estimation uncertainty is exactly what the VaR and ES credible intervals are meant to capture.
:::