Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(quantlib): add Vasicek credit portfolio model and Spread DV01

santhreal4886a81613b4
diff --git a/agent/src/quantlib/credit.py b/agent/src/quantlib/credit.py
index 03d03cea5..b6a937f04 100644
--- a/agent/src/quantlib/credit.py
+++ b/agent/src/quantlib/credit.py
@@ -48,6 +48,9 @@ __all__ = [
"edf_reference_band",
"credit_spread_analysis",
"spread_term_structure",
+ "expected_loss",
+ "vasicek_credit_var",
+ "credit_spread_dv01",
]
@@ -673,3 +676,116 @@ def spread_term_structure(
)
records.append(pd.Series(row, name=issuer))
return pd.DataFrame(records)
+
+
+def expected_loss(ead: float, pd: float, lgd: float) -> float:
+ """Compute regulatory Expected Loss (EL = EAD * PD * LGD).
+
+ Args:
+ ead: Exposure at Default in currency units >= 0.
+ pd: Probability of Default in [0.0, 1.0].
+ lgd: Loss Given Default in [0.0, 1.0].
+
+ Returns:
+ Expected loss amount in currency units.
+
+ Raises:
+ ValueError: If ead < 0, pd not in [0, 1], or lgd not in [0, 1].
+ """
+ if ead < 0.0:
+ raise ValueError(f"ead must be non-negative, got {ead}")
+ if not (0.0 <= pd <= 1.0):
+ raise ValueError(f"pd must be in [0.0, 1.0], got {pd}")
+ if not (0.0 <= lgd <= 1.0):
+ raise ValueError(f"lgd must be in [0.0, 1.0], got {lgd}")
+ return float(ead * pd * lgd)
+
+
+def vasicek_credit_var(
+ ead: float,
+ pd: float,
+ lgd: float,
+ asset_correlation: float,
+ confidence: float = 0.999,
+) -> dict:
+ """Vasicek single-factor asymptotic credit risk portfolio model (Basel II/III capital framework).
+
+ Under the Asymptotic Single Risk Factor (ASRF) model, conditional default
+ probability at confidence level alpha is:
+ WCDR(alpha) = Phi( (Phi^{-1}(PD) + sqrt(rho) * Phi^{-1}(alpha)) / sqrt(1 - rho) )
+
+ where rho is the pairwise asset return correlation.
+
+ Args:
+ ead: Exposure at Default in currency units (positive).
+ pd: Probability of Default in (0.0, 1.0).
+ lgd: Loss Given Default fraction in [0.0, 1.0].
+ asset_correlation: Pairwise systematic asset correlation rho in [0.0, 1.0).
+ confidence: VaR confidence level in (0.0, 1.0) (Basel standard = 0.999).
+
+ Returns:
+ dict with keys:
+ * ``expected_loss`` (float): Base expected loss (EL).
+ * ``wcdr`` (float): Worst-case conditional default rate at confidence.
+ * ``worst_case_loss`` (float): Total portfolio loss at confidence (WCL).
+ * ``unexpected_loss`` (float): Economic capital / Credit VaR (WCL - EL).
+ * ``capital_ratio`` (float): Capital required as percentage of EAD.
+
+ Raises:
+ ValueError: If parameters violate domain constraints.
+ """
+ if ead <= 0.0:
+ raise ValueError(f"ead must be strictly positive, got {ead}")
+ if not (0.0 < pd < 1.0):
+ raise ValueError(f"pd must be in (0.0, 1.0), got {pd}")
+ if not (0.0 <= lgd <= 1.0):
+ raise ValueError(f"lgd must be in [0.0, 1.0], got {lgd}")
+ if not (0.0 <= asset_correlation < 1.0):
+ raise ValueError(f"asset_correlation must be in [0.0, 1.0), got {asset_correlation}")
+ if not (0.0 < confidence < 1.0):
+ raise ValueError(f"confidence must be in (0.0, 1.0), got {confidence}")
+
+ rho = asset_correlation
+ inv_pd = float(norm.ppf(pd))
+ inv_conf = float(norm.ppf(confidence))
+
+ numerator = inv_pd + np.sqrt(rho) * inv_conf
+ denominator = np.sqrt(1.0 - rho)
+ wcdr = float(norm.cdf(numerator / denominator))
+
+ el = expected_loss(ead, pd, lgd)
+ wcl = float(ead * lgd * wcdr)
+ ul = float(max(0.0, wcl - el))
+ capital_ratio = float(ul / ead) if ead > 0 else 0.0
+
+ return {
+ "expected_loss": el,
+ "wcdr": wcdr,
+ "worst_case_loss": wcl,
+ "unexpected_loss": ul,
+ "capital_ratio": capital_ratio,
+ }
+
+
+def credit_spread_dv01(
+ spread_duration: float,
+ price: float = 100.0,
+ face: float = 100.0,
+ par_amount: float = 1_000_000.0,
+) -> float:
+ """Calculate Credit Spread DV01 (CS01 / Spread DV01) - dollar value of a 1 bp widening in credit spread.
+
+ CS01 = Spread Duration * (Price / Face) * 0.0001 * Par Position
+
+ Args:
+ spread_duration: Modified/spread duration in years.
+ price: Current clean market price of the credit instrument.
+ face: Quoted par base (standard 100.0).
+ par_amount: Total par notional held in position.
+
+ Returns:
+ Dollar loss for a 1 bp increase in credit spread (positive float).
+ """
+ if face <= 0.0 or price <= 0.0 or par_amount <= 0.0 or spread_duration < 0.0:
+ raise ValueError("price, face, par_amount must be positive and spread_duration non-negative")
+ return float(spread_duration * (price / face) * 1e-4 * par_amount)
diff --git a/agent/tests/quantlib/test_credit.py b/agent/tests/quantlib/test_credit.py
index 91bc92dc1..b99f29913 100644
--- a/agent/tests/quantlib/test_credit.py
+++ b/agent/tests/quantlib/test_credit.py
@@ -21,13 +21,16 @@ from src.quantlib.credit import (
AltmanZScore,
altman_z_score,
credit_spread_analysis,
+ credit_spread_dv01,
distance_to_default,
edf_reference_band,
+ expected_loss,
kmv_default_point,
kmv_distance_to_default,
merton_asset_solve,
merton_model,
spread_term_structure,
+ vasicek_credit_var,
)
# One balance sheet, reused so the three variants can be compared like for like.
@@ -496,3 +499,48 @@ def test_spread_term_structure_validates_its_inputs():
spread_term_structure({}, {1: 0.02})
with pytest.raises(ValueError, match="unknown input_unit"):
spread_term_structure({"x": {1: 0.025}}, {1: 0.02}, input_unit="ratio")
+
+
+# --------------------------------------------------------------------------
+# Vasicek Credit Risk & Expected Loss Tests
+# --------------------------------------------------------------------------
+
+
+def test_expected_loss_exact_multiplication():
+ # EAD = $10,000,000, PD = 2%, LGD = 45% -> EL = 10,000,000 * 0.02 * 0.45 = $90,000
+ assert expected_loss(10_000_000.0, 0.02, 0.45) == pytest.approx(90_000.0)
+
+
+def test_vasicek_credit_var_monotonic_with_correlation():
+ ead = 1_000_000.0
+ pd_val = 0.01
+ lgd = 0.40
+
+ res_low_rho = vasicek_credit_var(ead, pd_val, lgd, asset_correlation=0.10, confidence=0.999)
+ res_high_rho = vasicek_credit_var(ead, pd_val, lgd, asset_correlation=0.30, confidence=0.999)
+
+ assert res_low_rho["expected_loss"] == pytest.approx(res_high_rho["expected_loss"])
+ # Higher correlation leads to higher tail risk (WCDR and unexpected loss)
+ assert res_high_rho["wcdr"] > res_low_rho["wcdr"]
+ assert res_high_rho["unexpected_loss"] > res_low_rho["unexpected_loss"]
+ assert res_high_rho["capital_ratio"] > res_low_rho["capital_ratio"]
+
+
+def test_credit_spread_dv01_exact():
+ # 5.0 year spread duration on $1,000,000 par at par price 100:
+ # CS01 = 5.0 * (100/100) * 1e-4 * 1,000,000 = $500
+ cs01 = credit_spread_dv01(spread_duration=5.0, price=100.0, face=100.0, par_amount=1_000_000.0)
+ assert cs01 == pytest.approx(500.0)
+
+
+def test_vasicek_input_validation():
+ with pytest.raises(ValueError, match="ead must be strictly positive"):
+ vasicek_credit_var(-100.0, 0.01, 0.4, 0.1)
+ with pytest.raises(ValueError, match="pd must be in"):
+ vasicek_credit_var(1000.0, 1.5, 0.4, 0.1)
+ with pytest.raises(ValueError, match="asset_correlation"):
+ vasicek_credit_var(1000.0, 0.01, 0.4, 1.0)
+ with pytest.raises(ValueError, match="confidence"):
+ vasicek_credit_var(1000.0, 0.01, 0.4, 0.1, confidence=1.5)
+ with pytest.raises(ValueError, match="spread_duration non-negative"):
+ credit_spread_dv01(spread_duration=-1.0)