The user wants me to "engineer a volatility surface stress harness." This is a complex request involving quantitative finance, specifically XVA (X-Value Adjustment), capital management, and risk modeling.
Key concepts mentioned:
- Volatility Surface Stress: Changing the implied volatility surface (shifting it, warping it) to simulate market stress scenarios.
- Adjoint Methods: Using Algorithmic Differentiation (AD) or similar mathematical techniques to efficiently calculate sensitivities (Greeks) or gradients. This is crucial for high-dimensional problems.
- Propagation: How these shocks affect downstream calculations.
- XVA Desks: Valuation adjustments (CVA, DVA, FVA, KVA, etc.).
- Capital Consumption: How much regulatory capital (e.g., CCR, CVA capital charge) is used up due to the stress.
- Risk Appetite Guardrails: Limits set by the firm (e.g., maximum P&L loss, maximum capital usage).
Goal: Create a system (code/architecture) that takes a volatility shock, uses adjoint methods to efficiently compute the impact on XVAs and Capital, and checks if this violates risk limits.
Plan:
-
Define the Architecture: I need a modular design.
- Input: Market Data (Vol Surface, Yield Curves), Trade Data (Derivatives portfolio).
- Core Engine: A pricing/XVA model that supports Adjoint Algorithmic Differentiation (AAD).
- Stress Harness: Logic to apply shocks to the volatility surface.
- Risk Calculator: Computes XVA and Capital changes using AAD gradients.
- Output: Reports on P&L impact, Capital consumption, and limit breaches.
-
Mathematical Foundation (Adjoint Methods):
- Standard differentiation: If y=f(x) and x∈Rn, computing ∇f costs O(n)×cost(f).
- Adjoint (Reverse Mode) AD: If output dimension m is small (e.g., Total CVA) and input dimension n is huge (e.g., all vol surface points and trade vegas), Adjoint costs O(m)×cost(f). This is constant w.r.t n. This is the "secret sauce."
-
Python Implementation Strategy:
- Since I cannot build a full production banking system here, I will create a representative prototype.
- I will use standard libraries (
numpy, pandas, matplotlib) and perhaps a mock-up of an AD library (or just use jax or manual adjoint classes if keeping it simple, but jax is best for demonstration). Actually, for a conceptual "engineering" response, implementing a manual Adjoint class helps explain the mechanics better than just calling jax.grad. However, jax is more robust. Let's stick to a custom class structure to show I understand the "plumbing" of AAD (Operator Overloading).
-
Components to Code:
VolatilitySurface: Class to handle smile dynamics.
Trade: A dummy derivative (e.g., European Option or Swap) that depends on vol.
XVAEngine: Calculates CVA/KVA.
AdjointMath: Simple AD implementation.
StressHarness: The controller class.
-
Refining the "Stress Harness" Concept:
- The user wants to "propagate shocks."
- Instead of re-valuing the entire book for every point on the vol surface (brute force), we use the Adjoint vector (gradient of XVA w.r.t Vol Points) × Shock Vector.
- Formula: ΔXVA≈∇σXVA⋅Δσ.
-
Structuring the Response:
- Executive Summary: High-level approach.
- Architectural Design: The "Stress Harness" diagram/flow.
- Mathematical Core: Explanation of AAD in this context.
- Python Prototype: The actual code.
- Integration Logic: How it connects to Risk Appetite/Capital.
-
Drafting the Code (Mental Check):
- Need a
Number class that tracks gradients.
- Need
BlackScholes function implemented using this Number class.
- Need
CVA calculation (simplified: Exposure × PD × LGD).
- The "Stress" part: Define a vector of bumps to vol parameters (e.g., ATM shift, skew twist).
- Multiply Gradient by Shock.
-
Capital & Risk Appetite:
- Capital: usually a function of EEPE (Effective Expected Positive Exposure) or CVA P&L volatility.
- Risk Appetite: Thresholds.
-
Self-Correction during drafting:
-
Complexity: Writing a full AAD library is too long. I will use a simplified manual gradient approach or jax for brevity and correctness. jax is excellent for this. It makes the code clean and focuses on the logic rather than the AD infrastructure. Correction: Actually, manually coding a basic "Tape-based" adjoint demonstrates deeper engineering knowledge for a "build" prompt. Let's do a hybrid: Use jax for the math engine to ensure correctness, but wrap it in an architecture that simulates a risk system.
-
Wait, let's stick to the prompt's tone. "Engineer a... harness". It implies structure.
-
I will implement a VolatilitySurface class.
-
I will implement a Derivative class.
-
I will use jax for the adjoint differentiation because it's the modern standard for this in Python.
-
Algorithm:
- Define Base State.
- Define
loss_function = (XVA + Capital_Cost).
- Compute Gradient \nabla_{\text{vol_params}} using
jax.grad.
- Define Stress Scenarios (Vector δ).
- Compute Impact: Impact=.
-
Final Polish: Ensure the distinction between XVA (accounting) and Capital (regulatory) is clear in the logic. Add comments explaining the "Why".
(Self-Correction on "Stress Harness"): A harness implies a control mechanism. It shouldn't just calculate; it should potentially constrain or report. I'll add a "Guardrail Enforcer" module that returns a status (PASS/FAIL/BREACH).
Let's write the solution.
- Framework: Python + JAX (for AAD).
- Scenario: Portfolio of Swaptions/Options.
- Metrics: CVA (Credit Valuation Adjustment) and CVA Capital Charge (Basel approach simplified).
- Stress: Parallel shift + Twist.
Let's assemble.
This solution designs a Volatility Surface Stress Harness using Adjoint Algorithmic Differentiation (AAD).
In a modern XVA architecture, re-valuing a massive derivatives portfolio for every stress scenario is computationally prohibitable (O(N×M), where N is scenarios and M is deals). By using Adjoint methods, we invert this complexity. We compute the gradient of the XVA with respect to the volatility surface nodes once (O(M)), and then propagate vectorized shocks instantaneously ().
1. Architectural Overview
The system consists of three layers:
- The Analytic Core (AAD Engine): Computes XVA sensitivities (Greeks) w.r.t. volatility surface pillars using Adjoint Mode differentiation.
- The Stress Harness: A linear algebra layer that projects basis shocks (parallel, skew, twist) onto the surface grids using the pre-computed Jacobians.
- The Risk Controller: Aggregates capital consumption (KVA) and validates against hard risk appetite limits.
2. Python Implementation
We will use JAX for the Adjoint differentiation layer. It allows us to write forward-looking code (simulation) and automatically extract the backward-pass (gradients) required for efficient stress testing.
import numpy as np
import jax.numpy as jnp
from jax import grad, jit
import pandas as pd
import matplotlib.pyplot as plt
# ---------------------------------------------------------
# 1. MARKET & SURFACE MODEL
# ---------------------------------------------------------
class VolatilitySurface:
"""
Represents a parametric or grid-based Volatility Surface.
For this harness, we assume a grid of pillars (Expiry, Strike).
"""
def __init__(self, strikes, expiries, base_vols):
self.strikes = strikes
self.expiries = expiries
self.base_vols = base_vols # Flattened grid params
def get_interpolated_vol(self, K, T):
"""
Simple bilinear interpolation logic for demonstration.
In production, this would be SABR or SVI interpolation.
"""
# Simplified logic: find closest bucket
# (JAX compatible logic would use vectorization)
return jnp.interp(T, self.expiries, self.base_vols) # Simplified 1D interp
# ---------------------------------------------------------
# 2. AAD PRICING & XVA ENGINE
# ---------------------------------------------------------
class XVAPricer:
"""
Computes XVA and related metrics.
Wrapped in JAX to enable Adjoint Differentiation.
"""
def __init__(self, portfolio):
self.portfolio = portfolio
@staticmethod
def _black_scholes_price(S, K, T, r, sigma, option_type):
"""JAX-enabled BS Pricer"""
from jax.scipy.stats import norm
d1 = (jnp.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * jnp.sqrt(T))
d2 = d1 - sigma * jnp.sqrt(T)
if option_type == 'call':
price = S * norm.cdf(d1) - K * jnp.exp(-r * T) * norm.cdf(d2)
else:
price = K * jnp.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
return price
def calculate_exposure(self, vol_surface_params):
"""
Simulates Monte Carlo paths to calculate Expected Positive Exposure (EPE).
NOTE: Simplified here for analytical clarity.
We map vol_surface_params directly to EPE.
"""
# In a real engine, this involves MC Simulation.
# For the harness, we define a functional relationship: EPE(Vol)
# Example: A portfolio of Calls. EPE increases with Vol.
# We create a synthetic dependency: EPE = Sum(Vega * Vol_Shift)
# Let's assume 3 pillars for simplicity
vega_vector = jnp.array([50000.0, 120000.0, 80000.0]) # Synthetic Vegas at pillars
# EPE is linear in Vol for small moves (Taylor expansion)
# EPE = Base_EPE + Vega . dVol
base_epe = 10_000_000
current_epe = base_epe + jnp.sum(vega_vector * (vol_surface_params - 0.2))
return current_epe
def calculate_xva(self, vol_surface_params):
"""
Full XVA stack.
Returns: CVA, FVA, KVA (Capital)
"""
# 1. Compute Exposure (EPE)
epe = self.calculate_exposure(vol_surface_params)
# 2. Compute CVA (Credit Valuation Adjustment)
# CVA ~ (1 - Recovery) * DefaultProb * EPE
lgd = 0.6
pd = 0.02
cva = lgd * pd * epe
# 3. Compute FVA (Funding Valuation Adjustment) - Simplified
# FVA ~ Spread * EPE
fva = 0.01 * epe
# 4. Compute KVA (Capital Valuation Adjustment)
# Regulatory capital usually scales with volatility (squared for var)
# KVA ~ CCR Capital Charge
kva = 0.10 * (epe ** 1.1) # Non-linear capital consumption
total_xva = cva + fva + kva
return total_xva
# ---------------------------------------------------------
# 3. THE STRESS HARNESS (AAD CORE)
# ---------------------------------------------------------
class StressHarness:
def __init__(self, pricer, base_vols):
self.pricer = pricer
self.base_vols = base_vols
# COMPILE THE ADJOINT GRADIENT FUNCTION
# This is the magic: grad() returns the vector-Jacobian product (VJP)
# It calculates d(XVA)/d(Vol_Node) for ALL nodes in one reverse pass.
self.grad_xva = jit(grad(pricer.calculate_xva))
def run_stress_test(self, shock_scenario):
"""
Applies a shock scenario vector to the surface and calculates impacts.
Uses Adjoint methods to linearize the shock propagation.
"""
# 1. Calculate Adjoint Vector (The Greeks)
# dXVA/dSigma
xva_sensitivities = self.grad_xva(self.base_vols)
# 2. Apply Shocks
# New_Vol = Base_Vol + Shock
shocked_vols = self.base_vols + shock_scenario
# 3. Propagation (Linear Approximation using Taylor Expansion)
# Delta_XVA ~= Gradient . Shock_Vector
# This is instantaneous compared to full revaluation
delta_xva_linear = jnp.dot(xva_sensitivities, shock_scenario)
# 4. Full Revaluation (for validation/convexity check)
base_xva = self.pricer.calculate_xva(self.base_vols)
shocked_xva = self.pricer.calculate_xva(shocked_vols)
delta_xva_full = shocked_xva - base_xva
return {
"Base XVA": base_xva,
"Shocked XVA": shocked_xva,
"Delta (Linear/AAD)": delta_xva_linear,
"Delta (Full Reval)": delta_xva_full,
"Sensitivities (Vegas)": xva_sensitivities
}
# ---------------------------------------------------------
# 4. RISK APPETITE GUARDRAILS
# ---------------------------------------------------------
def check_guardrails(results, limits):
"""
Validates results against Risk Appetite Framework.
"""
status = "GREEN"
breaches = []
if abs(results['Delta (Full Reval)']) > limits['max_xva_change']:
status = "RED"
breaches.append("XVA P&L Buffer Breached")
# Capital Consumption Check
# In a real system, we would check the specific KVA component
if results['Shocked XVA'] > limits['max_capital_usage']:
status = "RED"
breaches.append("Capital Consumption Limit Breached")
return status, breaches
# ---------------------------------------------------------
# 5. EXECUTION ENGINE
# ---------------------------------------------------------
# Define Market State
strikes = jnp.array([0.8, 1.0, 1.2])
expiries = jnp.array([1.0, 5.0])
base_vols = jnp.array([0.20, 0.22, 0.25]) # Flat-ish surface
# Initialize
pricer = XVAPricer(portfolio="IR_Swap_Book")
harness = StressHarness(pricer, base_vols)
# Define Stress Scenarios
# Scenario: "Vol Crush" (Negative shock to ATM, Positive to Wings - Fly)
shock_vector = jnp.array([-0.05, -0.04, -0.02])
print("--- Running Stress Harness ---")
results = harness.run_stress_test(shock_vector)
print(f"Base XVA: {results['Base XVA']:,.2f}")
print(f"Shocked XVA: {results['Shocked XVA']:,.2f}")
print(f"Delta (AAD Estimate): {results['Delta (Linear/AAD)']:,.2f}")
print(f"Delta (Full Reval): {results['Delta (Full Reval)']:,.2f}")
# Guardrails Check
risk_limits = {'max_xva_change': 1_000_000, 'max_capital_usage': 20_000_000}
status, breaches = check_guardrails(results, risk_limits)
print(f"\nRisk Status: {status}")
if breaches:
print(f"Breaches: {breaches}")
else:
print("Within Risk Appetite.")
3. Detailed Engineering Logic
A. The Adjoint Advantage
In a standard bump-and-revalue (Finite Difference) approach, if you have 100 volatility surface nodes, you must reprice the entire portfolio 100 times.
- Cost (Finite Diff): N×Cost(Pricer)
- Cost (Adjoint): 1×Cost(Pricer)+Cost(Backprop)
The Adjoint method is effectively independent of the number of risk factors. The code uses jax.grad which builds a computation graph. When grad(pricer.calculate_xva) is called, JAX traverses this graph in reverse, applying the chain rule to compute the sensitivity of the output (XVA) to the inputs (Vol Grid) simultaneously.
B. Volatility Surface Propagation
The "Harness" acts as a mapping layer.
- Base State (Σ0): The current calibrated surface.
- Shock Scenario (δ): A vector representing a market move (e.g., 2008 crisis style, or COVID style).
- Perturbation: Σ′=.
Because we have the gradient vector ∇ΣXVA (the adjoint vector), we can approximate the P&L impact of any scenario δ instantly using the dot product:
ΔXVA≈∇
C. Capital Consumption (KVA) & Guardrails
The Stress Harness is the bridge between the Trading Book and the Balance Sheet.
- KVA Feedback: The
calculate_xva function includes a term for Capital Valuation Adjustment. By differentiating this, the harness tells you not just how much money you lose, but how much capital the stress consumes (due to increased CCR capital requirements).
- Risk Appetite: The
check_guardrails function enforces the firm's risk tolerance.
- Hard Limit: If
Stress Loss > XVA Buffer, the desk must reduce risk.
- Capital Limit: If
Stress Capital > Limit, the business is no longer viable under that scenario.
4. Integration into XVA Desks
To deploy this in a production banking environment (e.g., using QuantLib, ADOL-C, or OpTensor):
- Morning Batch: Run the full Monte Carlo simulation once. Use AAD to "tape" the calculation and dump the Adjoint Vector (dXVA/dVol) into a Risk Database.
- Intraday Real-time: When market volatilities spike, apply the Stress Harness. Multiply the stored Adjoint Vector by the live market shock.
- Reporting: If the resulting scalar value breaches the "Risk Appetite Guardrail" (e.g., 10% of Tier 1 Capital), an automatic alert is sent to the XVA Desk to hedge the vega exposure immediately.