// RISK · MODULE 07/12

Quantitative risk: from VaR to the risk copilot

Exact VaR and Expected Shortfall, stress testing, and the LLM as an explanation layer, never a calculator.

Level intermediate-advancedEdition jul 2026Leer en español


Modules 4 through 6 built the understanding layer: data sources, document RAG, and prompts with structured output. With this module the course enters Block III —reason and decide— and changes register: exact mathematics takes the lead here, and the LLM is confined to the role the golden rule assigns it (§1.2.2): narrate, orchestrate, and alert, never compute.

7.1 Risk measurement with exact formulas

Quantitative risk management rests on a small set of formulas whose provenance is verifiable: the J.P. Morgan/Reuters RiskMetrics Technical Document (1996), the Basel Committee documents (d450, d457), and the canonical academic literature (Rockafellar–Uryasev, Kupiec, Christoffersen, Bollerslev). This module presents them exactly as they appear in the primary sources, with the positive-loss convention: rtr_t denotes the log return on day tt; α\alpha is the tail significance level (0.01 for 99% VaR); zα=Φ−1(1−α)z_\alpha = \Phi^{-1}(1-\alpha) is the standard normal quantile of the right loss tail; φ\varphi and Φ\Phi are the standard normal density and distribution function.

7.1.1 VaR, Expected Shortfall, and validation

Parametric VaR (delta-normal). Under normal returns, VaR at confidence 1−α1-\alpha and horizon hh days for a portfolio of value VV with daily mean μ\mu and daily volatility σ\sigma is (graphrag.com):

VaRα(h)=V(zα σh−μh),zα=Φ−1(1−α)\mathrm{VaR}_{\alpha}(h) = V\left(z_{\alpha}\,\sigma\sqrt{h} - \mu h\right), \qquad z_{\alpha} = \Phi^{-1}(1-\alpha)

with z0,05=1,645z_{0{,}05} = 1{,}645 (95%) and z0,01=2,326z_{0{,}01} = 2{,}326 (99%). Time scaling applies the square-root-of-time rule, σ(h)=σh\sigma(h) = \sigma\sqrt{h}, valid only under i.i.d. returns. For a multi-asset portfolio with weights ww and covariance matrix Σ\Sigma (The Database for Multimodal AI):

σp2=w⊤Σw,VaRα=V⋅zαw⊤Σw\sigma_p^2 = w^{\top}\Sigma w, \qquad \mathrm{VaR}_{\alpha} = V \cdot z_{\alpha}\sqrt{w^{\top}\Sigma w}

Historical VaR (historical simulation). The historical factor moves of the last TT days (typically 250) are reapplied to the current portfolio and the hypothetical P&Ls are sorted L(1)≤L(2)≤⋯≤L(T)L_{(1)} \le L_{(2)} \le \dots \le L_{(T)}; VaR is the empirical quantile (arXiv.org):

VaRαHS=L(⌈T(1−α)⌉)\mathrm{VaR}_{\alpha}^{\mathrm{HS}} = L_{(\lceil T(1-\alpha) \rceil)}

With T=250T = 250 and α=0,05\alpha = 0{,}05, the 95% VaR is the 13th worst day (0,05×250=12,50{,}05 \times 250 = 12{,}5). It requires no distributional assumptions and captures the sample tails, but at 99% with 250 days there are only about 2.5 tail observations, which produces high sampling variation and slow response to regime changes (arXiv.org).

Monte Carlo VaR and FHS. NN factor paths are simulated under a calibrated model (GBM, Student-t, GARCH), the portfolio is revalued, and the quantile of the simulated distribution is taken (arXiv.org):

VaRαMC=F^L,N−1(1−α)\mathrm{VaR}_{\alpha}^{\mathrm{MC}} = \hat{F}^{-1}_{L,N}(1-\alpha)

where F^L,N\hat{F}_{L,N} is the empirical CDF of the NN simulated losses. The Filtered Historical Simulation variant (Barone-Adesi, Bourgoin, and Giannopoulos) fits a GARCH(1,1), extracts the standardized residuals zt=rt/σtz_t = r_t/\sigma_t, and simulates r~=σ^t+1z∗\tilde r = \hat\sigma_{t+1} z^{*} by resampling z∗z^{*} with replacement; comparative evidence shows that normal Monte Carlo underestimates the left tail relative to FHS (arXiv.org).

Expected Shortfall / CVaR. For a loss variable LL with continuous CDF, VaR and ES are defined as (🦜️🔗 LangChain):

VaRα(L)=inf⁡{x:FL(x)≥1−α},ESα(L)=1α∫0αVaRu(L) du=E ⁣[L∣L≥VaRα(L)]\mathrm{VaR}_{\alpha}(L) = \inf\{x : F_L(x) \ge 1-\alpha\}, \qquad \mathrm{ES}_{\alpha}(L) = \frac{1}{\alpha}\int_{0}^{\alpha} \mathrm{VaR}_{u}(L)\,du = \mathbb{E}\!\left[L \mid L \ge \mathrm{VaR}_{\alpha}(L)\right]

Under normality a closed form exists:

ESα=σ φ(zα)α−μ\mathrm{ES}_{\alpha} = \sigma\,\frac{\varphi(z_{\alpha})}{\alpha} - \mu

At 99% the factor is φ(2,326)/0,01≈2,665\varphi(2{,}326)/0{,}01 \approx 2{,}665; at 97.5%, φ(1,960)/0,025=0,0584/0,025=2,338\varphi(1{,}960)/0{,}025 = 0{,}0584/0{,}025 = 2{,}338, the central figure in the FRTB design (§7.2). Unlike VaR, ES is a coherent measure in the sense of Artzner et al. (1999): it satisfies subadditivity, the property VaR violates (🦜️🔗 LangChain). The Rockafellar–Uryasev (2000) variational representation turns CVaR estimation and optimization into linear programming (🦜️🔗 LangChain):

CVaR^β=min⁡c∈R{c+11−β⋅1T∑t=1T(Lt−c)+}\widehat{\mathrm{CVaR}}_{\beta} = \min_{c \in \mathbb{R}} \left\{ c + \frac{1}{1-\beta}\cdot\frac{1}{T}\sum_{t=1}^{T}(L_t - c)_{+} \right\}

with (x)+=max⁡(x,0)(x)_+ = \max(x, 0); the minimizer c∗c^{*} is VaR itself. The empirical estimator in historical simulation is simply the average of the ⌊Tα⌋\lfloor T\alpha \rfloor worst losses.

VaR backtesting. An unvalidated VaR model is an opinion. With the exception indicator It=1{Lt>VaRt}I_t = \mathbf{1}\{L_t > \mathrm{VaR}_t\}, Kupiec's (1995) proportion-of-failures test contrasts the observed rate N/TN/T against the nominal pp (CurvedTrading):

LRPOF=−2ln⁡ ⁣[(1−p)T−NpN(1−NT)T−N(NT)N]  ∼  χ12LR_{POF} = -2\ln\!\left[\frac{(1-p)^{T-N}p^{N}}{\left(1-\frac{N}{T}\right)^{T-N}\left(\frac{N}{T}\right)^{N}}\right] \;\sim\; \chi^2_1
Kupiec POF test with T = 250 and p = 1 %LR_POF: 0 → 5.03, 2 → 0.11, 4 → 0.77, 6 → 3.56, 8 → 7.73, 10 → 1302468101214012345678910Exceptions observed in 250 days (N)LR_POFcritical χ²₁(0.95) = 3.84expected: 2.53.565.50
Figure 7.C. Kupiec’s LR_POF statistic for a 99 % VaR over 250 days: with 6 exceptions (3.56) the model passes; with 7 (5.50) it is rejected. The threshold is sharp. Own elaboration with the module’s formula.

7.1.2 Volatility: the raw material of every risk number

Realized volatility. With MM evenly spaced intraday observations of the log price and returns rt,i=pt,i−pt,i−1r_{t,i} = p_{t,i} - p_{t,i-1} (QVeris AI):

RVt=∑i=1Mrt,i2,RVolt=RVtRV_t = \sum_{i=1}^{M} r_{t,i}^{2}, \qquad \mathrm{RVol}_t = \sqrt{RV_t}

Under a diffusion with jumps, RVtRV_t is a consistent estimator of quadratic variation as M→∞M \to \infty (Andersen–Bollerslev); with microstructure noise, the practical optimal frequency is 5 minutes (QVeris AI).

EWMA / RiskMetrics. The recursion from the RiskMetrics Technical Document (4th ed., 1996) is (graphrag.com):

σt2=λ σt−12+(1−λ) rt−12,λ=0,94 (daily),λ=0,97 (monthly)\sigma_t^2 = \lambda\,\sigma_{t-1}^2 + (1-\lambda)\,r_{t-1}^2, \qquad \lambda = 0{,}94 \text{ (daily)},\quad \lambda = 0{,}97 \text{ (monthly)}

Expanded, σt2=(1−λ)∑i=1∞λi−1rt−i2\sigma_t^2 = (1-\lambda)\sum_{i=1}^{\infty}\lambda^{i-1} r_{t-i}^2: decaying geometric weights with effective memory ≈1/(1−λ)≈17\approx 1/(1-\lambda) \approx 17 days for λ=0,94\lambda = 0{,}94. It is an IGARCH with no mean reversion (ω=0\omega = 0, α+β=1\alpha+\beta = 1), and its multivariate version Σt=λΣt−1+(1−λ) rt−1rt−1⊤\Sigma_t = \lambda\Sigma_{t-1} + (1-\lambda)\, r_{t-1} r_{t-1}^{\top} is always positive semidefinite (graphrag.com).

EWMA weights by age of the returnλ = 0.94 (daily, RiskMetrics): 1 → 6.00 %, 11 → 3.23 %, 21 → 1.74 %, 31 → 0.94 %, 41 → 0.50 %, 51 → 0.27 %, 60 → 0.16 %. λ = 0.97 (monthly): 1 → 3.00 %, 11 → 2.21 %, 21 → 1.63 %, 31 → 1.20 %, 41 → 0.89 %, 51 → 0.65 %, 60 → 0.50 %λ = 0.94 (daily, RiskMetrics)λ = 0.97 (monthly)0 %1 %2 %3 %4 %5 %6 %1102030405060Age of the return (days)Weight in today’s varianceeffective memory ≈ 17 days
Figure 7.B. With λ = 0.94 yesterday’s return weighs 6 % and after 17 days the weight is just over a third of the initial one; with λ = 0.97 memory is longer and flatter. Own elaboration with the RiskMetrics recursion.

GARCH(1,1). The Engle (1982) and Bollerslev (1986) model introduces mean reversion (Bright Data):

σt2=ω+α εt−12+β σt−12,ω>0, α,β≥0, α+β<1\sigma_t^2 = \omega + \alpha\,\varepsilon_{t-1}^2 + \beta\,\sigma_{t-1}^2, \qquad \omega>0,\ \alpha,\beta\ge 0,\ \alpha+\beta<1

The unconditional variance (long-run level) is σˉ2=ω1−α−β\bar\sigma^2 = \dfrac{\omega}{1-\alpha-\beta}, and the kk-step-ahead forecast reverts geometrically toward it:

Et[σt+k2]=σˉ2+(α+β)k−1(σt+12−σˉ2)\mathbb{E}_t[\sigma_{t+k}^2] = \bar\sigma^2 + (\alpha+\beta)^{k-1}\left(\sigma_{t+1}^2 - \bar\sigma^2\right)

The sum α+β\alpha+\beta measures the persistence of volatility shocks; EWMA is the limiting case ω=0\omega = 0, α+β=1\alpha+\beta = 1 (Bright Data). Numerical case. With α+β=0,97\alpha+\beta = 0{,}97, a volatility spike that doubles the long-run level (σt+12=2σˉ2\sigma_{t+1}^2 = 2\bar\sigma^2) takes k≈ln⁡(0,5)/ln⁡(0,97)≈23k \approx \ln(0{,}5)/\ln(0{,}97) \approx 23 days to reduce the excess by half.

Maximum drawdown and recovery asymmetry. Let VtV_t be the equity curve and V‾t=max⁡s≤tVs\overline{V}_t = \max_{s\le t} V_s the running maximum; the drawdown is Dt=(Vt−V‾t)/V‾t≤0D_t = (V_t - \overline{V}_t)/\overline{V}_t \le 0 and (Investopedia):

MDDT=min⁡0≤t≤TVt−V‾tV‾t\mathrm{MDD}_T = \min_{0\le t\le T} \frac{V_t - \overline{V}_t}{\overline{V}_t}

Recovery is asymmetric: a loss dd requires a gain g=d1−dg = \dfrac{d}{1-d} to return to the peak — a 50% drop demands a 100% rise, and a 90% drop, a 900% one (Investopedia). It is the risk metric investors actually feel, and the one anchoring the Calmar and Sterling ratios.

7.1.3 Risk-adjusted performance ratios

The full catalog, with its conventions and documented pitfalls:

Sharpe. Introduced as the reward-to-variability ratio (Sharpe, 1966) (AlphaLog):

S=Rp−Rfσp,Sanual=Sdiario252    (solo bajo i.i.d.)S = \frac{R_p - R_f}{\sigma_p}, \qquad S_{\mathrm{anual}} = S_{\mathrm{diario}}\sqrt{252} \;\;(\text{solo bajo i.i.d.})

Annualization with 12\sqrt{12} or 252\sqrt{252} requires i.i.d. returns; with positive serial autocorrelation — typical of hedge fund strategies with smoothed valuations — the annualized Sharpe can be overstated by up to 65% (Lo, 2002) (Alpha Vantage). It is the most ignored methodological warning in the industry.

Sortino. It replaces total volatility with the downside deviation relative to the minimum acceptable return τ\tau (databento.com):

Sortino=Rp−τσd,σd=1N∑i=1Nmin⁡(Ri−τ, 0)2\mathrm{Sortino} = \frac{R_p - \tau}{\sigma_d}, \qquad \sigma_d = \sqrt{\frac{1}{N}\sum_{i=1}^{N}\min(R_i - \tau,\,0)^2}

Omega (Keating–Shadwick, 2002). It uses the entire distribution, with no moment assumptions (databento.com):

Ω(θ)=∫θb[1−F(r)]dr∫aθF(r) dr  =  E[(R−θ)+]E[(θ−R)+]\Omega(\theta) = \frac{\displaystyle\int_{\theta}^{b}\left[1 - F(r)\right]dr}{\displaystyle\int_{a}^{\theta} F(r)\,dr} \;=\; \frac{\mathbb{E}[(R-\theta)^{+}]}{\mathbb{E}[(\theta-R)^{+}]}

with empirical form Ω^(θ)=1n∑i=1n(Ri−θ)+1n∑i=1n(θ−Ri)+\hat\Omega(\theta) = \dfrac{\frac{1}{n}\sum_{i=1}^n (R_i-\theta)^{+}}{\frac{1}{n}\sum_{i=1}^n (\theta-R_i)^{+}} (Macroption).

Calmar. Calmar=CAGR∣MDD∣\mathrm{Calmar} = \dfrac{\mathrm{CAGR}}{|\mathrm{MDD}|}, typically over 36-month windows; introduced by Terry W. Young (1991) (quantvps.com). Window bias: a track record that has not yet lived through its crisis exhibits an artificially high Calmar (quantvps.com).

Sterling. Deane Sterling Jones's (1981) original definition is (Alpha Vantage):

Sterling=APRALD+10%\mathrm{Sterling} = \frac{APR}{ALD + 10\%}

with APRAPR the compound annual return and ALDALD the average of the annual maximum drawdowns. The 10% reflected T-bill yields in 1981; variants with −10%-10\% and modern versions with RfR_f coexist (langfuse.com). Editorial rule: always cite the convention used.

Ulcer Index (Martin & McCann, 1987). Root mean square of percentage drawdowns from the last peak (TrueFoundry):

Ri=100×Pi−max⁡j≤iPjmax⁡j≤iPj,UI=1N∑i=1NRi2R_i = 100 \times \frac{P_i - \max_{j \le i} P_j}{\max_{j \le i} P_j}, \qquad UI = \sqrt{\frac{1}{N}\sum_{i=1}^{N} R_i^2}

The square penalizes the depth and the duration of drawdowns jointly; it is the basis of the Ulcer Performance Index, UPI=(Rp−Rf)/UIUPI = (R_p - R_f)/UI (TrueFoundry).

Tracking error and information ratio. For an active portfolio against its benchmark bb (🦜️🔗 LangChain):

TE=σ(Rp−Rb),IR=Rp−RbTETE = \sigma(R_p - R_b), \qquad IR = \frac{R_p - R_b}{TE}

Grinold's (1989) fundamental law of active management decomposes IR into skill and breadth: IR≈IC⋅BRIR \approx IC \cdot \sqrt{BR}, where ICIC is the information coefficient (correlation between forecast and realization) and BRBR the number of independent bets (NextFuture).

Higher-order moments and modified VaR. Equity returns exhibit negative skewness and excess kurtosis (kosmoy.com):

S^=1n∑i=1n(ri−rˉσ^)3,K^=μ^4σ^4,Kexceso=K^−3\hat{S} = \frac{1}{n}\sum_{i=1}^{n}\left(\frac{r_i - \bar r}{\hat\sigma}\right)^3, \qquad \hat{K} = \frac{\hat\mu_4}{\hat\sigma^4}, \qquad K_{\mathrm{exceso}} = \hat K - 3

(normal: S=0S = 0, K=3K = 3). The Cornish–Fisher expansion (Zangari, 1996) corrects the Gaussian quantile (AgenticWire):

zCF=z+16(z2−1)S+124(z3−3z)Kexceso−136(2z3−5z)S2z_{CF} = z + \frac{1}{6}(z^2 - 1)S + \frac{1}{24}(z^3 - 3z)K_{\mathrm{exceso}} - \frac{1}{36}(2z^3 - 5z)S^2 VaRmod=V[zCF σh−μh]\mathrm{VaR}_{\mathrm{mod}} = V\left[z_{CF}\,\sigma\sqrt{h} - \mu h\right]

and Boudt, Peterson, and Carl (2008) extend the correction to a coherent modified ES, ESmod=σφ(z)α[1+z6S+z2−124Kexceso]−μ\mathrm{ES}_{\mathrm{mod}} = \sigma\frac{\varphi(z)}{\alpha}\left[1 + \frac{z}{6}S + \frac{z^2-1}{24}K_{\mathrm{exceso}}\right] - \mu (AgenticWire). The expansion stops being monotonic for ∣S∣≳2|S| \gtrsim 2 or K≳6K \gtrsim 6: verify the monotonicity of zCFz_{CF} in α\alpha before reporting it (AgenticWire).

The following table summarizes the module's main risk metrics.

Table 7.1 — Risk metrics: formula, horizon, assumptions, and main limitation

MetricSummary formulaTypical horizonKey assumptionsMain limitation
Delta-normal VaRVzασhV z_\alpha \sigma \sqrt{h}1–10 daysNormality, i.i.d., linearityUnderestimates fat tails and non-linearities (graphrag.com)
Historical VaRL(⌈T(1−α)⌉)L_{(\lceil T(1-\alpha)\rceil)}1 day (250 obs.)History represents the future~2.5 tail obs. at 99%; slow under a new regime (arXiv.org)
Monte Carlo VaR / FHSF^L,N−1(1−α)\hat F^{-1}_{L,N}(1-\alpha)1–10 daysWell-calibrated factor modelSpecification risk; revaluation cost (arXiv.org)
ES / CVaR1α∫0αVaRu du\frac{1}{\alpha}\int_0^\alpha \mathrm{VaR}_u\,du1–10 daysWell-estimated tailStatistically difficult backtesting (kosmoy.com)
EWMA RiskMetricsλσt−12+(1−λ)rt−12\lambda\sigma_{t-1}^2 + (1-\lambda)r_{t-1}^2Dailyλ=0,94\lambda = 0{,}94 universalNo mean reversion (IGARCH) (graphrag.com)
GARCH(1,1)ω+αε2+βσ2\omega + \alpha\varepsilon^2 + \beta\sigma^2Daily–monthlyStationarity, α+β<1\alpha+\beta<1Persistence misestimated in crises (Bright Data)
MDDmin⁡t(Vt−V‾t)/V‾t\min_t (V_t - \overline V_t)/\overline V_tFull historyFaithful equity curveWindow-dependent; backward-looking (Investopedia)
Daily returns distribution with 99% VaR and 97.5% ES marked (synthetic data, illustrative)Daily returns (synthetic, illustrative): −0.100 → 0, −0.065 → 0, −0.030 → 0.79, 0.005 → 32, 0.040 → 0, 0.075 → 0, 0.100 → 0. Estimated density: −0.100 → 0, −0.067 → 0.09, −0.033 → 0.35, 0.001 → 38, 0.034 → 0.36, 0.068 → 0, 0.100 → 0Daily returns (synthetic, illustrative)Estimated density01020304050−0.100−0.075−0.050−0.0250.0000.0250.0500.0750.100Daily returnDensityVaR 99% = −3.05%ES 97.5% = −3.34%
Figure 7.1. Synthetic daily returns distribution with fat tails (normal / Student-t mixture), with 99% VaR and 97.5% ES marked. With tails heavier than normal, ES pulls away from VaR into the tail: exactly the behavior FRTB seeks to capitalize. Data generated for purely illustrative purposes. Own elaboration, Jul-2026.

7.2 Portfolio risk and stress testing

7.2.1 Euler decomposition, scenarios, and FRTB

Component and Marginal VaR. With parametric VaR VaRp=zασpV\mathrm{VaR}_p = z_\alpha \sigma_p V and monetary positions xix_i, Garman's (1996) decomposition is (The Database for Multimodal AI):

MVaRi=∂VaRp∂xi=zα (Σx)iσpCVaRi=xi⋅MVaRi=zα xi(Σx)iσp\mathrm{MVaR}_i = \frac{\partial \mathrm{VaR}_p}{\partial x_i} = z_\alpha\,\frac{(\Sigma x)_i}{\sigma_p} \qquad \mathrm{CVaR}_i = x_i \cdot \mathrm{MVaR}_i = z_\alpha\,\frac{x_i(\Sigma x)_i}{\sigma_p}

equivalently, CVaRi=VaRi⋅ρi,p\mathrm{CVaR}_i = \mathrm{VaR}_i \cdot \rho_{i,p}. The Euler property guarantees exact aggregation: ∑iCVaRi=VaRp\sum_i \mathrm{CVaR}_i = \mathrm{VaR}_p (kosmoy.com). Marginal VaR identifies the "worst hedge": the position with the highest MVaR is the one whose reduction cuts the most risk per monetary unit. This decomposition is, moreover, the mathematical basis of narrative risk attribution with an LLM (§7.3): the tool computes the CVaRi\mathrm{CVaR}_i, the language model explains them (The Database for Multimodal AI). The underlying diversification is Markowitz's: with two assets, σp2=wA2σA2+wB2σB2+2wAwBσAσBρAB\sigma_p^2 = w_A^2\sigma_A^2 + w_B^2\sigma_B^2 + 2 w_A w_B \sigma_A \sigma_B \rho_{AB}, and any ρ<1\rho < 1 reduces variance relative to the weighted average — with the critical caveat that in crises correlations converge to 1 (2008, March 2020) (confident-ai.com).

Historical scenarios. The shocks observed in real episodes are reapplied to the current portfolio: subprime 2007-08, COVID March 2020, Black Monday 1987 (−22.6% for the Dow in a single session), LTCM 1998, the 2022 rates shock. For each factor, the worst 1-day and 10-day shocks are determined. Their value is that they preserve the real stress correlations: in 2008 developed-market equities fell together, and in March 2020 equities and Treasury bonds were sold simultaneously in the dash for cash (openobserve.ai).

Hypothetical scenarios. Plausible extreme shocks not necessarily observed. A documented global bank's stress program combines historical scenarios ("subprime crisis", "Covid crisis") with a hypothetical worst case that moves each factor between ±3 and ±6 daily standard deviations, ignoring historical correlations (openobserve.ai).

Reverse stress testing. The BCBS principles invert the logic: "a stress testing programme must determine what scenarios could challenge the bank's viability (reverse stress tests) and thereby uncover hidden risks and interactions between risks", starting "from a known stress outcome — a breach of regulatory capital ratios, illiquidity or insolvency — and asking what events could lead to that outcome" (BCBS 2009, p. 14) (Laminar). PRA, EBA, and FCA incorporate it into their frameworks (ICAAP/SREP; FG 20/1), and the BCBS Range of Practices report (2017) documents that two-thirds of institutions practice it as a complement (xseek.io). The 2018 Stress Testing Principles (BCBS d450) replace the 2009 ones and require stress testing as a mandatory complement to internal models, precisely to cover what the model's assumptions do not capture (kosmoy.com).

FRTB: from 99% VaR to 97.5% ES. The Fundamental Review of the Trading Book (BCBS d352, 2016; revised in d457, 2019) replaces, in the internal models approach, 10-day 99% VaR with 97.5% ES calibrated over a stress period, with five liquidity horizons (10/20/40/60/120 days), a reduced set of modellable factors, and additive capital for non-modellable ones (NMRF) (kosmoy.com). The calibration is deliberately continuous under normality (Holiday Landmark):

VaR99%=2,326 σES97,5%=σ φ(1,960)0,025=0,05840,025 σ=2,338 σ\mathrm{VaR}_{99\%} = 2{,}326\,\sigma \qquad \mathrm{ES}_{97{,}5\%} = \sigma\,\frac{\varphi(1{,}960)}{0{,}025} = \frac{0{,}0584}{0{,}025}\,\sigma = 2{,}338\,\sigma

— almost identical (2,338σ≈2,326σ2{,}338\sigma \approx 2{,}326\sigma) when returns are normal, but with ES growing much faster than VaR as soon as fat tails appear: "same number in calm times, a larger number precisely on the fat-tail exposures that VaR historically undercapitalized" (Holiday Landmark). Backtesting is still done on 99% and 97.5% VaR with the traffic light over 250 days — because ES is not classically elicitable and its direct validation is statistically harder — complemented by the P&L Attribution Test (PLAT) at desk level; a desk that fails backtesting or PLAT is forcibly migrated from the internal to the standardized approach (kosmoy.com). Implementation calendar: EU (CRR3) January 2026, UK (PRA) January 2027, US pending (braintrust.dev).

Table 7.2 — FRTB (IMA) versus the previous internal approach (Basel 2.5)

DimensionPrevious framework (Basel 2.5, IMA)FRTB (IMA, d457)
Capital metric99% VaR, 10 days (+ stressed VaR)97.5% ES, calibrated to a stress period (braintrust.dev)
HorizonUniform 10 days10/20/40/60/120 days by factor liquidity (kosmoy.com)
Risk factorsAll modellable by defaultNMRF with additive capital; reduced set ≥ 75% of total ES
DiversificationFull implicitIMCC recognizes only 50% of the benefit (ρ=0,5\rho = 0{,}5)
ValidationTraffic light on 99% VaRTraffic light on 99% and 97.5% VaR + desk-level PLAT (kosmoy.com)
Consequence of failureCapital multiplierForced migration of the desk to the standardized approach (kosmoy.com)
Entry into force2011 (Basel 2.5)EU Jan-2026; UK Jan-2027; US pending (braintrust.dev)

7.3 The risk copilot with LangChain

7.3.1 Canonical pattern: the tool computes, the LLM narrates, the human vetoes

The 2024-2026 literature documents a transition from "LLMs as text analysts" to LLM agents with quantitative tools: the LLM reasons and orchestrates; the numbers are computed by deterministic code (horizontrading.io). The 2026 trading-agent taxonomy classifies risk control as a native capability of the agent — "risk as a gating mechanism in the action architecture, not post-hoc" (horizontrading.io) — and the reference case is FinCon (NeurIPS 2024): its intra-episode risk alert is triggered by a sudden drop in CVaR, defined as the mean of the worst 1% of daily P&L, and when activated "the manager agent adopts a risk-averse stance that day, regardless of the prior risk state" (Github). In the open source ecosystem, MCP servers such as wraquant-mcp expose 218 tools (risk, volatility, and regime modules) to Claude/LangChain agents; the documented conversation pattern is literally "VaR(95%): −2.1%, CVaR: −3.4%" computed by the tool and narrated by the agent (quodfinancial.com). LangChain also maintains an official sample repository of a risk assessment agent (langchain-samples/risk-assessment-agent, LangGraph + LangSmith) with GRC scenarios and human-in-the-loop (TS Imagine), and projects such as DART architecturally separate risk_manager.py (Monte Carlo VaR, Kelly, sizing) from the LLM analyzer (sanj.dev).

Layer 1: the deterministic tool. Every risk figure is produced in Python, with controlled rounding and structured output:

python
import numpy as np
from langchain_core.tools import tool

@tool
def compute_var_es(returns: list[float], confidence: float = 0.99) -> dict:
    """VaR and Expected Shortfall via historical simulation (positive losses)."""
    r = np.asarray(returns, dtype=float)
    losses = np.sort(-r)                       # positive losses, sorted
    alpha = 1.0 - confidence
    var = float(np.quantile(losses, confidence))
    tail = losses[losses >= var]
    es = float(tail.mean()) if tail.size else var
    # Controlled rounding: the LLM receives the final figure, never recomputes it
    return {"var": round(var, 6), "es": round(es, 6),
            "n_tail": int(tail.size), "alpha": alpha, "method": "historical"}

Layer 2: backtesting as a validation tool. The same principle applies to Kupiec's test:

python
import numpy as np
from scipy.stats import chi2
from langchain_core.tools import tool

@tool
def kupiec_pof(exceptions: int, n_days: int, p: float = 0.01) -> dict:
    """Kupiec POF test: H0 = the exception rate equals the nominal p."""
    N, T = exceptions, n_days
    lr = -2.0 * (np.log((1 - p) ** (T - N) * p ** N)
                 - np.log((1 - N / T) ** (T - N) * (N / T) ** N))
    return {"lr_pof": round(float(lr), 4),
            "p_value": round(float(chi2.sf(lr, 1)), 4),
            "reject_5pct": bool(lr > chi2.ppf(0.95, 1))}

Layer 3: the copilot agent with human escalation. The LLM orchestrates the tools and drafts the attribution based on the Euler decomposition it receives as JSON; an interrupt halts the flow on any limit breach so the risk manager decides:

python
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import InMemorySaver

SYSTEM = (
    "Eres un copiloto de riesgo institucional. NUNCA calcules cifras de riesgo: "
    "usa SIEMPRE las herramientas compute_var_es, kupiec_pof y euler_attribution. "
    "Narra la atribución solo a partir del JSON que devuelvan las herramientas, "
    "citando cada número exactamente como lo recibiste."
)

copilot = create_agent(
    model="claude-sonnet-4-6",
    tools=[compute_var_es, kupiec_pof, euler_attribution],
    system_prompt=SYSTEM,
    middleware=[
        HumanInTheLoopMiddleware(
            interrupt_on={
                "escalate_limit_breach": True,   # approve / edit / reject / respond
                "compute_var_es": False,          # safe read
            },
        ),
    ],
    checkpointer=InMemorySaver(),  # in production: PostgresSaver (audit log)
)

The full architecture separates three planes of responsibility:

Three-plane architecture: code for VaR, Euler and backtesting; the LLM for narrative; a human with veto power who approves or rejects on breaches.VaR/ES tool (historical, MC, FHS) → Copilot agent (create_agent); Euler tool (Component VaR) → Copilot agent (create_agent); Backtesting tool (Kupiec / Christoffersen) → Copilot agent (create_agent); Copilot agent (create_agent) → Natural-language attribution + RAG news context; Copilot agent (create_agent) → interrupt: limit breach (breach detected); interrupt: limit breach → Risk manager approve / reject; Risk manager approve / reject → Copilot agent (create_agent) (approve/respond); Risk manager approve / reject → Close with audit log (reject)breach detectedapprove/respondrejectDeterministic plane (code)LLM plane (narrative)Human plane (veto)VaR/ES tool(historical, MC, FHS)Euler tool(Component VaR)Backtesting tool(Kupiec / Christoffersen)Copilot agent(create_agent)Natural-language attribution+ RAG news contextinterrupt:limit breachRisk managerapprove / rejectClose with audit log
Diagram 7.1. Risk copilot architecture: deterministic tools produce every figure; the LLM narrates the Euler-based attribution; the interrupt escalates to the human on breaches.

Limit monitoring with natural-language alerts. A scheduler runs the VaR/ES/MDD computation against limits; on a breach, the agent composes the alert —which limit, by how much it is exceeded, which positions contribute according to Component VaR, suggested action— and the interrupt holds it until the human decision (TS Imagine):

At each close VaR, ES and MDD are computed; without a breach it is logged, with one the LLM drafts the alert and a human decides.Daily scheduler (market close) → Deterministic computation: VaR 99% / ES 97.5% / MDD; Deterministic computation: VaR 99% / ES 97.5% / MDD → Limit breach?; Limit breach? → Compliance log (checkpoint) (No); Limit breach? → LLM drafts NL alert: limit, excess, contribution by Component VaR, suggested action (Yes); LLM drafts NL alert: limit, excess, contribution by Component VaR, suggested action → interrupt() human escalation; interrupt() human escalation → Risk manager; Risk manager → Position reduction via execution tool (Approves action); Risk manager → Documented waiver (audit log) (Accepts exception); Risk manager → Escalation to risk committee (Rejects)NoYesApproves actionAccepts exceptionRejectsDaily scheduler(market close)Deterministic computation:VaR 99% / ES 97.5% / MDDLimit breach?Compliance log(checkpoint)LLM drafts NL alert:limit, excess, contributionby Component VaR, suggested actioninterrupt()human escalationRisk managerPosition reductionvia execution toolDocumented waiver(audit log)Escalation to risk committee
Diagram 7.2. Limit monitoring flow: detection is quantitative; the LLM provides the alert narrative; the human retains the decision.
python
from langgraph.types import interrupt

def breach_node(state):
    if state["var_99"] <= state["limit"]:
        return {"status": "compliant"}
    alert = llm.invoke(ALERT_PROMPT + json.dumps(state["euler_breakdown"]))
    decision = interrupt({"alert": alert, "state": state})  # pause until the human
    return {"status": decision["action"], "alert": alert}

7.4 The limits of the model and of the LLM

7.4.1 Structural critique of VaR, numerical hallucination, and model risk

The anti-VaR literature. Nassim Taleb campaigned against VaR for more than a decade and called it, literally, "a fraud" (NYT Magazine, Jan-4-2009); David Einhorn described it as "relatively useless as a risk-management tool and potentially catastrophic when its use creates a false sense of security… like an airbag that works all the time, except when you have an accident" (quodfinancial.com). The quantification of the failure is brutal: under normality, a 5σ5\sigma event should occur once every ~14,000 years; equity markets produce such events roughly once per decade, and in 2008 books with "moderate" 99% VaR suffered losses of several times VaR (🦜️🔗 LangChain). To the empirical critique is added the mathematical defect proven by Artzner et al. (1999): VaR is not subadditive, ignores severity beyond the quantile and, calibrated with low recent volatility, underestimates risk under stress — the three documented reasons for the regulatory change to ES (braintrust.dev). And a warning about endogenous risk: a massively adopted management technique becomes a source of risk ("portfolio insurance" in 1987; correlations at 1.0 in the 2008 liquidity crunch) (latitude.so).

Model risk and the London Whale. In 2012, JPMorgan's Chief Investment Office lost $6.2 billion: the internal investigation revealed that the VaR model had been modified to halve the reported risk and that the change evaded independent validation (paperswithbacktest.com). The historical reference framework was SR 11-7 (Fed/OCC, 2011), which defines "model" broadly and requires three pillars — conceptual soundness, effective validation with outcomes analysis and backtesting, and governance with an inventory — explicitly extended by supervisors to AI/ML models (paperswithbacktest.com). Regulatory update (as of Jul-29-2026): the Federal Reserve's SR 26-2 letter (Apr-17-2026) rescinded SR 11-7, explicitly left generative and agentic AI outside its perimeter, and declared itself non-binding; its principles — effective challenge, inventory, independent validation — persist as the standard of practice, but the governance of LLM agents is today in a regulatory vacuum that firms cover with observability (traces, checkpoints, audit logs) (United Fintech) (archived copy). The direct implication does not change: a LangChain risk copilot is, for practical purposes, a model (or a user of models), and requires inventory, independent validation, drift monitoring, and documented usage limits — with the human retaining the final veto over any consequential action (paperswithbacktest.com).

The module's synthesis is the governing insight of Block III: the LLM reasons, the math decides, the human vetoes. The formulas of sections 7.1 and 7.2 are the layer that decides; the copilot of section 7.3 is the layer that reasons and narrates; and the interrupt with audit log is the layer that vetoes. Weakening any of the three — letting the LLM compute, dispensing with backtesting, or removing human approval — reproduces exactly the failures documented in this section.


Exercises

  1. Multi-method VaR/ES tool. Extend the compute_var_es tool to support the three methods (delta-normal, historical, FHS with GARCH(1,1) and residual resampling). Verify on a synthetic series with Student-t tails that delta-normal underestimates 99% VaR relative to FHS, and document the size of the gap.
  2. Full Kupiec and Christoffersen backtesting. Implement Kupiec's POF test and Christoffersen's conditional coverage test (LRcc=LRuc+LRindLR_{cc} = LR_{uc} + LR_{ind}) as LangChain tools. Over 500 days of an EWMA model applied to the S&P 500, determine in which windows the model would have been rejected at 5% and whether exceptions cluster in streaks.
  3. Cornish–Fisher with guardrails. Implement the Cornish–Fisher modified VaR and Boudt's ES as a tool, with a prior validation that rejects the computation (and reports it to the agent) when ∣S∣>2|S| > 2 or K>6K > 6, also verifying the monotonicity of zCFz_{CF} in α\alpha.
  4. Narrative attribution copilot. Build the agent from section 7.3 with an euler_attribution tool that returns Component VaR by position (EWMA covariance matrix). Require in the system prompt that every narrated figure match the tool's JSON exactly, and write a numerical exact-match evaluation over 20 generated attributions.
  5. Limit monitor with interrupt. Implement Diagram 7.2 as a LangGraph StateGraph with a checkpointer: a deterministic computation node, a conditional breach edge, LLM alert drafting, and interrupt() with approve/reject decisions. Show that the paused graph resumes correctly with Command(resume=...) and that the checkpoint records the decision for audit.
  6. Miniature FRTB traffic light. Simulate 250 days of P&L against 99% and 97.5% VaR, classify the desk as green/amber/red according to the number of exceptions, and discuss why the regulator keeps the traffic light on VaR and not on ES (elicitability), contrasting your answer with the arithmetic 2,338σ≈2,326σ2{,}338\sigma \approx 2{,}326\sigma.

Module 7 of 15 — LangChain for Quantitative Trading. Data and versions verified as of July 2026; prices and market figures subject to change. LangChain 1.3.14 / langchain-core 1.5.2.


// check

Check your understanding

Self-assessment with instant feedback. No score is stored.

  1. A 99% VaR model records N = 7 exceptions in T = 250 days (expected: 2.5), with LR_POF ≈ 5.50. What does the Kupiec test conclude at the 5% level?

    Show answer

    B. Kupiec's POF test contrasts the observed rate N/T against the nominal p under H0; with LR_POF = 5.50 > 3.84 the model is rejected at 5%. The N = 6 case illustrates how sharp the threshold is (3.56 < 3.84). Streaks are assessed by Christoffersen's independence term, which complements Kupiec but is not a requirement of the POF test.

  2. RiskMetrics EWMA is an IGARCH with ω = 0 and α + β = 1. What does that imply for volatility forecasting?

    Show answer

    B. With α + β = 1 there is no finite unconditional variance: the recursion σ²_t = λσ²_{t−1} + (1−λ)r²_{t−1} treats each shock as permanent, with effective memory ≈ 1/(1−λ) ≈ 17 days. GARCH(1,1) with α + β < 1 does revert to σ̄² = ω/(1−α−β). Precisely the multivariate version of EWMA does guarantee positive semidefiniteness by construction.

  3. A hedge fund with smoothed monthly valuations annualizes its Sharpe with √12. According to Lo (2002), what is the documented risk?

    Show answer

    B. Annualization with √252 or √12 is only valid under i.i.d. Smooth marking of illiquid assets creates positive serial autocorrelation, which inflates the annualized Sharpe — Lo (2002) quantifies the overstatement at up to 65%. The module calls it the most ignored methodological warning in the industry, and the bias always plays in the manager's favor.

  4. Why does FRTB compute capital with 97.5% ES but keep backtesting with a traffic light on VaR?

    Show answer

    C. The calibration is deliberately continuous under normality (2.338σ ≈ 2.326σ), but ES penalizes the fat tails that VaR undercapitalized in 2008. The regulator keeps backtesting on 99% and 97.5% VaR because ES is not elicitable in the classical sense: validation stays with the quantile, complemented by PLAT at desk level.

  5. In the Euler decomposition, what does the position with the highest Marginal VaR identify?

    Show answer

    B. MVaR_i = ∂VaR_p/∂x_i = z_α(Σx)_i/σ_p measures the sensitivity of total VaR to each monetary unit of position i: it is the 'worst hedge' to review. Notional weight is not enough — in the worked example, the position with 60% of the notional concentrates 77.4% of the risk — and the Euler property guarantees that Σ CVaR_i = VaR_p.

  6. Why does the risk copilot's system prompt forbid the LLM from computing figures and force it to quote the tools' JSON?

    Show answer

    B. FAITH (ICAIF 2025) measures intrinsic numerical hallucination: not even the best model exceeds 95.6% grounding, and small ones fall below 50%. In risk, precision is non-negotiable, so the module's golden rule is that the tool computes (with controlled rounding) and the LLM narrates the attribution quoting each number exactly as received.

  7. In the limit monitor of Diagram 7.2, what exactly does the interrupt do when a breach is detected?

    Show answer

    B. The interrupt halts execution at a persistent checkpoint: detection is quantitative, the LLM only drafts the alert with the Component VaR breakdown, and the human decides (approve / accept the exception with a waiver / reject and escalate to committee). Resuming with Command(resume=...) and recording the decision in the audit log is exercise 5 of the module.

  8. Einhorn described VaR as 'an airbag that works all the time, except when you have an accident'. What mathematical defect formalizes that critique?

    Show answer

    B. Artzner et al. (1999) proved that VaR is not a coherent measure: it violates subadditivity and is blind to what happens beyond the quantile. Added to the procyclicality of calibrating it with low recent volatility, these are the three documented reasons for the regulatory change to 97.5% ES, which is subadditive and looks at the tail mean.