Coverage for features/bond_features.py: 100%
178 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Shared, pure real-yield-curve/credit-spread/duration feature
2implementations - additive sibling to features/macro_features.py, using
3data_pipeline/fred_backfill.py's actual FRED Treasury-yield/credit-spread
4series rather than macro_features.py's bond-ETF-price-momentum proxies.
6Broadcast identically to EVERY asset's model input (not just bond-tagged
7assets) - same "compute once per date/bar, every asset sees it" shape as
8macro_features.py, and the concrete mechanism by which bond/yield-curve
9signal becomes usable for equity/crypto/future/option predictions too, not
10just bonds themselves.
12Imported by BOTH train.py (offline, per-date FRED-series lookup) and
13main.py (runtime, once per bar) for parity by construction - same
14convention as features/technical_indicators.py and features/macro_features.py.
16Every function neutral-defaults to 0.0 on missing input - never raises -
17except empirical_duration_beta(), which returns None (not 0.0) below its
18minimum-observation floor: an unknown duration sensitivity must never be
19indistinguishable from a genuinely-zero one, the same "None = absent, 0.0 =
20neutral" distinction risk/position_sizing.py::rank_sizing_multiplier()
21already draws for missing rank predictions.
23V4.6 (development/Problems.md, Roadmap "Assets" - "single-bond trading")
24added analytic_modified_duration()/analytic_convexity()/bond_dv01(), a
25real closed-form bond-math sibling to empirical_duration_beta() above -
26NOT a replacement for it. Individual-bond trading was confirmed
27INFEASIBLE under this Lean version's security model (no SecurityType.Bond,
28no AddBond, no Common/Securities/Bond/ implementation anywhere in the real
29Lean source tree - every "bond" Lean supports is an equity-typed ETF
30wrapper, exactly what this codebase already does) - these 3 functions
31instead deepen the EXISTING bond-ETF sleeve's analytics, using
32bond_metadata.duration_proxy_years (already configured per-ETF in
33config.json) as an assumed maturity and bond_metadata.assumed_coupon_rate
34(or, when absent, the treasury yield-curve point nearest that maturity, as
35an at-par-pricing proxy coupon) as an assumed coupon - explicitly an
36ETF-level APPROXIMATION, not real per-bond cash-flow data.
38V4.7 merged these 3 functions' output into base_features/BOND_FEATURE_NAMES
39as real model inputs (main.py::_build_model_input_impl(),
40train.py::build_bond_features_by_date()) - code-complete, but deploying it
41live requires running a retrain first: config.json's
42phase1.features.input_set now lists the 3 new names, and main.py's
43scaling loop indexes base_features[name] with no default, so an
44un-retrained ml/feature_schema.json (still listing only the original 34
45names) would KeyError on the very next bar. Until that retrain runs,
46main.py's own latest_bond_analytics_by_symbol side-table remains the only
47place these values are actually visible (dashboard/state), same as before.
48"""
50from __future__ import annotations
52from typing import TYPE_CHECKING, Any
54if TYPE_CHECKING:
55 import numpy as np
57YIELD_CURVE_LEVEL_NEUTRAL = 0.0
58YIELD_CURVE_SLOPE_NEUTRAL = 0.0
59YIELD_CURVE_CURVATURE_NEUTRAL = 0.0
60CREDIT_SPREAD_LEVEL_NEUTRAL = 0.0
62BOND_FEATURE_NAMES = [
63 "bond_yield_curve_level",
64 "bond_yield_curve_slope",
65 "bond_yield_curve_curvature",
66 "bond_credit_spread_level",
67 "bond_empirical_duration_beta",
68 "bond_analytic_modified_duration",
69 "bond_analytic_convexity",
70 "bond_dv01",
71]
74def yield_curve_level(treasury_10yr_yield: float | None) -> float:
75 """Raw level of the 10yr Treasury yield (e.g. 0.045 for 4.5%). Returns
76 YIELD_CURVE_LEVEL_NEUTRAL (0.0) when unavailable."""
77 if treasury_10yr_yield is None:
78 return YIELD_CURVE_LEVEL_NEUTRAL
79 return float(treasury_10yr_yield)
82def yield_curve_slope(treasury_10yr_yield: float | None, treasury_3mo_yield: float | None) -> float:
83 """10yr - 3mo - the standard recession-signal curve slope (negative =
84 inverted curve). Real-data replacement for
85 macro_features.yield_curve_slope_proxy()'s price-momentum proxy.
86 Returns YIELD_CURVE_SLOPE_NEUTRAL (0.0) when either input is missing."""
87 if treasury_10yr_yield is None or treasury_3mo_yield is None:
88 return YIELD_CURVE_SLOPE_NEUTRAL
89 return float(treasury_10yr_yield) - float(treasury_3mo_yield)
92def yield_curve_curvature(
93 treasury_2yr_yield: float | None,
94 treasury_5yr_yield: float | None,
95 treasury_10yr_yield: float | None,
96) -> float:
97 """2*5yr - 2yr - 10yr - the standard butterfly/curvature measure of
98 curve shape independent of its overall level or slope. Returns
99 YIELD_CURVE_CURVATURE_NEUTRAL (0.0) when any input is missing."""
100 if treasury_2yr_yield is None or treasury_5yr_yield is None or treasury_10yr_yield is None:
101 return YIELD_CURVE_CURVATURE_NEUTRAL
102 return 2.0 * float(treasury_5yr_yield) - float(treasury_2yr_yield) - float(treasury_10yr_yield)
105def credit_spread_level(baa10y_spread: float | None) -> float:
106 """Raw BAA10Y (Moody's Baa corporate bond yield relative to the 10yr
107 Treasury) level - widens when credit risk appetite deteriorates.
108 Real-data replacement for macro_features.credit_spread_proxy()'s
109 momentum-based proxy. Returns CREDIT_SPREAD_LEVEL_NEUTRAL (0.0) when
110 unavailable."""
111 if baa10y_spread is None:
112 return CREDIT_SPREAD_LEVEL_NEUTRAL
113 return float(baa10y_spread)
116_VECTOR_BETA_MIN_LENGTH = 48
119def _vector_duration_beta(etf_daily_returns, delta_10yr_yield_daily, min_observations: int):
120 """numpy version of the OLS slope below for long windows (V6.0.0, latency: 4 sensitivity betas x ~110 symbols x 2.5 ticks a
121 day cost ~50% of `_build_model_input`). Same pairing and the same `variance < 1e-12 -> None` guard; the sums are
122 float64 vector sums, so the value differs from the scalar one only at rounding level (pinned by a test). Returns
123 `_USE_SCALAR` when a value is a real NaN or not finite, so those inputs keep the scalar path's exact behaviour."""
124 import numpy as np
126 size = min(len(etf_daily_returns), len(delta_10yr_yield_daily))
127 ys = np.array(etf_daily_returns[:size], dtype=float) # None becomes nan
128 xs = np.array(delta_10yr_yield_daily[:size], dtype=float)
129 missing_y, missing_x = np.isnan(ys), np.isnan(xs)
130 if int(missing_y.sum()) != etf_daily_returns[:size].count(None) or int(missing_x.sum()) != delta_10yr_yield_daily[:size].count(None):
131 return _USE_SCALAR # a genuine NaN is in the data
132 valid = ~(missing_y | missing_x)
133 if int(valid.sum()) < min_observations:
134 return None
135 ys, xs = ys[valid], xs[valid]
136 if not (np.isfinite(ys).all() and np.isfinite(xs).all()):
137 return _USE_SCALAR
138 deviation_x = xs - xs.mean()
139 variance_x = float(np.dot(deviation_x, deviation_x))
140 if variance_x < 1e-12:
141 return None
142 return float(np.dot(deviation_x, ys - ys.mean())) / variance_x
145_USE_SCALAR = object()
148def duration_beta_from_arrays(ys: np.ndarray, xs: np.ndarray, min_observations: int) -> float | None:
149 """The OLS slope of `ys` on `xs` for float64 arrays in which NaN stands for a missing value (V6.0.0, latency path of the
150 per-tick sensitivity betas, where the series are built as arrays and never carry a genuine NaN). Positional pairing,
151 the minimum-observation floor and the `variance < 1e-12 -> None` guard are `empirical_duration_beta`'s; the value
152 differs from it only at rounding level."""
153 import numpy as np
155 size = min(len(ys), len(xs))
156 ys, xs = ys[:size], xs[:size]
157 valid = ~(np.isnan(ys) | np.isnan(xs))
158 if int(valid.sum()) < min_observations:
159 return None
160 ys, xs = ys[valid], xs[valid]
161 if not (np.isfinite(ys).all() and np.isfinite(xs).all()):
162 return None
163 deviation_x = xs - xs.mean()
164 variance_x = float(np.dot(deviation_x, deviation_x))
165 if variance_x < 1e-12:
166 return None
167 return float(np.dot(deviation_x, ys - ys.mean())) / variance_x
170def empirical_duration_beta(
171 etf_daily_returns: list[float | None],
172 delta_10yr_yield_daily: list[float | None],
173 min_observations: int = 60,
174) -> float | None:
175 """Rolling OLS slope of ETF daily returns regressed on same-day
176 Delta-10yr-yield: an empirical "how much does this ETF move per unit of
177 yield change" duration proxy, since these are ETFs with no single
178 stated maturity, not individual bonds with a textbook duration figure.
180 Pairs the two series positionally (index i of each list must already
181 correspond to the same trading date - callers are responsible for
182 alignment), drops any pair where either side is None, and requires at
183 least min_observations valid pairs. Returns None (not 0.0) below that
184 floor - a missing/insufficient-history duration estimate must be
185 distinguishable from "genuinely zero duration sensitivity"."""
186 if len(etf_daily_returns) >= _VECTOR_BETA_MIN_LENGTH:
187 vector = _vector_duration_beta(etf_daily_returns, delta_10yr_yield_daily, min_observations)
188 if vector is not _USE_SCALAR:
189 return vector
190 return _scalar_duration_beta(etf_daily_returns, delta_10yr_yield_daily, min_observations)
193def _scalar_duration_beta(etf_daily_returns, delta_10yr_yield_daily, min_observations: int) -> float | None:
194 paired = [
195 (x, y)
196 for x, y in zip(etf_daily_returns, delta_10yr_yield_daily, strict=False)
197 if x is not None and y is not None
198 ]
199 if len(paired) < min_observations:
200 return None
202 xs = [float(pair[1]) for pair in paired]
203 ys = [float(pair[0]) for pair in paired]
204 mean_x = sum(xs) / len(xs)
205 mean_y = sum(ys) / len(ys)
206 covariance = sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys, strict=False))
207 variance_x = sum((x - mean_x) ** 2 for x in xs)
208 # An exact `== 0.0` check is not robust here: for a mathematically
209 # constant xs, whether mean_x/variance_x round to exactly 0.0 depends on
210 # sum()'s internal summation algorithm, which CPython changed (naive
211 # left-to-right -> compensated) between 3.11 and 3.12 - the same input
212 # can produce a true 0.0 on one Python version and a tiny rounding-noise
213 # variance (~1e-20 scale, versus real delta-yield variance on the order
214 # of 1e-4 to 1e-8) on another, silently producing a wild
215 # covariance/near-zero-noise ratio instead of the intended None. See
216 # development/Problems.md#10.
217 if variance_x < 1e-12:
218 return None
219 return covariance / variance_x
222BOND_DURATION_BETA_LOOKBACK = 252
225def resolve_bond_duration_beta_mode(features_config: dict[str, Any] | None) -> tuple[str, int]:
226 """(`mode`, `lookback`) from `phase1.features.bond_duration_beta`. Absent = ("full_history", 252): train.py's single
227 whole-history slope and main.py's lock-in-once cache, the pre-V5.8.0 behaviour. "rolling" = a point-in-time trailing
228 slope on both sides (V5.8.0: the whole-history slope leaked validation/backtest data into every training row and was
229 constant per ticker, i.e. a ticker ID)."""
230 raw = (features_config or {}).get("bond_duration_beta") or {}
231 mode = str(raw.get("mode", "full_history"))
232 if mode not in {"full_history", "rolling"}:
233 mode = "full_history"
234 try:
235 lookback = max(2, int(raw.get("lookback", BOND_DURATION_BETA_LOOKBACK)))
236 except (TypeError, ValueError):
237 lookback = BOND_DURATION_BETA_LOOKBACK
238 return mode, lookback
241def _returns_and_yield_deltas(closes, treasury_levels) -> tuple[list[float | None], list[float | None]]:
242 returns: list[float | None] = [None]
243 deltas: list[float | None] = [None]
244 for index in range(1, len(closes)):
245 previous_close, close = closes[index - 1], closes[index]
246 returns.append((close / previous_close - 1.0) if previous_close and close is not None else None)
247 previous_level, level = treasury_levels[index - 1], treasury_levels[index]
248 deltas.append((level - previous_level) if level is not None and previous_level is not None else None)
249 return returns, deltas
252def rolling_duration_beta(
253 closes: list[float | None],
254 treasury_levels: list[float | None],
255 lookback: int = BOND_DURATION_BETA_LOOKBACK,
256 min_observations: int = 60,
257) -> float | None:
258 """Point-in-time duration beta at the LAST element: empirical_duration_beta() over the trailing `lookback` daily
259 returns (built from the last `lookback + 1` closes and 10-year yield levels, index-aligned per bar). main.py calls
260 this on its per-symbol windows; train.py's rolling_duration_beta_series() produces the same value for every row."""
261 length = min(len(closes), len(treasury_levels))
262 closes = list(closes)[len(closes) - length:][-(lookback + 1):]
263 treasury_levels = list(treasury_levels)[len(treasury_levels) - length:][-(lookback + 1):]
264 returns, deltas = _returns_and_yield_deltas(closes, treasury_levels)
265 return empirical_duration_beta(returns, deltas, min_observations=min_observations)
268def rolling_duration_beta_series(
269 closes: list[float | None],
270 treasury_levels: list[float | None],
271 lookback: int = BOND_DURATION_BETA_LOOKBACK,
272 min_observations: int = 60,
273) -> list[float | None]:
274 """rolling_duration_beta() evaluated at every position (row i sees elements <= i only), vectorised with pandas so
275 a 2,700-row bond history costs milliseconds. Pairs with either side missing are dropped exactly as the scalar
276 function drops them (both series masked together), and the same min-observation / degenerate-variance guards apply."""
277 import numpy as np
278 import pandas as pd
280 returns, deltas = _returns_and_yield_deltas(list(closes), list(treasury_levels))
281 x = pd.Series([np.nan if value is None else float(value) for value in deltas], dtype=float)
282 y = pd.Series([np.nan if value is None else float(value) for value in returns], dtype=float)
283 valid = x.notna() & y.notna()
284 x = x.where(valid)
285 y = y.where(valid)
286 window = x.rolling(lookback, min_periods=1)
287 count = valid.astype(float).rolling(lookback, min_periods=1).sum()
288 mean_x = window.mean()
289 mean_y = y.rolling(lookback, min_periods=1).mean()
290 sum_xy = (x * y).rolling(lookback, min_periods=1).sum()
291 sum_xx = (x * x).rolling(lookback, min_periods=1).sum()
292 covariance_sum = sum_xy - count * mean_x * mean_y
293 variance_sum = sum_xx - count * mean_x * mean_x
294 out: list[float | None] = []
295 for n, cov, var in zip(count.to_numpy(), covariance_sum.to_numpy(), variance_sum.to_numpy(), strict=False):
296 if not np.isfinite(n) or n < min_observations or not np.isfinite(var) or var < 1e-12:
297 out.append(None)
298 else:
299 out.append(float(cov / var))
300 return out
303def _bond_cash_flows(coupon_rate: float, years_to_maturity: float, payments_per_year: int, face_value: float = 100.0) -> list[float]:
304 """Coupon + principal cash-flow schedule for a plain-vanilla,
305 fixed-coupon bond priced at face_value=100 (a standard convention -
306 duration/convexity are scale-invariant per-unit-price ratios, so the
307 actual face value used doesn't affect the resulting figures). One
308 entry per period; the LAST entry additionally includes the face_value
309 repayment. Returns [] for a non-positive period count."""
310 num_periods = max(int(round(years_to_maturity * payments_per_year)), 0)
311 if num_periods == 0:
312 return []
313 coupon_per_period = coupon_rate / payments_per_year * face_value
314 cash_flows = [coupon_per_period] * num_periods
315 cash_flows[-1] += face_value
316 return cash_flows
319def analytic_modified_duration(
320 yield_to_maturity: float | None,
321 coupon_rate: float | None,
322 years_to_maturity: float | None,
323 payments_per_year: int = 2,
324) -> float | None:
325 """Standard closed-form modified duration from a plain-vanilla,
326 fixed-coupon cash-flow schedule: Macaulay duration (the price-weighted
327 average time to each cash flow, in years) divided by
328 (1 + yield_to_maturity/payments_per_year).
330 A genuinely DIFFERENT estimate from empirical_duration_beta() above,
331 not a replacement for it: empirical_duration_beta() measures how much
332 an ETF's OWN observed price actually moved per unit of yield change (a
333 market-realized sensitivity); this function computes what a
334 HYPOTHETICAL plain-vanilla bond with the given yield/coupon/maturity
335 would theoretically be sensitive to, from cash-flow math alone - see
336 this module's own docstring for the ETF-level-approximation caveat on
337 what yield_to_maturity/coupon_rate/years_to_maturity should be sourced
338 from in practice.
340 Returns None (never raises) when any input is missing, years_to_maturity
341 is non-positive, or the computed price is non-positive (a degenerate/
342 extreme-negative-yield edge case) - an unknown/undefined duration must
343 never be indistinguishable from a genuinely-zero one, the same
344 convention empirical_duration_beta() already established."""
345 if yield_to_maturity is None or coupon_rate is None or years_to_maturity is None or years_to_maturity <= 0:
346 return None
347 period_yield = float(yield_to_maturity) / payments_per_year
348 if period_yield <= -1.0:
349 return None
350 cash_flows = _bond_cash_flows(float(coupon_rate), float(years_to_maturity), payments_per_year)
351 if not cash_flows:
352 return None
354 discounted = [cf / (1.0 + period_yield) ** (t + 1) for t, cf in enumerate(cash_flows)]
355 price = sum(discounted)
356 if price <= 0.0:
357 return None
358 weighted_time = sum(((t + 1) / payments_per_year) * pv for t, pv in enumerate(discounted))
359 macaulay_duration = weighted_time / price
360 return macaulay_duration / (1.0 + period_yield)
363def analytic_convexity(
364 yield_to_maturity: float | None,
365 coupon_rate: float | None,
366 years_to_maturity: float | None,
367 payments_per_year: int = 2,
368) -> float | None:
369 """Standard closed-form convexity (the second derivative of bond price
370 with respect to yield, annualized) from the same plain-vanilla
371 cash-flow schedule analytic_modified_duration() uses - same
372 ETF-level-approximation caveat and degrade-to-None convention."""
373 if yield_to_maturity is None or coupon_rate is None or years_to_maturity is None or years_to_maturity <= 0:
374 return None
375 period_yield = float(yield_to_maturity) / payments_per_year
376 if period_yield <= -1.0:
377 return None
378 cash_flows = _bond_cash_flows(float(coupon_rate), float(years_to_maturity), payments_per_year)
379 if not cash_flows:
380 return None
382 discounted = [cf / (1.0 + period_yield) ** (t + 1) for t, cf in enumerate(cash_flows)]
383 price = sum(discounted)
384 if price <= 0.0:
385 return None
386 convexity_sum = sum(
387 (t + 1) * (t + 2) * pv / (1.0 + period_yield) ** 2 for t, pv in enumerate(discounted)
388 )
389 return convexity_sum / (price * payments_per_year ** 2)
392def bond_dv01(price: float | None, modified_duration: float | None, notional: float = 1.0) -> float | None:
393 """Dollar duration per 1bp yield move (DV01):
394 price * modified_duration * 0.0001 * notional - a directly useful
395 risk-sizing number (expected dollar P&L for a 1 basis point yield
396 change). Returns None (never raises) when price/modified_duration is
397 missing, or price/notional is non-positive."""
398 if price is None or modified_duration is None or price <= 0.0 or notional <= 0.0:
399 return None
400 return float(price) * float(modified_duration) * 0.0001 * float(notional)
403def nearest_yield_curve_point(years_to_maturity: float | None, curve_points: dict[str, Any]) -> float | None:
404 """Picks the yield-curve observation whose maturity (in years, the
405 dict's keys) is CLOSEST to years_to_maturity - the at-par-pricing
406 proxy coupon/yield fallback analytic_modified_duration()/
407 analytic_convexity() need when bond_metadata.assumed_coupon_rate isn't
408 explicitly configured for an ETF. A coarse approximation by
409 construction (this codebase's own Treasury curve only has 4 points -
410 3mo/2yr/5yr/10yr - so a long-duration ETF's true maturity is
411 necessarily approximated by the longest available point); callers
412 already document that limitation, this function just picks the
413 nearest one rather than guessing further. Skips any None-valued point
414 (a FRED series with no observation as-of the current date) - returns
415 None (never raises) when no curve point has a value at all, or
416 years_to_maturity is None."""
417 if years_to_maturity is None:
418 return None
419 usable_points = {maturity: yield_value for maturity, yield_value in curve_points.items() if yield_value is not None}
420 if not usable_points:
421 return None
422 nearest_maturity = min(usable_points, key=lambda maturity: abs(maturity - years_to_maturity))
423 return usable_points[nearest_maturity]