The user wants a VaR (Value at Risk) and stress testing suite for treasury investments. This is a complex financial risk management tool. I need to create a comprehensive Python solution that covers:
-
VaR Methods:
- Historical Simulation
- Parametric (Variance-Covariance)
- Monte Carlo Simulation
-
Stress Testing:
- Historical Scenarios (2008 Crisis, 2020 COVID, 2013 Taper Tantrum)
- Hypothetical Scenarios (Rate Shocks, Yield Curve Twists)
- Reverse Stress Testing
-
Portfolio Components:
- Treasury bonds
- Treasury bills
- TIPS (Treasury Inflation-Protected Securities)
- Treasury futures
-
Risk Metrics:
- VaR at different confidence levels
- Expected Shortfall (CVaR)
- DV01 (Dollar Value of 01)
- Duration and Convexity
-
Visualization:
- VaR over time
- Stress test impact
- Yield curve scenarios
- P&L distributions
Let me build a complete, professional-grade suite using:
- yfinance for market data
- numpy/scipy for calculations
- pandas for data manipulation
- matplotlib/seaborn/plotly for visualization
- QuantLib for bond pricing (optional, can use custom implementation)
I'll structure this as a modular, extensible system.
Treasury Investment VaR and Stress Testing Suite
This is a comprehensive risk management system for treasury investments, featuring multiple VaR methodologies, stress testing scenarios, and interactive visualizations.
Installation
pip install numpy pandas scipy matplotlib seaborn plotly yfinance pandas-datareader
Complete Code
"""
Treasury Investment VaR and Stress Testing Suite
================================================
A comprehensive risk management system for treasury portfolios.
Features:
- Multiple VaR methodologies (Historical, Parametric, Monte Carlo)
- Expected Shortfall (CVaR)
- Historical and hypothetical stress scenarios
- Yield curve risk analysis
- Interactive visualizations
"""
import numpy as np
import pandas as pd
import scipy.stats as stats
from scipy.interpolate import interp1d
from scipy.optimize import minimize
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
from datetime import datetime, timedelta
import warnings
import yfinance as yf
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Optional, Union
from enum import Enum
import json
warnings.filterwarnings('ignore')
# Set plotting style
plt.style.use('seaborn-v0_8-whitegrid')
sns.set_palette("husl")
# =============================================================================
# DATA STRUCTURES AND ENUMS
# =============================================================================
class VaRMethod(Enum):
HISTORICAL = "Historical Simulation"
PARAMETRIC = "Parametric (Variance-Covariance)"
MONTE_CARLO = "Monte Carlo Simulation"
CORNISH_FISHER = "Cornish-Fisher Expansion"
class StressScenarioType(Enum):
HISTORICAL = "Historical Scenario"
HYPOTHETICAL = "Hypothetical Scenario"
REVERSE = "Reverse Stress Test"
MACRO = "Macroeconomic Scenario"
@dataclass
class TreasuryPosition:
"""Represents a treasury position"""
security_type: str # T-Bill, T-Note, T-Bond, TIPS
cusip: str
face_value: float
coupon_rate: float
maturity_date: datetime
purchase_date: datetime
purchase_price: float
current_price: float = None
duration: float = None
convexity: float = None
dv01: float = None
def __post_init__(self):
if self.current_price is None:
self.current_price = self.purchase_price
self.calculate_risk_metrics()
def calculate_risk_metrics(self):
"""Calculate duration, convexity, and DV01"""
years_to_maturity = (self.maturity_date - datetime.now()).days / 365.25
if years_to_maturity <= 0:
years_to_maturity = 0.01
# Approximate modified duration
if self.security_type == "T-Bill":
self.duration = years_to_maturity
else:
ytm = self.coupon_rate / 100 + 0.001 # Approximate YTM
self.duration = self._calculate_modified_duration(
years_to_maturity, self.coupon_rate / 100, ytm, self.current_price
)
# Approximate convexity
self.convexity = self._calculate_convexity(
years_to_maturity, self.coupon_rate / 100,
self.coupon_rate / 100 + 0.001, self.current_price
)
# DV01 (Dollar Value of 01)
self.dv01 = self.face_value * self.duration * 0.0001
def _calculate_modified_duration(self, years, coupon, ytm, price):
"""Calculate modified duration using closed-form formula"""
periods = int(years * 2)
if periods == 0:
return years
period_coupon = coupon / 2
period_ytm = ytm / 2
if coupon == 0:
return years / (1 + ytm)
mac_duration = 0
for t in range(1, periods + 1):
weight = period_coupon / ((1 + period_ytm) ** t)
if t == periods:
weight += 1 / ((1 + period_ytm) ** t)
mac_duration += t * weight
mac_duration /= (price / 100)
return mac_duration / 2 / (1 + period_ytm)
def _calculate_convexity(self, years, coupon, ytm, price):
"""Calculate convexity"""
periods = int(years * 2)
if periods == 0:
return years ** 2
period_coupon = coupon / 2
period_ytm = ytm / 2
convexity = 0
for t in range(1, periods + 1):
weight = period_coupon / ((1 + period_ytm) ** t)
if t == periods:
weight += 1 / ((1 + period_ytm) ** t)
convexity += t * (t + 1) * weight
convexity /= (price / 100)
return convexity / 4 / ((1 + period_ytm) ** 2)
@property
def market_value(self):
return self.face_value * self.current_price / 100
@property
def years_to_maturity(self):
return max((self.maturity_date - datetime.now()).days / 365.25, 0)
@dataclass
class StressScenario:
"""Stress test scenario definition"""
name: str
scenario_type: StressScenarioType
description: str
yield_curve_shock: Dict[str, float] # Tenor -> basis point shock
spread_changes: Dict[str, float] = field(default_factory=dict)
inflation_shock: float = 0.0
fx_changes: Dict[str, float] = field(default_factory=dict)
probability: float = 0.01
historical_date: Optional[datetime] = None
@dataclass
class VaRResult:
"""VaR calculation result"""
method: VaRMethod
confidence_level: float
var_amount: float
var_percentage: float
expected_shortfall: float
es_percentage: float
portfolio_value: float
calculation_time: datetime
lookback_period: int
additional_metrics: Dict = field(default_factory=dict)
# =============================================================================
# YIELD CURVE MODEL
# =============================================================================
class YieldCurveModel:
"""Nelson-Siegel yield curve model with calibration"""
def __init__(self):
self.beta0 = 0.05 # Long-term rate
self.beta1 = -0.02 # Short-term component
self.beta2 = 0.02 # Curvature
self.tau = 1.5 # Decay factor
self.tenors = [0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30]
self.rates = {}
def nelson_siegel(self, t, beta0, beta1, beta2, tau):
"""Nelson-Siegel yield curve formula"""
if t <= 0:
return beta0 + beta1
return (beta0 +
beta1 * (1 - np.exp(-t/tau)) / (t/tau) +
beta2 * ((1 - np.exp(-t/tau)) / (t/tau) - np.exp(-t/tau)))
def calibrate(self, market_rates: Dict[float, float]):
"""Calibrate model to market rates"""
self.rates = market_rates
tenors = list(market_rates.keys())
rates = list(market_rates.values())
def objective(params):
b0, b1, b2, tau = params
model_rates = [self.nelson_siegel(t, b0, b1, b2, tau) for t in tenors]
return np.sum((np.array(model_rates) - np.array(rates)) ** 2)
result = minimize(objective, [0.05, -0.02, 0.02, 1.5],
bounds=[(0, 0.2), (-0.1, 0.1), (-0.1, 0.1), (0.1, 5)])
self.beta0, self.beta1, self.beta2, self.tau = result.x
return result.success
def get_rate(self, tenor: float) -> float:
"""Get interpolated rate for any tenor"""
if tenor in self.rates:
return self.rates[tenor]
return self.nelson_siegel(tenor, self.beta0, self.beta1, self.beta2, self.tau)
def apply_shock(self, shock: Dict[str, float]) -> 'YieldCurveModel':
"""Apply basis point shocks to the curve"""
shocked_rates = {}
for tenor in self.tenors:
base_rate = self.get_rate(tenor)
bp_shock = 0
for shock_tenor, bp in shock.items():
shock_t = float(shock_tenor.replace('Y', '').replace('M', ''))
if 'M' in shock_tenor:
shock_t /= 12
if abs(tenor - shock_t) < 0.1:
bp_shock = bp / 10000 # Convert bps to decimal
shocked_rates[tenor] = base_rate + bp_shock
new_curve = YieldCurveModel()
new_curve.calibrate(shocked_rates)
return new_curve
# =============================================================================
# TREASURY PORTFOLIO
# =============================================================================
class TreasuryPortfolio:
"""Treasury portfolio management"""
def __init__(self, name: str = "Treasury Portfolio"):
self.name = name
self.positions: List[TreasuryPosition] = []
self.yield_curve = YieldCurveModel()
self._load_default_yield_curve()
def _load_default_yield_curve(self):
"""Load default yield curve (approximation of current rates)"""
default_rates = {
0.25: 0.0535, # 3M
0.5: 0.0525, # 6M
1: 0.050, # 1Y
2: 0.047, # 2Y
3: 0.045, # 3Y
5: 0.043, # 5Y
7: 0.044, # 7Y
10: 0.043, # 10Y
20: 0.046, # 20Y
30: 0.045 # 30Y
}
self.yield_curve.calibrate(default_rates)
def add_position(self, position: TreasuryPosition):
"""Add a position to the portfolio"""
self.positions.append(position)
def remove_position(self, cusip: str):
"""Remove a position by CUSIP"""
self.positions = [p for p in self.positions if p.cusip != cusip]
@property
def market_value(self) -> float:
"""Total portfolio market value"""
return sum(p.market_value for p in self.positions)
@property
def total_face_value(self) -> float:
"""Total face value"""
return sum(p.face_value for p in self.positions)
@property
def portfolio_duration(self) -> float:
"""Weighted average duration"""
total_mv = self.market_value
if total_mv == 0:
return 0
return sum(p.duration * p.market_value for p in self.positions) / total_mv
@property
def portfolio_convexity(self) -> float:
"""Weighted average convexity"""
total_mv = self.market_value
if total_mv == 0:
return 0
return sum(p.convexity * p.market_value for p in self.positions) / total_mv
@property
def portfolio_dv01(self) -> float:
"""Portfolio DV01"""
return sum(p.dv01 for p in self.positions)
def get_position_weights(self) -> Dict[str, float]:
"""Get position weights"""
total_mv = self.market_value
return {p.cusip: p.market_value / total_mv for p in self.positions}
def get_duration_bucket_exposure(self) -> Dict[str, float]:
"""Get exposure by duration bucket"""
buckets = {
'0-1Y': 0, '1-3Y': 0, '3-5Y': 0,
'5-10Y': 0, '10-20Y': 0, '20Y+': 0
}
for p in self.positions:
ytm = p.years_to_maturity
mv = p.market_value
if ytm < 1:
buckets['0-1Y'] += mv
elif ytm < 3:
buckets['1-3Y'] += mv
elif ytm < 5:
buckets['3-5Y'] += mv
elif ytm < 10:
buckets['5-10Y'] += mv
elif ytm < 20:
buckets['10-20Y'] += mv
else:
buckets['20Y+'] += mv
return buckets
def to_dataframe(self) -> pd.DataFrame:
"""Convert portfolio to DataFrame"""
data = []
for p in self.positions:
data.append({
'CUSIP': p.cusip,
'Type': p.security_type,
'Face Value': p.face_value,
'Market Value': p.market_value,
'Coupon (%)': p.coupon_rate,
'Maturity': p.maturity_date.strftime('%Y-%m-%d'),
'YTM (Years)': round(p.years_to_maturity, 2),
'Duration': round(p.duration, 2),
'Convexity': round(p.convexity, 2),
'DV01 ($)': round(p.dv01, 2),
'Weight (%)': round(p.market_value / self.market_value * 100, 2)
})
return pd.DataFrame(data)
# =============================================================================
# VAR CALCULATOR
# =============================================================================
class VaRCalculator:
"""Multi-method VaR calculator"""
def __init__(self, portfolio: TreasuryPortfolio):
self.portfolio = portfolio
self.returns_data = None
self.lookback_days = 252
def generate_synthetic_returns(self, n_days: int = 1000) -> np.ndarray:
"""Generate synthetic returns based on portfolio characteristics"""
# Portfolio duration as base volatility driver
duration = self.portfolio.portfolio_duration
base_vol = duration * 0.005 # Approximation: duration * daily rate vol
# Generate returns with fat tails
np.random.seed(42)
returns = np.random.standard_t(df=5, size=n_days) * base_vol
# Add some autocorrelation
for i in range(1, len(returns)):
returns[i] += 0.1 * returns[i-1]
return returns
def load_historical_data(self, tickers: List[str], days: int = 756):
"""Load historical price data"""
try:
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
data = yf.download(tickers, start=start_date, end=end_date,
progress=False)['Adj Close']
if isinstance(data, pd.Series):
data = data.to_frame()
self.returns_data = data.pct_change().dropna()
self.lookback_days = len(self.returns_data)
return True
except Exception as e:
print(f"Error loading data: {e}")
return False
def historical_var(self, returns: np.ndarray, confidence: float = 0.95) -> Tuple[float, float]:
"""Historical simulation VaR"""
var_pct = np.percentile(returns, (1 - confidence) * 100)
var_amount = -var_pct * self.portfolio.market_value
# Expected Shortfall
es_pct = np.mean(returns[returns <= var_pct])
es_amount = -es_pct * self.portfolio.market_value
return var_amount, es_amount
def parametric_var(self, returns: np.ndarray, confidence: float = 0.95) -> Tuple[float, float]:
"""Parametric (Variance-Covariance) VaR"""
mu = np.mean(returns)
sigma = np.std(returns)
# VaR using normal distribution
z_score = stats.norm.ppf(1 - confidence)
var_pct = -(mu + z_score * sigma)
var_amount = var_pct * self.portfolio.market_value
# ES for normal distribution
es_z = stats.norm.pdf(z_score) / (1 - confidence)
es_pct = -(mu - sigma * es_z)
es_amount = es_pct * self.portfolio.market_value
return var_amount, es_amount
def cornish_fisher_var(self, returns: np.ndarray, confidence: float = 0.95) -> Tuple[float, float]:
"""Cornish-Fisher expansion VaR (adjusts for skewness and kurtosis)"""
mu = np.mean(returns)
sigma = np.std(returns)
skew = stats.skew(returns)
kurt = stats.kurtosis(returns)
# Standard normal quantile
z = stats.norm.ppf(1 - confidence)
# Cornish-Fisher expansion
z_cf = (z + (z**2 - 1) * skew / 6 +
(z**3 - 3*z) * kurt / 24 -
(2*z**3 - 5*z) * skew**2 / 36)
var_pct = -(mu + z_cf * sigma)
var_amount = var_pct * self.portfolio.market_value
# Approximate ES
tail_returns = returns[returns <= np.percentile(returns, (1-confidence)*100)]
es_pct = -np.mean(tail_returns) if len(tail_returns) > 0 else var_pct
es_amount = es_pct * self.portfolio.market_value
return var_amount, es_amount
def monte_carlo_var(self, returns: np.ndarray, confidence: float = 0.95,
n_simulations: int = 10000) -> Tuple[float, float]:
"""Monte Carlo simulation VaR"""
mu = np.mean(returns)
sigma = np.std(returns)
# Fit t-distribution for fat tails
df, loc, scale = stats.t.fit(returns)
# Generate simulations
simulated_returns = stats.t.rvs(df, loc=mu, scale=scale, size=n_simulations)
var_pct = np.percentile(simulated_returns, (1 - confidence) * 100)
var_amount = -var_pct * self.portfolio.market_value
# Expected Shortfall
es_pct = np.mean(simulated_returns[simulated_returns <= var_pct])
es_amount = -es_pct * self.portfolio.market_value
return var_amount, es_amount
def calculate_var(self, method: VaRMethod, confidence: float = 0.95,
returns: np.ndarray = None) -> VaRResult:
"""Calculate VaR using specified method"""
if returns is None:
returns = self.generate_synthetic_returns()
start_time = datetime.now()
if method == VaRMethod.HISTORICAL:
var, es = self.historical_var(returns, confidence)
elif method == VaRMethod.PARAMETRIC:
var, es = self.parametric_var(returns, confidence)
elif method == VaRMethod.CORNISH_FISHER:
var, es = self.cornish_fisher_var(returns, confidence)
elif method == VaRMethod.MONTE_CARLO:
var, es = self.monte_carlo_var(returns, confidence)
else:
raise ValueError(f"Unknown method: {method}")
portfolio_value = self.portfolio.market_value
# Calculate additional metrics
additional = {
'Skewness': stats.skew(returns),
'Kurtosis': stats.kurtosis(returns),
'Volatility (ann.)': np.std(returns) * np.sqrt(252),
'Sharpe Ratio': np.mean(returns) / np.std(returns) * np.sqrt(252) if np.std(returns) > 0 else 0,
'Max Drawdown': self._calculate_max_drawdown(returns)
}
return VaRResult(
method=method,
confidence_level=confidence,
var_amount=round(var, 2),
var_percentage=round(var / portfolio_value * 100, 4),
expected_shortfall=round(es, 2),
es_percentage=round(es / portfolio_value * 100, 4),
portfolio_value=portfolio_value,
calculation_time=datetime.now(),
lookback_period=len(returns),
additional_metrics=additional
)
def _calculate_max_drawdown(self, returns: np.ndarray) -> float:
"""Calculate maximum drawdown"""
cumulative = np.cumprod(1 + returns)
running_max = np.maximum.accumulate(cumulative)
drawdowns = (cumulative - running_max) / running_max
return np.min(drawdowns)
def var_by_confidence(self, method: VaRMethod,
confidences: List[float] = None) -> pd.DataFrame:
"""Calculate VaR at multiple confidence levels"""
if confidences is None:
confidences = [0.90, 0.95, 0.97, 0.99, 0.995]
returns = self.generate_synthetic_returns()
results = []
for conf in confidences:
result = self.calculate_var(method, conf, returns)
results.append({
'Confidence': f"{conf*100:.1f}%",
'VaR ($)': result.var_amount,
'VaR (%)': result.var_percentage,
'ES ($)': result.expected_shortfall,
'ES (%)': result.es_percentage
})
return pd.DataFrame(results)
def rolling_var(self, method: VaRMethod, window: int = 252,
confidence: float = 0.95) -> pd.DataFrame:
"""Calculate rolling VaR"""
returns = self.generate_synthetic_returns(2000)
dates = pd.date_range(end=datetime.now(), periods=len(returns))
rolling_vars = []
rolling_es = []
for i in range(window, len(returns)):
window_returns = returns[i-window:i]
result = self.calculate_var(method, confidence, window_returns)
rolling_vars.append(result.var_amount)
rolling_es.append(result.expected_shortfall)
df = pd.DataFrame({
'Date': dates[window:],
f'VaR ({confidence*100:.0f}%)': rolling_vars,
f'ES ({confidence*100:.0f}%)': rolling_es
})
df.set_index('Date', inplace=True)
return df
# =============================================================================
# STRESS TESTING ENGINE
# =============================================================================
class StressTestingEngine:
"""Comprehensive stress testing for treasury portfolios"""
def __init__(self, portfolio: TreasuryPortfolio):
self.portfolio = portfolio
self.scenarios: Dict[str, StressScenario] = {}
self._load_historical_scenarios()
self._load_hypothetical_scenarios()
def _load_historical_scenarios(self):
"""Load historical crisis scenarios"""
scenarios = [
StressScenario(
name="2008 Global Financial Crisis",
scenario_type=StressScenarioType.HISTORICAL,
description="Lehman Brothers collapse, credit freeze",
yield_curve_shock={
'3M': 400, '6M': 350, '1Y': 300, '2Y': 200,
'5Y': 100, '10Y': 50, '30Y': 30
},
spread_changes={'Agency': 150, 'Corporate': 500},
probability=0.01,
historical_date=datetime(2008, 9, 15)
),
StressScenario(
name="2013 Taper Tantrum",
scenario_type=StressScenarioType.HISTORICAL,
description="Fed taper announcement, bond sell-off",
yield_curve_shock={
'3M': 0, '6M': 10, '1Y': 50, '2Y': 100,
'5Y': 130, '10Y': 100, '30Y': 80
},
probability=0.02,
historical_date=datetime(2013, 5, 22)
),
StressScenario(
name="2020 COVID Crisis",
scenario_type=StressScenarioType.HISTORICAL,
description="Pandemic panic, flight to quality",
yield_curve_shock={
'3M': -100, '6M': -80, '1Y': -60, '2Y': -40,
'5Y': -30, '10Y': -25, '30Y': -20
},
spread_changes={'MBS': 50},
probability=0.02,
historical_date=datetime(2020, 3, 9)
),
StressScenario(
name="2022 Rate Hike Cycle",
scenario_type=StressScenarioType.HISTORICAL,
description="Aggressive Fed tightening",
yield_curve_shock={
'3M': 400, '6M': 380, '1Y': 350, '2Y': 300,
'5Y': 200, '10Y': 150, '30Y': 100
},
probability=0.03,
historical_date=datetime(2022, 3, 15)
),
StressScenario(
name="2023 Regional Banking Crisis",
scenario_type=StressScenarioType.HISTORICAL,
description="SVB collapse, deposit flight",
yield_curve_shock={
'3M': -50, '6M': -40, '1Y': -30, '2Y': -50,
'5Y': -40, '10Y': -30, '30Y': -20
},
probability=0.02,
historical_date=datetime(2023, 3, 10)
),
]
for s in scenarios:
self.scenarios[s.name] = s
def _load_hypothetical_scenarios(self):
"""Load hypothetical stress scenarios"""
scenarios = [
StressScenario(
name="Parallel Shift +200bps",
scenario_type=StressScenarioType.HYPOTHETICAL,
description="Sharp rise in all rates",
yield_curve_shock={
'3M': 200, '6M': 200, '1Y': 200, '2Y': 200,
'5Y': 200, '10Y': 200, '30Y': 200
},
probability=0.05
),
StressScenario(
name="Parallel Shift -200bps",
scenario_type=StressScenarioType.HYPOTHETICAL,
description="Sharp fall in all rates",
yield_curve_shock={
'3M': -200, '6M': -200, '1Y': -200, '2Y': -200,
'5Y': -200, '10Y': -200, '30Y': -200
},
probability=0.05
),
StressScenario(
name="Steepener (2s10s +150bps)",
scenario_type=StressScenarioType.HYPOTHETICAL,
description="Curve steepening",
yield_curve_shock={
'3M': -50, '6M': -25, '1Y': 0, '2Y': 25,
'5Y': 75, '10Y': 175, '30Y': 200
},
probability=0.05
),
StressScenario(
name="Flattener (2s10s -150bps)",
scenario_type=StressScenarioType.HYPOTHETICAL,
description="Curve flattening",
yield_curve_shock={
'3M': 200, '6M': 175, '1Y': 150, '2Y': 125,
'5Y': 50, '10Y': -25, '30Y': -50
},
probability=0.05
),
StressScenario(
name="Inverted to Normal",
scenario_type=StressScenarioType.HYPOTHETICAL,
description="Curve normalization from inversion",
yield_curve_shock={
'3M': -150, '6M': -100, '1Y': -50, '2Y': 0,
'5Y': 50, '10Y': 100, '30Y': 100
},
probability=0.10
),
StressScenario(
name="Stagflation",
scenario_type=StressScenarioType.MACRO,
description="High inflation, low growth",
yield_curve_shock={
'3M': 300, '6M': 280, '1Y': 250, '2Y': 200,
'5Y': 150, '10Y': 120, '30Y': 100
},
inflation_shock=0.03,
probability=0.10
),
StressScenario(
name="Deflationary Recession",
scenario_type=StressScenarioType.MACRO,
description="Economic contraction, deflation",
yield_curve_shock={
'3M': -200, '6M': -180, '1Y': -150, '2Y': -100,
'5Y': -50, '10Y': -30, '30Y': -20
},
inflation_shock=-0.02,
probability=0.05
),
]
for s in scenarios:
self.scenarios[s.name] = s
def add_custom_scenario(self, scenario: StressScenario):
"""Add a custom scenario"""
self.scenarios[scenario.name] = scenario
def apply_scenario(self, scenario: StressScenario) -> Dict:
"""Apply a stress scenario to the portfolio"""
portfolio_mv = self.portfolio.market_value
total_pnl = 0
position_impacts = []
for position in self.portfolio.positions:
ytm = position.years_to_maturity
# Find appropriate shock
shock_bp = 0
for tenor_str, bp in scenario.yield_curve_shock.items():
tenor = float(tenor_str.replace('Y', '').replace('M', ''))
if 'M' in tenor_str:
tenor /= 12
# Interpolate shock
if ytm <= tenor + 0.5 and ytm >= tenor - 0.5:
shock_bp = bp
break
elif ytm < 0.5:
shock_bp = scenario.yield_curve_shock.get('3M', 0)
elif ytm > 20:
shock_bp = scenario.yield_curve_shock.get('30Y', 0)
# Calculate P&L using duration and convexity
shock_decimal = shock_bp / 10000 # Convert bps to decimal
# Price change = -D * Δy + 0.5 * C * (Δy)²
price_change_pct = (-position.duration * shock_decimal +
0.5 * position.convexity * shock_decimal ** 2)
pnl = position.market_value * price_change_pct
total_pnl += pnl
position_impacts.append({
'CUSIP': position.cusip,
'Type': position.security_type,
'Market Value': position.market_value,
'YTM (Years)': round(ytm, 2),
'Duration': position.duration,
'Rate Shock (bps)': shock_bp,
'P&L ($)': round(pnl, 2),
'P&L (%)': round(price_change_pct * 100, 4)
})
# Calculate impact metrics
impact_pct = total_pnl / portfolio_mv * 100 if portfolio_mv > 0 else 0
return {
'scenario_name': scenario.name,
'scenario_type': scenario.scenario_type.value,
'description': scenario.description,
'total_pnl': round(total_pnl, 2),
'impact_pct': round(impact_pct, 4),
'portfolio_value_before': portfolio_mv,
'portfolio_value_after': round(portfolio_mv + total_pnl, 2),
'position_impacts': position_impacts,
'probability': scenario.probability
}
def run_all_scenarios(self) -> pd.DataFrame:
"""Run all scenarios and return summary"""
results = []
for name, scenario in self.scenarios.items():
impact = self.apply_scenario(scenario)
results.append({
'Scenario': name,
'Type': scenario.scenario_type.value,
'P&L ($)': impact['total_pnl'],
'P&L (%)': impact['impact_pct'],
'Probability': f"{scenario.probability*100:.1f}%",
'Expected Loss ($)': round(impact['total_pnl'] * scenario.probability, 2)
})
df = pd.DataFrame(results)
df = df.sort_values('P&L ($)', ascending=True)
return df
def reverse_stress_test(self, target_loss_pct: float = -20.0) -> Dict:
"""Find scenarios that would cause a specific loss"""
results = []
portfolio_mv = self.portfolio.market_value
target_loss = portfolio_mv * target_loss_pct / 100
# Test different yield shocks
shock_range = range(-500, 501, 25)
for shock_bp in shock_range:
parallel_shock = {f'{t}Y': shock_bp for t in ['3M', '6M', '1Y', '2Y', '5Y', '10Y', '30Y']}
scenario = StressScenario(
name=f"Parallel {shock_bp:+}bps",
scenario_type=StressScenarioType.REVERSE,
description=f"Parallel shift of {shock_bp} basis points",
yield_curve_shock=parallel_shock,
probability=abs(shock_bp) / 10000
)
impact = self.apply_scenario(scenario)
if impact['total_pnl'] <= target_loss:
results.append({
'shock_bp': shock_bp,
'pnl': impact['total_pnl'],
'pnl_pct': impact['impact_pct']
})
return {
'target_loss_pct': target_loss_pct,
'target_loss_amount': target_loss,
'breaching_scenarios': sorted(results, key=lambda x: x['pnl'])[:5]
}
def scenario_correlation_analysis(self) -> pd.DataFrame:
"""Analyze correlation between scenario impacts"""
scenario_returns = {}
for name, scenario in self.scenarios.items():
impact = self.apply_scenario(scenario)
position_pnl = [p['P&L ($)'] for p in impact['position_impacts']]
if len(position_pnl) > 1:
scenario_returns[name] = position_pnl
if len(scenario_returns) < 2:
return pd.DataFrame()
df = pd.DataFrame(scenario_returns)
return df.corr()
# =============================================================================
# VISUALIZATION DASHBOARD
# =============================================================================
class RiskDashboard:
"""Interactive visualization dashboard"""
def __init__(self, portfolio: TreasuryPortfolio):
self.portfolio = portfolio
self.var_calculator = VaRCalculator(portfolio)
self.stress_engine = StressTestingEngine(portfolio)
def plot_var_comparison(self, save_path: str = None):
"""Compare VaR across methods and confidence levels"""
methods = [VaRMethod.HISTORICAL, VaRMethod.PARAMETRIC,
VaRMethod.CORNISH_FISHER, VaRMethod.MONTE_CARLO]
confidences = [0.90, 0.95, 0.99]
fig = make_subplots(
rows=1, cols=2,
subplot_titles=('VaR Comparison by Method', 'VaR Comparison by Confidence'),
specs=[[{'type': 'bar'}, {'type': 'bar'}]]
)
returns = self.var_calculator.generate_synthetic_returns()
# By method at 95% confidence
method_vars = []
for method in methods:
result = self.var_calculator.calculate_var(method, 0.95, returns)
method_vars.append({'Method': method.value, 'VaR': result.var_amount, 'ES': result.expected_shortfall})
df_methods = pd.DataFrame(method_vars)
fig.add_trace(
go.Bar(name='VaR', x=df_methods['Method'], y=df_methods['VaR'],
marker_color='#1f77b4'),
row=1, col=1
)
fig.add_trace(
go.Bar(name='ES', x=df_methods['Method'], y=df_methods['ES'],
marker_color='#ff7f0e'),
row=1, col=1
)
# By confidence level (Monte Carlo)
conf_vars = []
for conf in confidences:
result = self.var_calculator.calculate_var(VaRMethod.MONTE_CARLO, conf, returns)
conf_vars.append({'Confidence': f"{conf*100:.0f}%", 'VaR': result.var_amount, 'ES': result.expected_shortfall})
df_conf = pd.DataFrame(conf_vars)
fig.add_trace(
go.Bar(name='VaR', x=df_conf['Confidence'], y=df_conf['VaR'],
marker_color='#1f77b4', showlegend=False),
row=1, col=2
)
fig.add_trace(
go.Bar(name='ES', x=df_conf['Confidence'], y=df_conf['ES'],
marker_color='#ff7f0e', showlegend=False),
row=1, col=2
)
fig.update_layout(
title_text='Value at Risk Analysis',
barmode='group',
height=500,
template='plotly_white'
)
fig.update_yaxes(title_text='Loss ($)', row=1, col=1)
fig.update_yaxes(title_text='Loss ($)', row=1, col=2)
if save_path:
fig.write_html(save_path)
return fig
def plot_stress_test_results(self, save_path: str = None):
"""Visualize stress test results"""
results = self.stress_engine.run_all_scenarios()
# Color coding based on impact
colors = ['#d62728' if x < 0 else '#2ca02c' for x in results['P&L ($)']]
fig = go.Figure()
fig.add_trace(go.Bar(
x=results['Scenario'],
y=results['P&L ($)'],
marker_color=colors,
text=results['P&L (%)'].apply(lambda x: f'{x:.2f}%'),
textposition='outside'
))
fig.update_layout(
title='Stress Test Scenario Impacts',
xaxis_title='Scenario',
yaxis_title='P&L Impact ($)',
xaxis_tickangle=-45,
height=700,
template='plotly_white',
showlegend=False
)
if save_path:
fig.write_html(save_path)
return fig
def plot_yield_curve_scenarios(self, save_path: str = None):
"""Plot base and stressed yield curves"""
fig = go.Figure()
# Base curve
tenors = [0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30]
base_rates = [self.portfolio.yield_curve.get_rate(t) * 100 for t in tenors]
fig.add_trace(go.Scatter(
x=tenors, y=base_rates,
mode='lines+markers',
name='Base Case',
line=dict(color='#1f77b4', width=3)
))
# Select key scenarios
key_scenarios = [
'Parallel Shift +200bps',
'Parallel Shift -200bps',
'Steepener (2s10s +150bps)',
'Flattener (2s10s -150bps)'
]
colors = ['#d62728', '#2ca02c', '#9467bd', '#8c564b']
for scenario_name, color in zip(key_scenarios, colors):
scenario = self.stress_engine.scenarios.get(scenario_name)
if scenario:
stressed_rates = []
for t in tenors:
base = self.portfolio.yield_curve.get_rate(t) * 100
shock = 0
for tenor_str, bp in scenario.yield_curve_shock.items():
tenor_val = float(tenor_str.replace('Y', '').replace('M', ''))
if 'M' in tenor_str:
tenor_val /= 12
if abs(t - tenor_val) < 0.1:
shock = bp / 100
break
stressed_rates.append(base + shock)
fig.add_trace(go.Scatter(
x=tenors, y=stressed_rates,
mode='lines+markers',
name=scenario_name,
line=dict(color=color, width=2, dash='dash')
))
fig.update_layout(
title='Yield Curve Stress Scenarios',
xaxis_title='Tenor (Years)',
yaxis_title='Yield (%)',
height=600,
template='plotly_white',
legend=dict(yanchor='top', y=0.99, xanchor='left', x=0.01)
)
if save_path:
fig.write_html(save_path)
return fig
def plot_rolling_var(self, save_path: str = None):
"""Plot rolling VaR over time"""
rolling_df = self.var_calculator.rolling_var(VaRMethod.MONTE_CARLO, window=252)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=rolling_df.index,
y=rolling_df['VaR (95%)'],
mode='lines',
name='VaR (95%)',
line=dict(color='#1f77b4', width=2)
))
fig.add_trace(go.Scatter(
x=rolling_df.index,
y=rolling_df['ES (95%)'],
mode='lines',
name='Expected Shortfall (95%)',
line=dict(color='#ff7f0e', width=2)
))
fig.update_layout(
title='Rolling Value at Risk (1-Year Window)',
xaxis_title='Date',
yaxis_title='Risk Measure ($)',
height=500,
template='plotly_white'
)
if save_path:
fig.write_html(save_path)
return fig
def plot_return_distribution(self, save_path: str = None):
"""Plot return distribution with VaR markers"""
returns = self.var_calculator.generate_synthetic_returns()
var_95 = self.var_calculator.calculate_var(VaRMethod.MONTE_CARLO, 0.95, returns)
var_99 = self.var_calculator.calculate_var(VaRMethod.MONTE_CARLO, 0.99, returns)
fig = go.Figure()
# Histogram
fig.add_trace(go.Histogram(
x=returns * 100,
nbinsx=100,
name='Returns',
marker_color='#1f77b4',
opacity=0.7
))
# Add VaR lines
fig.add_vline(
x=-var_95.var_percentage,
line_dash='dash',
line_color='red',
annotation_text=f'VaR 95%: ${var_95.var_amount:,.0f}'
)
fig.add_vline(
x=-var_99.var_percentage,
line_dash='dash',
line_color='darkred',
annotation_text=f'VaR 99%: ${var_99.var_amount:,.0f}'
)
fig.update_layout(
title='Portfolio Return Distribution',
xaxis_title='Return (%)',
yaxis_title='Frequency',
height=500,
template='plotly_white'
)
if save_path:
fig.write_html(save_path)
return fig
def plot_portfolio_composition(self, save_path: str = None):
"""Plot portfolio composition and risk metrics"""
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Duration Bucket Exposure', 'Position Weights',
'Risk Metrics', 'Yield Curve Positioning'),
specs=[[{'type': 'pie'}, {'type': 'pie'}],
[{'type': 'bar'}, {'type': 'scatter'}]]
)
# Duration bucket exposure
buckets = self.portfolio.get_duration_bucket_exposure()
fig.add_trace(go.Pie(
labels=list(buckets.keys()),
values=list(buckets.values()),
name='Duration Buckets'
), row=1, col=1)
# Position weights
weights = self.portfolio.get_position_weights()
fig.add_trace(go.Pie(
labels=[p.cusip for p in self.portfolio.positions],
values=[p.market_value for p in self.portfolio.positions],
name='Positions'
), row=1, col=2)
# Risk metrics
metrics = {
'Duration': self.portfolio.portfolio_duration,
'Convexity': self.portfolio.portfolio_convexity / 100,
'DV01 (K)': self.portfolio.portfolio_dv01 / 1000
}
fig.add_trace(go.Bar(
x=list(metrics.keys()),
y=list(metrics.values()),
marker_color=['#1f77b4', '#ff7f0e', '#2ca02c']
), row=2, col=1)
# Yield curve positioning (maturity vs duration)
fig.add_trace(go.Scatter(
x=[p.years_to_maturity for p in self.portfolio.positions],
y=[p.duration for p in self.portfolio.positions],
mode='markers+text',
marker_size=[p.market_value / 100000 for p in self.portfolio.positions],
text=[p.cusip[:6] for p in self.portfolio.positions],
textposition='top center'
), row=2, col=2)
fig.update_layout(
title_text='Portfolio Analysis',
height=800,
template='plotly_white',
showlegend=False
)
if save_path:
fig.write_html(save_path)
return fig
def generate_report(self, output_dir: str = '.'):
"""Generate comprehensive risk report"""
import os
os.makedirs(output_dir, exist_ok=True)
print("=" * 80)
print("TREASURY PORTFOLIO RISK REPORT")
print(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 80)
# Portfolio Summary
print("\n1. PORTFOLIO SUMMARY")
print("-" * 40)
print(f" Market Value: ${self.portfolio.market_value:,.2f}")
print(f" Face Value: ${self.portfolio.total_face_value:,.2f}")
print(f" Positions: {len(self.portfolio.positions)}")
print(f" Duration: {self.portfolio.portfolio_duration:.2f} years")
print(f" Convexity: {self.portfolio.portfolio_convexity:.2f}")
print(f" DV01: ${self.portfolio.portfolio_dv01:,.2f}")
# VaR Analysis
print("\n2. VALUE AT RISK ANALYSIS")
print("-" * 40)
returns = self.var_calculator.generate_synthetic_returns()
for method in VaRMethod:
result = self.var_calculator.calculate_var(method, 0.95, returns)
print(f"\n {method.value}:")
print(f" VaR (95%): ${result.var_amount:,.2f} ({result.var_percentage:.4f}%)")
print(f" ES (95%): ${result.expected_shortfall:,.2f} ({result.es_percentage:.4f}%)")
# Stress Test Results
print("\n3. STRESS TEST RESULTS")
print("-" * 40)
stress_results = self.stress_engine.run_all_scenarios()
worst_scenarios = stress_results.head(5)
print("\n Top 5 Worst-Case Scenarios:")
for _, row in worst_scenarios.iterrows():
print(f" {row['Scenario']}: ${row['P&L ($)']:,.2f} ({row['P&L (%)']:.2f}%)")
# Generate plots
print("\n4. GENERATING VISUALIZATIONS")
print("-" * 40)
plots = [
('var_comparison.html', self.plot_var_comparison),
('stress_test_results.html', self.plot_stress_test_results),
('yield_curve_scenarios.html', self.plot_yield_curve_scenarios),
('rolling_var.html', self.plot_rolling_var),
('return_distribution.html', self.plot_return_distribution),
('portfolio_composition.html', self.plot_portfolio_composition),
]
for filename, plot_func in plots:
try:
plot_func(os.path.join(output_dir, filename))
print(f" ✓ Generated {filename}")
except Exception as e:
print(f" ✗ Error generating {filename}: {e}")
print("\n" + "=" * 80)
print(f"Report complete. Visualizations saved to {output_dir}/")
print("=" * 80)
return stress_results
# =============================================================================
# MAIN EXECUTION
# =============================================================================
def create_sample_portfolio() -> TreasuryPortfolio:
"""Create a sample treasury portfolio for demonstration"""
portfolio = TreasuryPortfolio("Sample Treasury Portfolio")
# Add diverse treasury positions
positions = [
# T-Bills
TreasuryPosition(
security_type="T-Bill",
cusip="US912795ZL78",
face_value=10_000_000,
coupon_rate=0,
maturity_date=datetime(2024, 6, 15),
purchase_date=datetime(2023, 12, 15),
purchase_price=98.5,
current_price=99.2
),
TreasuryPosition(
security_type="T-Bill",
cusip="US912795ZM61",
face_value=15_000_000,
coupon_rate=0,
maturity_date=datetime(2024, 9, 15),
purchase_date=datetime(2024, 3, 15),
purchase_price=97.8,
current_price=98.5
),
# T-Notes
TreasuryPosition(
security_type="T-Note",
cusip="US91282CDB56",
face_value=25_000_000,
coupon_rate=4.5,
maturity_date=datetime(2026, 5, 15),
purchase_date=datetime(2023, 5, 15),
purchase_price=99.5,
current_price=100.25
),
TreasuryPosition(
security_type="T-Note",
cusip="US912828ZT04",
face_value=20_000_000,
coupon_rate=3.875,
maturity_date=datetime(2028, 2, 15),
purchase_date=datetime(2023, 2, 15),
purchase_price=97.5,
current_price=98.75
),
TreasuryPosition(
security_type="T-Note",
cusip="US912828ZY78",
face_value=30_000_000,
coupon_rate=4.25,
maturity_date=datetime(2029, 8, 15),
purchase_date=datetime(2024, 2, 15),
purchase_price=98.0,
current_price=99.5
),
# T-Bonds
TreasuryPosition(
security_type="T-Bond",
cusip="US912810TN19",
face_value=15_000_000,
coupon_rate=3.0,
maturity_date=datetime(2041, 5, 15),
purchase_date=datetime(2021, 5, 15),
purchase_price=85.5,
current_price=88.25
),
TreasuryPosition(
security_type="T-Bond",
cusip="US912810TM36",
face_value=10_000_000,
coupon_rate=2.875,
maturity_date=datetime(2046, 2, 15),
purchase_date=datetime(2021, 2, 15),
purchase_price=80.0,
current_price=82.5
),
# TIPS
TreasuryPosition(
security_type="TIPS",
cusip="US912828ZU69",
face_value=8_000_000,
coupon_rate=0.125,
maturity_date=datetime(2027, 1, 15),
purchase_date=datetime(2022, 1, 15),
purchase_price=95.0,
current_price=97.0
),
TreasuryPosition(
security_type="TIPS",
cusip="US912828ZV52",
face_value=7_000_000,
coupon_rate=0.375,
maturity_date=datetime(2032, 2, 15),
purchase_date=datetime(2022, 2, 15),
purchase_price=90.0,
current_price=93.5
),
]
for pos in positions:
portfolio.add_position(pos)
return portfolio
def main():
"""Main execution function"""
print("\n" + "=" * 80)
print(" TREASURY INVESTMENT VAR AND STRESS TESTING SUITE")
print("=" * 80)
# Create sample portfolio
print("\n[1] Creating sample treasury portfolio...")
portfolio = create_sample_portfolio()
# Display portfolio details
print(f"\n Portfolio: {portfolio.name}")
print(f" Total Market Value: ${portfolio.market_value:,.2f}")
print(f" Number of Positions: {len(portfolio.positions)}")
print(f" Portfolio Duration: {portfolio.portfolio_duration:.2f} years")
print(f" Portfolio DV01: ${portfolio.portfolio_dv01:,.2f}")
# Display position details
print("\n[2] Portfolio Holdings:")
print("-" * 100)
portfolio_df = portfolio.to_dataframe()
print(portfolio_df.to_string(index=False))
# Initialize VaR Calculator
print("\n[3] Calculating Value at Risk...")
var_calc = VaRCalculator(portfolio)
# Calculate VaR using different methods
returns = var_calc.generate_synthetic_returns(1000)
print("\n VaR Results (95% Confidence):")
print(" " + "-" * 60)
print(f" {'Method':<30} {'VaR ($)':>15} {'ES ($)':>15}")
print(" " + "-" * 60)
for method in VaRMethod:
result = var_calc.calculate_var(method, 0.95, returns)
print(f" {method.value:<30} {result.var_amount:>15,.2f} {result.expected_shortfall:>15,.2f}")
# VaR at different confidence levels
print("\n VaR at Different Confidence Levels (Monte Carlo):")
print(" " + "-" * 50)
var_by_conf = var_calc.var_by_confidence(VaRMethod.MONTE_CARLO)
print(var_by_conf.to_string(index=False))
# Initialize Stress Testing Engine
print("\n[4] Running Stress Tests...")
stress_engine = StressTestingEngine(portfolio)
# Display available scenarios
print(f"\n Available Scenarios: {len(stress_engine.scenarios)}")
# Run all scenarios
stress_results = stress_engine.run_all_scenarios()
print("\n Stress Test Results:")
print(" " + "-" * 100)
print(stress_results.to_string(index=False))
# Reverse stress test
print("\n[5] Reverse Stress Test (Target Loss: 10%)...")
reverse_test = stress_engine.reverse_stress_test(-10.0)
print(f" Scenarios causing >10% loss:")
for scenario in reverse_test['breaching_scenarios']:
print(f" Parallel shift of {scenario['shock_bp']:+} bps: "
f"${scenario['pnl']:,.2f} ({scenario['pnl_pct']:.2f}%)")
# Generate Dashboard
print("\n[6] Generating Risk Dashboard...")
dashboard = RiskDashboard(portfolio)
# Generate all visualizations
dashboard.generate_report('./risk_reports')
# Display additional statistics
print("\n[7] Portfolio Risk Statistics:")
print(" " + "-" * 40)
# Generate more detailed statistics
result = var_calc.calculate_var(VaRMethod.MONTE_CARLO, 0.95, returns)
for metric, value in result.additional_metrics.items():
if 'Ratio' in metric or 'Drawdown' in metric:
print(f" {metric}: {value:.4f}")
else:
print(f" {metric}: {value:.6f}")
# Yield curve analysis
print("\n[8] Current Yield Curve:")
print(" " + "-" * 40)
tenors = [0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30]
print(f" {'Tenor':<10} {'Yield (%)':>10}")
print(" " + "-" * 22)
for t in tenors:
rate = portfolio.yield_curve.get_rate(t) * 100
print(f" {t:<10} {rate:>10.3f}")
print("\n" + "=" * 80)
print(" ANALYSIS COMPLETE")
print("=" * 80 + "\n")
return portfolio, var_calc, stress_engine, dashboard
if __name__ == "__main__":
portfolio, var_calc, stress_engine, dashboard = main()
Key Features
1. VaR Methodologies
- Historical Simulation: Uses actual historical returns distribution
- Parametric (Variance-Covariance): Assumes normal distribution
- Monte Carlo Simulation: Generates thousands of scenarios with fat-tail distributions
- Cornish-Fisher Expansion: Adjusts for skewness and kurtosis
2. Stress Testing Scenarios
- Historical Crises: 2008 GFC, 2013 Taper Tantrum, 2020 COVID, 2022 Rate Hikes
- Hypothetical Shocks: Parallel shifts, curve steepening/flattening
- Reverse Stress Testing: Find scenarios that cause target loss levels
- Macro Scenarios: Stagflation, deflationary recession
3. Risk Metrics
- Duration and convexity
- DV01 (Dollar Value of 01)
- Expected Shortfall (CVaR)
- Maximum drawdown
- Sharpe ratio
4. Visualizations
- VaR comparison charts
- Stress test impact visualization
- Yield curve scenarios
- Rolling VaR over time
- Return distribution with VaR markers
- Portfolio composition analysis
Output Examples
The suite generates an HTML dashboard with interactive charts:
./risk_reports/
├── var_comparison.html
├── stress_test_results.html
├── yield_curve_scenarios.html
├── rolling_var.html
├── return_distribution.html
└── portfolio_composition.html
This comprehensive suite provides treasury managers with the tools needed to understand and quantify their portfolio's risk exposure under both normal and stressed market conditions.