Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge branch 'pr1167' into quantlib-batch

Haozhe Wue1fff8aa0a73
diff --cc agent/src/quantlib/credit.py
index f142442bf,9ce85f0ed..5cddeb591
--- a/agent/src/quantlib/credit.py
+++ b/agent/src/quantlib/credit.py
@@@ -33,9 -48,9 +33,12 @@@ __all__ =
"edf_reference_band",
"credit_spread_analysis",
"spread_term_structure",
+ "hazard_rate_to_survival_probability",
+ "survival_probability_to_hazard_rate",
+ "cds_price",
+ "expected_loss",
+ "vasicek_credit_var",
+ "credit_spread_dv01",
]
@@@ -652,147 -678,118 +655,262 @@@ def spread_term_structure
return pd.DataFrame(records)
+def hazard_rate_to_survival_probability(hazard_rate: float, tenor_years: float) -> float:
+ """Convert a constant hazard rate lambda to cumulative survival probability Q(T) = exp(-lambda * T).
+
+ Args:
+ hazard_rate: Annualised default intensity / hazard rate lambda >= 0.
+ tenor_years: Time horizon in years >= 0.
+
+ Returns:
+ Survival probability in [0.0, 1.0].
+
+ Raises:
+ ValueError: If hazard_rate or tenor_years is negative.
+ """
+ if hazard_rate < 0.0 or tenor_years < 0.0:
+ raise ValueError(f"hazard_rate and tenor_years must be non-negative, got {hazard_rate}, {tenor_years}")
+ return float(np.exp(-hazard_rate * tenor_years))
+
+
+def survival_probability_to_hazard_rate(survival_prob: float, tenor_years: float) -> float:
+ """Convert a survival probability Q(T) to implied constant hazard rate lambda = -ln(Q(T)) / T.
+
+ Args:
+ survival_prob: Survival probability in (0.0, 1.0].
+ tenor_years: Time horizon in years > 0.
+
+ Returns:
+ Annualised hazard rate lambda.
+
+ Raises:
+ ValueError: If survival_prob is not in (0.0, 1.0] or tenor_years <= 0.
+ """
+ if survival_prob <= 0.0 or survival_prob > 1.0:
+ raise ValueError(f"survival_prob must be in (0.0, 1.0], got {survival_prob}")
+ if tenor_years <= 0.0:
+ raise ValueError(f"tenor_years must be strictly positive, got {tenor_years}")
+ return float(-np.log(survival_prob) / tenor_years)
+
+
+def cds_price(
+ spread_bps: float,
+ recovery_rate: float = 0.40,
+ tenor_years: float = 5.0,
+ risk_free_rate: float = 0.03,
+ coupon_bps: float = 100.0,
+ notional: float = 10_000_000.0,
+ payment_frequency: int = 4,
+) -> dict:
+ """ISDA standard model single-name Credit Default Swap (CDS) valuation engine.
+
+ Computes the implied hazard rate, survival probability curve, Risky Present Value
+ of a Basis Point (RPV01), protection leg PV, premium leg PV, fair par spread,
+ and mark-to-market (MTM) upfront cash payment.
+
+ Args:
+ spread_bps: Market quoted par CDS spread in basis points (e.g. 150.0 for 150 bps).
+ recovery_rate: Expected recovery rate on default in [0.0, 1.0) (standard senior unsecured = 0.40).
+ tenor_years: Contract maturity in years > 0 (standard benchmark = 5.0 years).
+ risk_free_rate: Continuously compounded annual risk-free discount rate.
+ coupon_bps: Fixed running coupon in basis points (standard 100 bps IG, 500 bps HY).
+ notional: Contract notional amount in currency units.
+ payment_frequency: Premium coupon payment frequency per year (standard quarterly = 4).
+
+ Returns:
+ dict with keys:
+ * ``hazard_rate`` (float): Implied constant hazard rate (default intensity).
+ * ``survival_probability`` (float): Probability of survival to maturity Q(T).
+ * ``default_probability`` (float): Cumulative probability of default 1 - Q(T).
+ * ``rpv01`` (float): Risky annuity (present value of unit running spread per dollar notional).
+ * ``protection_leg_pv`` (float): Present value of default protection per dollar notional.
+ * ``premium_leg_pv`` (float): Present value of fixed running premium per dollar notional.
+ * ``par_spread_bps`` (float): Model par spread in basis points.
+ * ``upfront_pct`` (float): Upfront payment as decimal fraction of notional.
+ * ``upfront_amount`` (float): Net upfront cash payment (positive = buyer pays seller).
+ * ``buyer_mtm`` (float): Mark-to-market value for the protection buyer.
+
+ Raises:
+ ValueError: If spread_bps < 0, recovery_rate not in [0, 1), tenor_years <= 0, or notional <= 0.
+ """
+ if spread_bps < 0.0:
+ raise ValueError(f"spread_bps must be non-negative, got {spread_bps}")
+ if not (0.0 <= recovery_rate < 1.0):
+ raise ValueError(f"recovery_rate must be in [0.0, 1.0), got {recovery_rate}")
+ if tenor_years <= 0.0:
+ raise ValueError(f"tenor_years must be strictly positive, got {tenor_years}")
+ if notional <= 0.0:
+ raise ValueError(f"notional must be strictly positive, got {notional}")
+ if payment_frequency <= 0:
+ raise ValueError(f"payment_frequency must be positive, got {payment_frequency}")
+
+ s_dec = spread_bps / 10_000.0
+ c_dec = coupon_bps / 10_000.0
+ lgd = 1.0 - recovery_rate
+
+ # Implied hazard rate lambda ≈ s / LGD
+ lambda_hazard = float(s_dec / lgd) if lgd > 0 else 0.0
+
+ n_periods = max(1, int(round(tenor_years * payment_frequency)))
+ t_grid = np.linspace(tenor_years / n_periods, tenor_years, n_periods)
+ t_prev = np.r_[0.0, t_grid[:-1]]
+ dts = t_grid - t_prev
+ t_mid = 0.5 * (t_prev + t_grid)
+
+ # Survival probabilities Q(t) = exp(-lambda * t)
+ q_grid = np.exp(-lambda_hazard * t_grid)
+ q_prev = np.r_[1.0, q_grid[:-1]]
+
+ # Discount factors D(t) = exp(-r * t)
+ df_grid = np.exp(-risk_free_rate * t_grid)
+ df_mid = np.exp(-risk_free_rate * t_mid)
+
+ # Premium leg / RPV01: sum(dt_i * D(t_i) * Q(t_i)) + accrual on default
+ premium_cashflow = np.sum(dts * df_grid * q_grid)
+ accrual_cashflow = np.sum(0.5 * dts * df_mid * (q_prev - q_grid))
+ rpv01 = float(premium_cashflow + accrual_cashflow)
+
+ # Protection leg: sum( LGD * D(t_mid) * (Q(t_{i-1}) - Q(t_i)) )
+ default_prob_steps = q_prev - q_grid
+ prot_leg_pv = float(lgd * np.sum(df_mid * default_prob_steps))
+
+ # Par spread in bps
+ par_spread = float((prot_leg_pv / rpv01) * 10_000.0) if rpv01 > 0 else spread_bps
+
+ # Premium leg PV for running coupon c
+ prem_leg_pv = float(c_dec * rpv01)
+
+ # Upfront percentage and amount
+ upfront_pct = float(prot_leg_pv - prem_leg_pv)
+ upfront_amt = float(upfront_pct * notional)
+
+ survival_T = float(np.exp(-lambda_hazard * tenor_years))
+ default_prob_T = float(1.0 - survival_T)
+
+ return {
+ "hazard_rate": lambda_hazard,
+ "survival_probability": survival_T,
+ "default_probability": default_prob_T,
+ "rpv01": rpv01,
+ "protection_leg_pv": prot_leg_pv,
+ "premium_leg_pv": prem_leg_pv,
+ "par_spread_bps": par_spread,
+ "upfront_pct": upfront_pct,
+ "upfront_amount": upfront_amt,
+ "buyer_mtm": upfront_amt,
+ }
+ 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 decimal fraction 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).
+
+ Raises:
+ ValueError: If price, face, or par_amount is not positive, or if
+ spread_duration is negative.
+ """
+ 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 --cc agent/tests/quantlib/test_credit.py
index f93a70d18,b99f29913..11a218ac4
--- a/agent/tests/quantlib/test_credit.py
+++ b/agent/tests/quantlib/test_credit.py
@@@ -20,17 -20,17 +20,20 @@@ from src.quantlib.credit import
ZONE_LABELS_ZH,
AltmanZScore,
altman_z_score,
+ cds_price,
credit_spread_analysis,
+ credit_spread_dv01,
distance_to_default,
edf_reference_band,
+ hazard_rate_to_survival_probability,
+ expected_loss,
kmv_default_point,
kmv_distance_to_default,
merton_asset_solve,
merton_model,
spread_term_structure,
+ survival_probability_to_hazard_rate,
+ vasicek_credit_var,
)
# One balance sheet, reused so the three variants can be compared like for like.
@@@ -502,67 -502,45 +505,109 @@@ def test_spread_term_structure_validate
# --------------------------------------------------------------------------
+# CDS Pricing & Hazard Rate Tests
+# --------------------------------------------------------------------------
+
+
+def test_hazard_rate_and_survival_prob_roundtrip():
+ lambda_val = 0.025
+ T = 5.0
+ q = hazard_rate_to_survival_probability(lambda_val, T)
+ assert 0.0 < q < 1.0
+ recovered_lambda = survival_probability_to_hazard_rate(q, T)
+ assert recovered_lambda == pytest.approx(lambda_val, rel=1e-12)
+
+
+def test_cds_price_fair_par_spread_zero_upfront():
+ # When the fixed running coupon equals the model par spread, upfront payment is identically 0.
+ spread = 150.0
+ res_par = cds_price(
+ spread_bps=spread,
+ coupon_bps=spread,
+ recovery_rate=0.40,
+ tenor_years=5.0,
+ risk_free_rate=0.03,
+ )
+ par_bps = res_par["par_spread_bps"]
+ result = cds_price(
+ spread_bps=spread,
+ coupon_bps=par_bps,
+ recovery_rate=0.40,
+ tenor_years=5.0,
+ risk_free_rate=0.03,
+ )
+ assert result["upfront_pct"] == pytest.approx(0.0, abs=1e-12)
+ assert result["upfront_amount"] == pytest.approx(0.0, abs=1e-6)
+ assert result["par_spread_bps"] == pytest.approx(spread, rel=0.05)
+ assert result["survival_probability"] == pytest.approx(np.exp(-result["hazard_rate"] * 5.0), rel=1e-12)
+ assert result["default_probability"] == pytest.approx(1.0 - result["survival_probability"], rel=1e-12)
+
+def test_cds_price_buyer_mtm_positive_when_spread_above_coupon():
+ # Quoted spread 250 bps > 100 bps running coupon -> protection buyer has positive MTM
+ result = cds_price(
+ spread_bps=250.0,
+ coupon_bps=100.0,
+ recovery_rate=0.40,
+ tenor_years=5.0,
+ notional=10_000_000.0,
+ )
+ assert result["upfront_amount"] > 0.0
+ assert result["buyer_mtm"] > 0.0
+ assert result["protection_leg_pv"] > result["premium_leg_pv"]
+
+
+def test_cds_price_input_validation():
+ with pytest.raises(ValueError, match="spread_bps must be non-negative"):
+ cds_price(spread_bps=-10.0)
+ with pytest.raises(ValueError, match="recovery_rate"):
+ cds_price(spread_bps=100.0, recovery_rate=1.0)
+ with pytest.raises(ValueError, match="tenor_years"):
+ cds_price(spread_bps=100.0, tenor_years=0.0)
+ with pytest.raises(ValueError, match="notional"):
+ cds_price(spread_bps=100.0, notional=-1000.0)
+ with pytest.raises(ValueError, match="hazard_rate"):
+ hazard_rate_to_survival_probability(-0.01, 5.0)
+ with pytest.raises(ValueError, match="survival_prob"):
+ survival_probability_to_hazard_rate(1.5, 5.0)
+ # 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)