Coverage for evaluation/trend_sleeve_backtest.py: 100%
107 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"""Offline simulation of the trend sleeve (V6.4.4, rule R-TREND1).
3Daily closes from the shipped Lean zips; on every `rebalance_every_bars`-th session from `start + phase` the sleeve's
4target weights come from `portfolio.trend_sleeve.trend_sleeve_weights` on the closes up to and including that session
5(the same function main.py calls), filtered by `apply_min_change`, and are bought at that close as units (one-bar lag:
6the position earns from the next session on, as live). Units then drift with prices until the next rebalance. Each trade
7pays max(commission_bps x notional, min_commission_usd) plus `half_spread_bps`; the sleeve's own loss guard
8(`portfolio.sleeve_guard`, NAV fractions) closes it and blocks entries during a cooldown.
10Returns are fractions of the account NAV, which grows only by the sleeve's own P&L here (the sleeve's contribution).
11"""
13from __future__ import annotations
15import math
16from pathlib import Path
18import numpy as np
19import pandas as pd
21from portfolio.sleeve_guard import SleeveGuardConfig, evaluate_sleeve_guard
22from portfolio.trend_sleeve import TrendSleeveConfig, apply_min_change, trend_sleeve_weights
25def load_daily_closes(root: Path, config: dict, symbols, start: str | None = None, end: str | None = None) -> pd.DataFrame:
26 """date x symbol closes of the universe assets `symbols` from their config zips (rows where every symbol has a
27 close; the trend symbols share the US equity calendar)."""
28 from data_pipeline.data_audit import asset_zip_paths, read_lean_daily_zip
30 assets = {str(asset["ticker"]): asset for asset in config["phase1"]["universe"]["assets"]}
31 series = {}
32 for symbol in symbols:
33 asset = assets[symbol]
34 frame = read_lean_daily_zip(asset_zip_paths(asset, Path(root) / "data")["trade"], str(asset.get("security_type")))
35 series[symbol] = frame.set_index(frame["date"].dt.strftime("%Y-%m-%d"))["close"]
36 closes = pd.DataFrame(series).dropna().sort_index()
37 if start:
38 closes = closes[closes.index >= start]
39 if end:
40 closes = closes[closes.index <= end]
41 return closes
44def _trade_cost(notional: float, commission_bps: float, min_commission_usd: float, half_spread_bps: float) -> float:
45 if notional <= 0.0:
46 return 0.0
47 return max(notional * commission_bps / 1e4, min_commission_usd) + notional * half_spread_bps / 1e4
50def simulate_trend_sleeve(
51 closes: pd.DataFrame,
52 config: TrendSleeveConfig,
53 *,
54 start: str,
55 end: str,
56 phase: int = 0,
57 commission_bps: float = 1.5,
58 min_commission_usd: float = 1.0,
59 half_spread_bps: float = 2.0,
60 guard: SleeveGuardConfig | None = None,
61 nav: float = 100_000.0,
62 annualization: float = 252.0,
63) -> dict:
64 """One path of the sleeve over [start, end]. `closes` must hold history before `start` for the lookbacks."""
65 dates = list(closes.index)
66 columns = list(closes.columns)
67 values = closes.to_numpy(dtype=float)
68 first = next((i for i, date in enumerate(dates) if date >= start), len(dates))
69 last = max((i for i, date in enumerate(dates) if date <= end), default=-1)
70 units = dict.fromkeys(columns, 0.0)
71 weights_held: dict[str, float] = {}
72 equity = float(nav)
73 pnl_history: list[float] = []
74 suspended_until = None
75 daily, gross_series, weight_rows = {}, {}, {}
76 total_cost, traded = 0.0, 0.0
77 for i in range(first, last + 1):
78 date = dates[i]
79 prices = dict(zip(columns, values[i], strict=False))
80 if i > first:
81 previous = dict(zip(columns, values[i - 1], strict=False))
82 pnl = sum(units[s] * (prices[s] - previous[s]) for s in columns)
83 else:
84 pnl = 0.0
85 cost_today = 0.0
86 step = i - first - phase
87 guard_state = {"active": True}
88 if guard is not None:
89 pnl_history.append(pnl / nav)
90 guard_state = evaluate_sleeve_guard(pnl_history, 1.0, guard, current_bar=i, suspended_until_bar=suspended_until)
91 suspended_until = guard_state.get("suspended_until_bar")
92 target = None
93 if not guard_state["active"]:
94 target = {}
95 elif step >= 0 and step % config.rebalance_every_bars == 0:
96 history = {s: values[: i + 1, columns.index(s)].tolist() for s in config.symbols if s in columns}
97 target = apply_min_change(weights_held, trend_sleeve_weights(history, config, annualization=annualization),
98 config.min_weight_change)
99 equity_before = equity + pnl
100 if target is not None and target != weights_held:
101 for symbol in columns:
102 new_units = target.get(symbol, 0.0) * equity_before / prices[symbol]
103 if symbol in weights_held and symbol in target and target[symbol] == weights_held[symbol]:
104 new_units = units[symbol]
105 notional = abs(new_units - units[symbol]) * prices[symbol]
106 if notional > 0.0:
107 cost_today += _trade_cost(notional, commission_bps, min_commission_usd, half_spread_bps)
108 traded += notional
109 units[symbol] = new_units
110 weights_held = dict(target)
111 total_cost += cost_today
112 net = pnl - cost_today
113 daily[date] = net / equity
114 equity += net
115 gross_series[date] = sum(abs(units[s]) * prices[s] for s in columns) / equity if equity > 0 else 0.0
116 weight_rows[date] = {s: units[s] * prices[s] / equity for s in columns}
117 daily_series = pd.Series(daily, dtype=float)
118 years = max(len(daily_series) / annualization, 1e-9)
119 return {
120 "daily": daily_series,
121 "gross": pd.Series(gross_series, dtype=float),
122 "weights": pd.DataFrame.from_dict(weight_rows, orient="index"),
123 "turnover": traded / nav / years,
124 "costs": total_cost,
125 }
128def summarize_daily(daily: pd.Series, annualization: float = 252.0) -> dict:
129 """Annualised net Sharpe, total return and max drawdown (NAV fractions) of a daily return series."""
130 values = daily.to_numpy(dtype=float)
131 values = values[np.isfinite(values)]
132 if len(values) < 2:
133 return {"net_sharpe": 0.0, "total_return": 0.0, "max_drawdown": 0.0, "days": int(len(values))}
134 std = float(np.std(values, ddof=1))
135 sharpe = float(np.mean(values) / std * math.sqrt(annualization)) if std > 0 else 0.0
136 curve = np.cumprod(1.0 + values)
137 drawdown = float(np.max(1.0 - curve / np.maximum.accumulate(curve)))
138 return {"net_sharpe": sharpe, "total_return": float(curve[-1] - 1.0), "max_drawdown": drawdown, "days": int(len(values))}
141def trend_phase_summary(closes: pd.DataFrame, config: TrendSleeveConfig, *, start: str, end: str, phases: int = 10,
142 **kwargs) -> dict:
143 """The sleeve over `phases` evenly spaced rebalance phases: median / min / max of each summary figure, plus phase 0's
144 daily returns (the series combined with the main book)."""
145 every = config.rebalance_every_bars
146 count = max(1, min(phases, every))
147 phase_list = sorted({int(round(i * every / count)) % every for i in range(count)})
148 summaries, phase0 = [], None
149 for phase in phase_list:
150 result = simulate_trend_sleeve(closes, config, start=start, end=end, phase=phase, **kwargs)
151 summary = summarize_daily(result["daily"]) | {"turnover": result["turnover"], "costs": result["costs"]}
152 summaries.append(summary)
153 if phase0 is None:
154 phase0 = result["daily"]
155 out = {"phases": phase_list, "daily_phase0": phase0}
156 for key in ("net_sharpe", "total_return", "max_drawdown", "turnover", "costs"):
157 column = [summary[key] for summary in summaries]
158 out[f"median_{key}"] = float(np.median(column))
159 out[f"min_{key}"] = float(np.min(column))
160 out[f"max_{key}"] = float(np.max(column))
161 return out