Applicable Scenarios
When users raise the following types of questions, prioritize invoking this skill:
- Bond pricing, YTM calculation, duration/convexity analysis
- Corporate credit ratings, default probability estimation
- Credit spread analysis and trading strategies
- Credit assessment of local government financing vehicle bonds, ABS/MBS
- Interest rate risk management (DV01, key rate duration)
- Analysis of China's fixed income market structure
I. Credit Analysis Framework
1.1 Credit Rating System
Issuer Rating vs Issue Rating
| Type | Definition | Rating Object |
|---|---|---|
| Issuer Rating | The issuer's overall debt-servicing capacity | Enterprises, governments, financial institutions |
| Issue Rating | The credit quality of a specific bond | Specific bonds, taking into account collateral, seniority, and covenant terms |
The issue rating may be higher or lower than the issuer rating (depending on the guarantee structure).
Comparison of Standard & Poor's / Moody's / China Ratings
| S&P | Moody's | China Rating | Meaning |
|---|---|---|---|
| AAA | Aaa | AAA | Highest credit quality, extremely low default risk |
| AA+/AA/AA- | Aa1/Aa2/Aa3 | AA+/AA/AA- | High quality, extremely low default risk |
| A+/A/A- | A1/A2/A3 | A+/A/A- | Relatively high credit quality |
| BBB+/BBB/BBB- | Baa1/Baa2/Baa3 | BBB+/BBB/BBB- | Lower bound of investment grade (IG/HY dividing line) |
| BB+ and below | Ba1 and below | BB+ and below | High yield/speculative grade |
| D | D | D | Default |
China Characteristics: Domestic ratings are inflated; an AA rating domestically is roughly equivalent to BBB- internationally, and a comprehensive judgment should be made in combination with the rating outlook (positive/stable/negative).
1.2 Altman Z-Score Model
Used to predict corporate financial distress; the original model applies to listed manufacturing companies:
Z = 1.2×X1 + 1.4×X2 + 3.3×X3 + 0.6×X4 + 1.0×X5
| Variable | Calculation Formula | Meaning |
|---|---|---|
| X1 | Working Capital / Total Assets | Liquidity |
| X2 | Retained Earnings / Total Assets | Profit Accumulation |
| X3 | EBIT / Total Assets | Profitability |
| X4 | Market Value of Equity / Book Value of Total Liabilities | Financial Leverage |
| X5 | Sales Revenue / Total Assets | Asset Efficiency |
Interpretation Ranges:
- Z > 2.99: Safe Zone (low default risk)
- 1.81 < Z < 2.99: Grey Zone (requires in-depth analysis)
- Z < 1.81: Distress Zone (high default risk)
Improved Versions:
- Z' (private enterprises): X4 uses the book value of equity instead, with cutoffs of 2.90/1.23
- Z'' (non-manufacturing/emerging markets): remove X5, with cutoffs of 2.60/1.10
Limitations:
- Based on historical data, highly lagging
- Not applicable to financial enterprises (leverage is defined differently)
- Parameters need to be recalibrated for the Chinese market
1.3 Merton Structural Model
Treats the company's equity as a call option on the company's assets (strike price = face value of debt):
Core Assumptions:
- The company's asset value V follows a geometric Brownian motion:
dV = μV dt + σ_V V dW - The debt is a zero-coupon bond with face value D and maturity date T
- Default occurs only at time T (European-style default assumption)
Equity pricing (BS formula):
E = V·N(d1) - D·e^(-rT)·N(d2)
d1 = [ln(V/D) + (r + σ_V²/2)T] / (σ_V·√T)
d2 = d1 - σ_V·√T
Probability of default (risk-neutral):
PD = N(-d2)
Distance to Default (DD, Distance to Default):
DD = [ln(V/D) + (μ - σ_V²/2)T] / (σ_V·√T)
Credit spread estimation:
信用利差 ≈ -ln[N(d2) + (V/D·e^(rT))·N(-d1)] / T
Parameter estimation method(simultaneous equations):
- E = V·N(d1) - D·e^(-rT)·N(d2)
- σ_E·E = N(d1)·σ_V·V
1.4 KMV model (Expected Default Frequency EDF)
KMV is the commercial implementation of the Merton model, acquired by Moody's:
Steps:
- Infer asset value V and asset volatility σ_V from stock price and equity volatility
- Calculate the Default Point:
DP = 短期债务 + 0.5×长期债务 - Calculate the distance to default:
DD = (V - DP) / (V × σ_V) - Map DD to EDF through a historical default database (non-normal mapping)
Differences from Merton:
- The default trigger point is not all debt, but short-term + half of long-term
- The DD→EDF mapping is based on an empirical database, not a normal distribution assumption
- EDF is a real-world probability, not a risk-neutral probability
EDF reference ranges(approximately):
- EDF < 0.1%: investment grade
- 0.1%–1%: BBB-BB grade
- 1%–5%: B grade
- EDF > 5%: CCC and below
1.5 Credit scorecard methodology
Applicable to retail credit/ABS underlying asset analysis:
Modeling process:
- Data preparation: collect historical loan data and define default labels (e.g., 90+ days past due)
- Feature engineering: WOE (Weight of Evidence) encoding
- Feature selection: IV (Information Value) screening, keep IV > 0.02
- Model training: Logistic Regression (mainstream), XGBoost
- Score conversion:
Score = A - B×ln(odds), usually base score 600, PDO=20
WOE and IV calculation:
WOE_i = ln(好样本比例_i / 坏样本比例_i)
IV_i = (好样本比例_i - 坏样本比例_i) × WOE_i
总IV = Σ IV_i
IV reference standards:
- IV < 0.02: no predictive power
- 0.02–0.1: weak predictive power
- 0.1–0.3: moderate predictive power
- IV > 0.3: strong predictive power
II. Fixed-income product analysis
2.1 Treasury bonds and government bonds
Yield curve analysis
Spot rate curve (Zero Curve): the risk-free zero-coupon bond yields for each tenor, extracted from coupon-bearing bonds via the Bootstrap method.
Forward rate curve (Forward Curve):
f(T1, T2) = [(1+r2)^T2 / (1+r1)^T1]^(1/(T2-T1)) - 1
Term spread:
- 10Y-2Y: an indicator for predicting the economic cycle; a negative value usually signals recession
- 10Y-1Y: a measure of liquidity preference
- 30Y-10Y: judgment of supply and demand at the ultra-long end
Yield curve shapes:
| Shape | Characteristics | Economic meaning |
|---|---|---|
| Normal (Normal) | Long end > short end | Expectation of economic expansion |
| Flat (Flat) | All tenors are similar | Economic turning point |
| Inverted (Inverted) | Short end > long end | Recession signal |
| Humped (Humped) | The middle tenor is the highest | Liquidity stratification |
Characteristics of the Chinese government bond yield curve
- Benchmark curve: China Government Bonds (CGBs) + Policy Bank Bonds
- Key tenors: 1Y/3Y/5Y/7Y/10Y/30Y
- The 10Y government bond is the core benchmark rate
2.2 Corporate bond analysis
Core metrics
Coupon Rate: agreed at issuance, with interest calculated on par value.
Yield to Maturity YTM: The internal rate of return that makes the bond's present value = market price:
P = Σ [C/(1+y)^t] + F/(1+y)^n
Where C = coupon, F = par value, y = YTM, n = number of periods.
Current Yield:CY = 年票息 / 市场价格(ignoring principal gains/losses)
Modified Duration:
MD = -dP/P ÷ dy = Macaulay Duration / (1+y/m)
Meaning: for every 1% change in interest rates, the bond price changes by approximately MD% (inversely).
Convexity:
CX = [Σ t(t+1)·CF_t/(1+y)^(t+2)] / P
价格变化修正:ΔP/P ≈ -MD·Δy + 0.5·CX·(Δy)²
Bond pricing formula (implementation)
The pricing function is tested code in the repository; import it directly,do not rewrite it by hand in the session:
from src.quantlib.fixedincome import bond_price
bond_price(face=100, coupon_rate=0.05, ytm=0.04, n_periods=5, freq=1)
# -> 104.4518... 5年期、票息5%、YTM=4%、年付
Two conventions areexplicit parametershere, not implicit assumptions:
compounding:"discrete"(default,freqdiscrete compoundings per year, i.e. the form ofP = Σ C/(1+y/m)^tabove) or"continuous"。- Day count basis:
bond_pricediscounts by whole coupon periods, so what is returned is the price on thecoupon date(clean price, with accrued interest of 0). Settlement on a non-coupon date requires adding accrued interest to get the full price (dirty price):
import datetime as dt
from src.quantlib.fixedincome import accrued_interest
accrued = accrued_interest(
face=100, coupon_rate=0.05, freq=2,
last_coupon=dt.date(2024, 1, 15),
settlement=dt.date(2024, 4, 15),
next_coupon=dt.date(2024, 7, 15),
day_count="30/360", # ACT/365F(默认) | ACT/360 | ACT/ACT | 30/360 | 30E/360
) # -> 1.25
dirty_price = bond_price(100, 0.05, 0.04, 10, 2) + accrued
2.3 Convertible bonds (straight bond component)
For the conversion option component of convertible bonds, see
convertible-bondskill; this section focuses on straight bond value.
Bond Floor:
纯债价值 = Σ [票息/(1+r_straight)^t] + 面值/(1+r_straight)^n
Where r_straight is the yield of a straight bond with the same rating and same maturity.
Conversion premium rate and straight bond premium rate:
- Conversion premium rate = (convertible bond price - conversion value) / conversion value
- Straight bond premium rate = (convertible bond price - straight bond value) / straight bond value
Credit implications of downward revision clauses: A downward revision of the conversion price may lead to dilution, and the company's willingness must be assessed (strong redemption incentive vs. put pressure).
2.4 ABS/MBS analysis
Underlying asset analysis framework
Asset quality metrics:
- Weighted Average Coupon (WAC)
- Weighted Average Maturity (WAM)
- Weighted Average Loan-to-Value Ratio (LTV)
- Historical delinquency rate (DPD 30/60/90+)
- Cumulative Default Rate (CDR)
Prepayment rate models:
- CPR (Conditional Prepayment Rate): annualized prepayment rate
- SMM (Single Monthly Mortality): monthly prepayment rate
CPR = 1 - (1 - SMM)^12 SMM = 1 - (1 - CPR)^(1/12) - PSA model: standard prepayment assumption (PSA100 = increases linearly to 6%/year over the first 30 months, then remains constant at 6%/year)
Tranche structure analysis:
- Senior: first to be repaid, highest rating
- Mezzanine: subordinated repayment
- Equity/Junior: first to absorb losses, receives excess spread
Key risk indicators:
增信倍数 = (底层资产池规模 - 优先级规模) / 优先级规模
超额利差 = 底层资产池利率 - 优先级融资成本 - 服务费
2.5 Credit analysis of urban investment bonds
Urban investment bonds (LGFV, local government financing vehicle bonds) are a variety unique to China's fixed income market.
Analysis framework
Four-Dimensional Evaluation Model:
| Dimension | Core Indicators | Weight |
|---|---|---|
| Regional Fiscal Strength | General public budget revenue, GDP scale, fiscal self-sufficiency rate | 40% |
| Platform Tier | Provincial > Municipal > District/County level; the higher the tier, the stronger the implicit support | 25% |
| Platform Status | Whether it is the sole urban investment platform, asset injection strength, business diversification | 20% |
| Debt Structure | Scale of interest-bearing debt, proportion of short-term debt, refinancing pressure | 15% |
Implicit Debt Risk Signals:
- Urban investment monetary funds/short-term debt < 0.5 (liquidity tightness)
- EBITDA interest coverage ratio < 1 (reliance on external financing to pay interest)
- Non-standard financing proportion > 30% (high refinancing risk)
- District/county-level urban investment platforms, weak regions (debt ratio > 100%)
Urban Investment Valuation Premium Structure(Reference):
城投利率 ≈ 同期国债 + 流动性溢价(30-50bp) + 区域溢价(0-200bp) + 平台溢价(0-100bp)
Policy Risk: Divergence has intensified since the 2023 urban investment debt resolution policy. Watch:
- Progress of the package of debt resolution measures
- Platform transformation (urban investment platform to enterprise)
- Regional list management policy
III. Interest Rate Risk Management
3.1 Duration System
Macaulay Duration
Sum of time-weighted present values of cash flows, in "years":
D_mac = Σ [t × CF_t/(1+y)^t] / P
Modified Duration
Measure of interest rate sensitivity:
D_mod = D_mac / (1 + y/m)
ΔP ≈ -D_mod × P × Δy
Effective Duration
Applicable to bonds with embedded options (callable bonds, MBS, etc.):
D_eff = (P_down - P_up) / (2 × P_0 × Δy)
Where P_down/P_up is the price after a downward/upward shift of Δy in interest rates.
Dollar Duration
Dollar Duration = D_mod × P × 面值
3.2 Convexity
Measures the sensitivity of duration to interest rates (second-order effect):
C = Σ [t(t+1) × CF_t/(1+y)^(t+2)] / P
价格精确估算:
ΔP/P ≈ -D_mod·Δy + 0.5·C·(Δy)²
The Value of Convexity: Positive convexity makes a bond rise more than expected when interest rates fall (and fall less than expected when interest rates rise), so bonds with positive convexity are more favored than bonds with negative convexity (such as callable bonds and MBS).
3.3 DV01 (Basis Point Value)
Price change caused by a 1 basis point (0.01%) change in interest rates:
DV01 = D_mod × P × 0.0001
At the portfolio level:Portfolio DV01 = Σ (DV01_i × 持仓量_i)
Use: Interest rate hedge ratio calculation
对冲比率 = DV01_被对冲头寸 / DV01_对冲工具
3.4 Key Rate Duration (KRD)
Measures the impact on price of a 1bp parallel shift at each key maturity point of the yield curve:
- Common key points: 1Y, 2Y, 3Y, 5Y, 7Y, 10Y, 20Y, 30Y
KRD_i = -ΔP/(P × Δy_i)(only the i-th key rate changes by 1bp)Σ KRD_i ≈ D_mod(the sum of key rate durations is approximately equal to modified duration)
Application:
- Identify the portfolio's exposure to interest rates at specific maturities
- Precisely hedge non-parallel shift risk (twist/butterfly)
3.5 Immunization Strategies
Duration Matching:
Make the asset portfolio duration = liability duration, immunizing against parallel shifts in interest rates.
Conditions:Σ (w_i × D_i) = D_liability
Cash Flow Matching: Directly match cash flows in each period, completely eliminating reinvestment risk, but with poor flexibility and high cost.
Contingent Immunization: Actively manage when the portfolio value exceeds the safety floor, and switch to passive immunization when it falls to the floor.
Rebalancing Frequency:
- Duration drifts over time and requires regular (quarterly/monthly) rebalancing
- Rebalance immediately after significant interest rate changes (>50bp)
IV. Credit Spread Analysis
4.1 Composition of Credit Spreads
信用利差(Credit Spread)= 违约风险溢价 + 流动性溢价 + 税收溢价(部分市场)
| Component | Influencing Factors | Quantification Method |
|---|---|---|
| Default Risk Premium | Rating, industry, financial condition, macroeconomic cycle | CDS quotes, model estimation |
| Liquidity Premium | Issue size, remaining maturity, market depth | Bid-ask spread, turnover rate |
| Tax Premium | Government bond tax exemption (some countries/investors) | Interest rate differential analysis |
Spread Measurement Benchmarks:
- International markets: G-Spread (vs government bonds), I-Spread (vs swaps), Z-Spread (zero-volatility spread), OAS (option-adjusted spread)
- Chinese market: credit spreads are usually compared with government bonds or AAA local government financing vehicles
OAS(Option-Adjusted Spread): Credit spread after stripping out the value of embedded options, suitable for comparison of bonds with embedded options:
P = Σ CF_t / (1 + r_t + OAS)^t
4.2 Credit Spread Curve Shape
Positive Slope(common): long-term spread > short-term spread, reflecting compounded maturity uncertainty.
Flat/Inverted:
- Market is optimistic about long-term credit risk (flat)
- Short-term liquidity crisis/refinancing difficulties (inverted), a warning signal
Correlation between credit spreads and government bond yields:
- Economic expansion: credit spreads tighten (rising risk appetite)
- Economic recession/credit events: credit spreads widen
- "Flight to quality" effect: government bond yields fall + credit spreads widen, a double blow to high-yield bonds
4.3 Drivers of Credit Spread Changes
Macro Factors:
- GDP growth, PMI: expectations improve → spreads tighten
- Monetary policy easing: liquidity premium declines
- Credit events (default wave): systemic spread widening
Industry Factors:
- Industry policies (e.g., real estate regulation, local government financing vehicle debt resolution)
- Industry prosperity cycle
- Refinancing environment
Individual Bond Factors:
- Rating adjustments (downgrade → spread jump)
- Changes in financial data
- Maturity pressure (approaching maturity → increased liquidity spread)
4.4 Credit Spread Trading Strategies
Spread Tightening Trade: Go long undervalued (high-spread) credit bonds, short government bonds to hedge interest rate risk.
- Applicable scenarios: early economic recovery, central bank easing cycle
Spread Widening Trade: Short credit bonds (via CDS), long government bonds.
- Applicable scenarios: economic downturn, frequent credit events
Cross-Rating Spread Trade: Go long high yield/short investment grade (when spreads tighten), or the opposite.
Butterfly Spread Trade: Go long the intermediate segment, short the short end and long end, to profit from relative value in the middle section of the credit curve.
China-Specific Instruments:
- Credit risk mitigation instruments (CRMW/CDS): hedge credit risk
- Government bond futures: hedge interest rate duration risk
V. Python Implementation (quantlib)
The models in this chapterare already tested code in the repository, located in src/quantlib/fixedincome.py(bond math + curve fitting)
and src/quantlib/credit.py(Altman Z / Merton-KMV / spread). Both modules have corresponding
tests/quantlib/test_fixedincome.py、tests/quantlib/test_credit.py, and duration and DV01 were verified point by point against
"repricing ±1bp".
Call them directly via import; do not rewrite these formulas in the session. Hand-writing them gives you neither test guarantees nor reproducibility.
Uniform unit conventions: rates and ratios are decimals (0.05 means 5%), tenors and time spans are inyears, and the return values of
duration/convexity are inyears / years²(not the number of coupon periods); only those with the _bp suffix are basis points.
5.1 Bond Pricing, Duration and DV01
from src.quantlib.fixedincome import (
bond_price, ytm_solve, macaulay_duration, modified_duration,
convexity, dv01, effective_duration,
)
face, coupon, ytm, n, freq = 100, 0.05, 0.04, 5, 1
price = bond_price(face, coupon, ytm, n, freq) # 104.4518
ytm_solve(price, face, coupon, n, freq) # 0.04(价格反解 YTM)
macaulay_duration(face, coupon, ytm, n, freq) # 4.5571 年
modified_duration(face, coupon, ytm, n, freq) # 4.3818 年
convexity(face, coupon, ytm, n, freq) # 24.4766 年²
dv01(face, coupon, ytm, n, freq, par_amount=1_000_000) # 457.69 元/bp
Key Parameters
| Parameter | Description |
|---|---|
freq |
Number of coupon payments per year,1=annual payments,2=semiannual payments. All functions accept it; never hard-code |
compounding |
"discrete"(default) or "continuous". Under continuous compounding, modified duration is always equal to Macaulay duration |
par_amount |
dv01 position face amount, default 1 million; the market value for hedging is calculated as par_amount * price / face position face amount, default 1 million; the market value for hedging is calculated as par_amount * price / face |
bracket |
ytm_solve root-finding interval, default (-0.5, 10.0), covering all tradable bonds |
The cash flows of bonds with embedded options (callable bonds, MBS) move with interest rates, so analytical duration does not apply; use the repricing method instead:
d_eff = effective_duration(reprice=lambda y: my_oas_model(y), yield_level=0.04, bump=1e-4)
reprice must include its own call/prepayment logic;effective_duration is only responsible for (P_down - P_up) / (2·P₀·Δy)。
5.2 Yield Curve Fitting (Nelson-Siegel / Svensson)
import numpy as np
from src.quantlib.fixedincome import fit_yield_curve, nelson_siegel, svensson
maturities = np.array([0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30])
yields = np.array([0.019, 0.020, 0.022, 0.024, 0.025, 0.027, 0.028, 0.029, 0.033, 0.035])
fit = fit_yield_curve(maturities, yields, model="svensson")
fit.params # (beta0, beta1, beta2, beta3, lambda1, lambda2)
fit.rmse # 拟合残差(小数,与输入同单位)
fit(4.5) # 任意期限插值 -> 该点即期利率
fit([1, 5, 10]) # 也接受数组
fit_yield_curve returns a CurveFit object(not a (params, func) tuple): it is itself callable,
and also has the three read-only fields model / params / rmse .model takes "nelson_siegel"(4 parameters)
or "svensson"(6 parameters, double curvature factor).
The fitting method isseparable least squares: given the decay parameter λ, the βs are linear, so they are solved exactly with OLS, and only a grid + Nelder-Mead search is done over 1–2 λs. This matters a lot—performing single-start L-BFGS-B over all parameters together (what this skill's earlier template did)cannot even recover the curve it generated itself: on a noise-free Nelson-Siegel curve with 10 tenors it stalls at RMSE 6.4e-4 (6.4bp), whereas the current implementation is 4.0e-14.
When you need to evaluate directly by parameter (for example, for factor decomposition or scenario simulation), use the low-level functions:
nelson_siegel(tau=[1, 5, 10], beta0=0.045, beta1=-0.02, beta2=0.03, lambda1=2.5)
svensson(tau=5.0, beta0=0.05, beta1=-0.03, beta2=0.04, beta3=-0.02,
lambda1=1.2, lambda2=8.0)
beta0 is the level factor (long-end asymptotic rate),beta0 + beta1 is the instantaneous short rate,
beta2 / beta3 is the curvature factor,lambda* is the decay speed (years). Pass a scalar to get a scalar; pass an array to get an array.
5.3 Altman Z-Score Calculation
from src.quantlib.credit import altman_z_score
z = altman_z_score(
working_capital=200, # X1 分子:流动资产 - 流动负债
retained_earnings=300, # X2 分子:留存收益
ebit=150, # X3 分子:息税前利润
equity_value=900, # X4 分子:original 用股权市值,prime/double_prime 用账面净资产
total_liabilities=600, # X4 分母:全部负债的账面值
total_assets=1000, # X1/X2/X3/X5 的分母
revenue=1200, # X5 分子;double_prime 不需要,可省略
model="original", # original | prime | double_prime
)
z.z_score # 3.255
z.zone # "safe" | "grey" | "distress"
z.label_zh # "安全区(低违约风险)"
z.components # {"x1": 0.20, "x2": 0.30, "x3": 0.15, "x4": 1.50, "x5": 1.20}
z.safe_threshold # 2.99
z.distress_threshold # 1.81
The coefficients and cutoff values of the three variants are in ALTMAN_MODELS , corresponding one-to-one with the table in §1.2:
model |
Applicable to | Coefficients (X1..X5) | Safe / Distress |
|---|---|---|---|
original |
Listed manufacturers (Altman 1968) | 1.2 / 1.4 / 3.3 / 0.6 / 1.0 | > 2.99 / < 1.81 |
prime(Z') |
Private enterprises, X4 uses book net assets instead | 0.717 / 0.847 / 3.107 / 0.420 / 0.998 | > 2.90 / < 1.23 |
double_prime(Z'') |
Non-manufacturing / emerging markets, X5 removed | 6.56 / 3.26 / 6.72 / 1.05 / — | > 2.60 / < 1.10 |
The denominator of X4 is "total liabilities", not "interest-bearing liabilities". The variable table in §1.2 says "total liability book value", the parameter name
total_liabilitiesis consistent with the model definition. Substituting interest-bearing liabilities will systematically overestimate the Z value.
The same statement can give different zones under the three variants (in the above example:original safe zone,prime grey zone),
this is exactly the point of recalibration, not a contradiction.
5.4 Credit spread analysis
from src.quantlib.credit import credit_spread_analysis, spread_term_structure
df = credit_spread_analysis(
bond_yields=bond_ytm_series, # pd.Series,索引=日期
risk_free_yields=cgb_ytm_series, # 必须与上面同一个索引
window=252, # 滚动窗口(交易日)
lookback_periods=21, # 慢速变化列的回溯期
signal_z=1.5, # 触发 rich/cheap 的 |z| 阈值
input_unit="percent", # percent | decimal | bp
)
The returned DataFrame columns are fixed as:spread_bp、rolling_mean_bp、rolling_std_bp、z_score、
historical_percentile、change_1p_bp、change_lookback_bp、signal。
signal takes "rich"(spread low, expensive) / "neutral" / "cheap"(spread high, cheap).
historical_percentileis a full-sample ranking, carries look-ahead bias, and cannot be used as a backtest signal. It sorts each row together with the rowsafterit—the percentile for the same day will change as new data arrives (measured: the same row is 0.02 on a 50-row slice and becomes 0.01 on 100 rows). This is the behavior of the original template, kept so as not to silently change the convention.z_scoreandsignaluse rolling windows and are causal; use these two for signals.
grid = spread_term_structure(
issuers={"AAA城投": {1: 0.025, 3: 0.028, 5: 0.032},
"AA城投": {1: 0.032, 3: 0.041, 5: 0.055}},
risk_free_curve={1: 0.020, 3: 0.022, 5: 0.025},
input_unit="decimal", # 注意默认值与上面那个函数不同
decimals=1,
)
# 行=发行人,列=1Y_spread_bp / 3Y_spread_bp / 5Y_spread_bp
You must confirm the input unit yourself. The historical defaults of the two functions are inconsistent:
credit_spread_analysisthe default yield ispercentage(3.2means 3.2%),spread_term_structurethe default isdecimal(0.032). The defaults preserve the behavior of the original template, butinput_unitis now an explicit parameter—before feeding data, first see clearly which kind of series you have; getting it backwards means a 100-fold spread error.
5.5 Merton structural model and KMV
from src.quantlib.credit import (
merton_model, merton_asset_solve, distance_to_default,
kmv_default_point, kmv_distance_to_default, edf_reference_band,
)
m = merton_model(
equity_value=100, # 股权市值
equity_vol=0.40, # 股权年化波动率
debt_face=100, # 债务面值(简化为单笔零息债)
risk_free=0.03, # 连续复利无风险利率
horizon=1.0, # 债务到期年限
asset_drift=None, # 距违约距离用的资产漂移;None = 用 risk_free(风险中性口径)
)
m.asset_value # 197.04 反推出的资产价值
m.asset_vol # 0.2030 反推出的资产波动率
m.distance_to_default # 3.3868 asset_drift=None 时等于 d2
m.default_probability # 0.000354 风险中性违约概率 N(-d2)
m.credit_spread_bp # 0.176 bp
The simultaneous equations (the two equations in §1.3) are solved in merton_asset_solve , and are solved inlog space,
so the roots will not run to negative assets or negative volatility; non-convergence throws ValueErrordirectly, and will not silently return a garbage solution.
The DD of Merton and KMV are two different quantities; do not mix them:
# Merton:对数空间、带漂移与期限
distance_to_default(asset_value=200, asset_vol=0.25, default_point=100,
horizon=2.0, drift=0.06)
# KMV:线性缺口,无期限无漂移,违约点只含短债 + 部分长债
dp = kmv_default_point(short_term_debt=100, long_term_debt=200,
long_term_weight=0.5) # -> 200
kmv_distance_to_default(asset_value=1000, asset_vol=0.25, default_point=dp) # -> 3.2
edf_reference_band(3.2) # -> (0.001, 0.01),即 §8 表里的 0.1%–1% 档
edf_reference_bandjust turns the "DD → EDF" empirical table in §8 into a lookup function. The real KMV EDF comes from Moody's proprietary default database; the output here can only serve as amagnitude check, and must never be reported as a calibrated default probability.
Risk-neutral vs real-world:asset_drift only affects distance_to_default, and does not affect d2、
default_probability and credit_spread—the latter three are by definition risk-neutral. To see the real-world convention,
pass in an expected asset return, then use edf_reference_band to read the file; do not report N(-dd) as EDF.
Six, Characteristics of China's fixed income market
6.1 Market structure
Interbank market vs exchange market
| Dimension | Interbank market (CFETS) | Exchange market (SSE/SZSE) |
|---|---|---|
| Regulator | People's Bank of China | CSRC |
| Main participants | Banks, insurers, funds, foreign institutions | Brokerages, funds, individual investors |
| Trading method | Quote-driven (OTC) + anonymous click | Centralized matching + block trading |
| Main instrument types | Treasury bonds, policy financial bonds, credit bonds, ABS | Enterprise bonds, corporate bonds, convertible bonds |
| Scale proportion | ~90% (by trading volume) | ~10% |
| Settlement method | T+0/T+1(DVP) | T+1 |
| Liquidity | High (government bonds/policy financial bonds) | High (convertible bonds)/Low (pure bonds) |
Main bond types
| Type | Issuer | Regulation/Registration | Credit risk |
|---|---|---|---|
| Government bonds (CGBs) | Ministry of Finance | No restrictions | None (sovereign credit) |
| Local government bonds | Provincial and municipal governments | Ministry of Finance approval | Extremely low |
| Policy bank bonds (CDB/ADBC/Export-Import Bank) | Policy banks | No restrictions | Extremely low (quasi-sovereign) |
| Negotiable certificates of deposit (NCD) | Banks | Central bank | Low (bank credit) |
| Super & short-term commercial paper (SCP) / commercial paper (CP) / medium-term notes (MTN) | Non-financial enterprises | National Association of Financial Market Institutional Investors (NAFMII) | Medium |
| Enterprise bonds | Enterprises | NDRC | Medium-high |
| Corporate bonds | Listed companies | CSRC | Medium-high |
| Urban investment bonds | Local government financing vehicles | Diverse | Medium-high (implicit government backing) |
| ABS/ABN | SPV | NAFMII/CSRC | Depends on underlying assets |
6.2 Key points for in-depth analysis of urban investment bonds
Primary market analysis(issuance pricing):
- Verify the issuer's tier and region (provincial/municipal/district-county)
- Review the proportion of core business (ratio of infrastructure business vs commercialized business)
- Assess the region's general public budget revenue and government debt ratio
- Analyze the authenticity of urban investment transferred assets over the past 3 years (abnormal current account transactions)
Secondary market analysis(position valuation):
- Track spread changes (vs same rating and same tenor)
- Pay attention to public opinion events (technical default/commercial paper overdue/rating downgrade)
- Monitor refinancing pace (maturity pressure vs new issuance pace)
- Pay attention to regional policies (debt resolution list, debt swap progress)
Risk warning signals (red lines):
- Monetary funds/short-term debt < 0.3
- Non-standard financing/interest-bearing liabilities > 40%
- Commercial paper overdue included in the system (dishonest bill list)
- Overall refinancing in the region's urban investment sector is obstructed
- Management personnel changes combined with negative regional rating outlook
6.3 Credit analysis of wealth management/asset management products
Look-through analysis of underlying assets after the net value transformation:
- Mixed wealth management: need to separately assess the equity side (market value fluctuations) and the fixed-income side (credit risk)
- Fixed income + strategy: principal 80%+ bonds, within 20% equity/convertible bonds
- FOF wealth management: two-layer nested look-through, need to assess underlying fund holdings
Liquidity analysis framework:
产品层面流动性 = f(底层资产流动性, 赎回条款, 摊余成本法 vs 市值法)
- Amortized cost method: stable prices but hidden risks (not applicable to net-value products)
- Mark-to-market method: reflects true value, but volatility exposure may trigger a wave of redemptions
Underlying credit assessment steps:
- Obtain detailed bond holdings (disclosed in quarterly/semi-annual reports)
- Classify by rating/industry/LGFV/non-LGFV
- Calculate weighted credit spread
- Identify concentration risk (single bond > 5% is high concentration)
- Assess liquidity gradient (high liquidity → low liquidity coverage)
6.4 Default Case Analysis Methodology
Default type:
| Type | Characteristics | Typical cases in China |
|---|---|---|
| Liquidity default | Assets healthy but cash flow ruptured | Some small and medium-sized real estate developers |
| Technical default | Trigger clauses (cross-default/acceleration) | Mostly seen in weakly qualified entities |
| Operational default | Deterioration of core business leads to declining repayment capacity | Yongcheng Coal, Huachen (2020) |
| Fraudulent default | Financial fraud/asset tunneling | Kangmei Pharmaceutical, Lanshengbo |
Precursor Signals of Default:
财务层面:
- 应收账款/总资产 异常增高(虚增收入)
- 货币资金余额高但受限比例高
- 商誉/无形资产占比持续增大
- 关联方交易占比异常
市场层面:
- 二级市场价格持续下跌(跌破90)
- 信用利差快速走阔(单周>50bp)
- 主承销商更换或不参与后续发行
- CDS报价(如有)快速上升
评级层面:
- 评级列入负面观察
- 多家评级机构下调
- 展望由稳定下调至负面
Post-Default Analysis:
- Reconstruct the default trigger timing and cash flow direction
- Balance sheet "authenticity" assessment (distinguish real assets vs. book assets)
- Sort out creditor priority (guarantee order, collateral)
- Estimate expected recovery rate in disposal (Recovery Rate)
- Systemic risk contagion paths (cross-holdings, similar entities)
Recovery rate reference for the Chinese market:
- LGFV bonds (resolved after technical default): close to 100%
- Real estate developer defaults: about 20%-50% (depending on land reserve quality)
- Industrial enterprise defaults: about 30%-60%
- Financial institutions (non-bank): about 40%-70% (degree of regulatory intervention)
VII. Relationship with Other Skills
| Related Skill | Complementary relationship |
|---|---|
convertible-bond |
The equity conversion option portion of convertible bonds is handled by the convertible-bond skill; this skill is responsible for pure bond pricing and credit risk |
macro-analysis |
The macro interest rate environment and credit cycle judgment are provided as inputs by the macro skill |
risk-management |
Portfolio-level credit risk (VaR/CVaR) refers to the risk-management skill |
equity-fundamental |
Credit analysis and equity valuation share the financial statement analysis framework; Altman Z-Score applies to both sides |
VIII. Quick Reference
Common formula quick reference
YTM 近似公式:
YTM ≈ [C + (F-P)/n] / [(F+P)/2]
久期与价格变化:
ΔP ≈ -D_mod × P × Δy + 0.5 × CX × P × (Δy)²
DV01 = D_mod × P × 0.0001 × 持仓面值
信用利差 = 债券YTM - 同期限国债YTM
Z-Score 风险信号:
Z > 2.99 → 安全 1.81 < Z < 2.99 → 灰色 Z < 1.81 → 危险
违约距离 DD → EDF:
DD > 4: EDF < 0.1%
DD 2-4: EDF 0.1%-1%
DD 1-2: EDF 1%-5%
DD < 1: EDF > 5%
China fixed income data sources
| Data type | Recommended source |
|---|---|
| Government bond yield curve | China Central Depository & Clearing Co. (CCDC), Ministry of Finance official website |
| Credit bond market quotes | Wind, DM data |
| LGFV financial data | Annual reports of bond issuers, Wind |
| Rating reports | China Chengxin, Lianhe Ratings, Orient Jin Cheng official websites |
| Default data | Wind, China Bond Information Network (chinamoney.com.cn) |
| ABS data | CNABS (China National Asset-Backed Securities Analytics) |