audit_eth_robust_twap_accounting.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. from __future__ import annotations
  2. import sys
  3. from dataclasses import dataclass
  4. from pathlib import Path
  5. import pandas as pd
  6. ROOT = Path(__file__).resolve().parents[1]
  7. sys.path.insert(0, str(ROOT))
  8. from okx_codex_trader.models import Candle
  9. from okx_codex_trader.sampled_report import SegmentResult, mark_to_market, trade_equity
  10. from scripts import explore_ultrashort as explore
  11. SYMBOL = "ETH-USDT-SWAP"
  12. BAR = "15m"
  13. YEARS = 10.0
  14. LEVERAGE = 3
  15. INITIAL_EQUITY = explore.INITIAL_EQUITY
  16. OUTPUT_DIR = Path("reports/eth-exploration")
  17. PREFIX = "eth-robust-twap-accounting-audit"
  18. COSTS = {
  19. "maker_taker": 0.0021,
  20. "taker_taker": 0.0030,
  21. }
  22. HORIZONS = (
  23. ("full", None),
  24. ("3y", pd.DateOffset(years=3)),
  25. ("1y", pd.DateOffset(years=1)),
  26. ("6m", pd.DateOffset(months=6)),
  27. ("3m", pd.DateOffset(months=3)),
  28. ("30d", pd.DateOffset(days=30)),
  29. ("21d", pd.DateOffset(days=21)),
  30. )
  31. @dataclass(frozen=True)
  32. class Spec:
  33. trend_sma: int
  34. rsi_length: int
  35. rsi_threshold: float
  36. exit_rsi: float
  37. stop_loss_pct: float
  38. max_hold_bars: int
  39. entry_offsets: tuple[float, ...]
  40. entry_valid_bars: int
  41. fill_buffer: float = 0.0
  42. @property
  43. def name(self) -> str:
  44. offsets = "-".join(f"{offset:.4f}" for offset in self.entry_offsets)
  45. buffer_label = f"-fb{self.fill_buffer:.4f}" if self.fill_buffer else ""
  46. return (
  47. f"rsi2-long-guarded-price-twap-o{offsets}-v{self.entry_valid_bars}{buffer_label}"
  48. f"-t{self.trend_sma}-r{self.rsi_length}-l{self.rsi_threshold}"
  49. f"-x{self.exit_rsi}-sl{self.stop_loss_pct}-mh{self.max_hold_bars}"
  50. )
  51. BASE_SPEC = Spec(
  52. trend_sma=60,
  53. rsi_length=2,
  54. rsi_threshold=3.0,
  55. exit_rsi=50.0,
  56. stop_loss_pct=0.012,
  57. max_hold_bars=48,
  58. entry_offsets=(0.003, 0.006, 0.009),
  59. entry_valid_bars=4,
  60. )
  61. def fmt_ts(ts: int) -> str:
  62. return pd.to_datetime(ts, unit="ms", utc=True).strftime("%Y-%m-%d %H:%M")
  63. def pct(value: float) -> str:
  64. return f"{value * 100:.2f}%"
  65. def load_candles() -> list[Candle]:
  66. cached, _ = explore.load_cached_candles(explore.CANDLE_CACHE_DIR, SYMBOL, BAR)
  67. requested = explore.history_bars_for_years(BAR, YEARS)
  68. return cached[-requested:] if len(cached) > requested else cached
  69. def compute_rsi(closes: pd.Series, length: int) -> list[float]:
  70. deltas = closes.diff()
  71. gains = deltas.clip(lower=0.0)
  72. losses = -deltas.clip(upper=0.0)
  73. rsi = [float("nan")] * len(closes)
  74. if len(closes) <= length:
  75. return rsi
  76. average_gain = float(gains.iloc[1 : length + 1].mean())
  77. average_loss = float(losses.iloc[1 : length + 1].mean())
  78. for index in range(length, len(closes)):
  79. if index > length:
  80. average_gain = ((average_gain * (length - 1)) + float(gains.iloc[index])) / length
  81. average_loss = ((average_loss * (length - 1)) + float(losses.iloc[index])) / length
  82. if average_loss == 0.0:
  83. rsi[index] = 100.0 if average_gain > 0.0 else 50.0
  84. else:
  85. rsi[index] = 100.0 - (100.0 / (1.0 + average_gain / average_loss))
  86. return rsi
  87. def close_position(
  88. trades: list[dict[str, object]],
  89. exits: list[dict[str, object]],
  90. position: dict[str, object],
  91. account_equity: float,
  92. candle: Candle,
  93. exit_price: float,
  94. reason: str,
  95. ) -> tuple[float, bool]:
  96. margin_used = float(position["margin_used"])
  97. exit_margin_equity = trade_equity(
  98. side="long",
  99. margin_used=margin_used,
  100. entry_price=float(position["entry_price"]),
  101. exit_price=exit_price,
  102. leverage=LEVERAGE,
  103. )
  104. pnl = exit_margin_equity - margin_used
  105. cost_weight = margin_used / account_equity
  106. trades.append(
  107. {
  108. "side": "Long",
  109. "entry_time": fmt_ts(int(position["entry_time"])),
  110. "exit_time": fmt_ts(candle.ts),
  111. "entry_price": round(float(position["entry_price"]), 4),
  112. "exit_price": round(exit_price, 4),
  113. "pnl": round(pnl, 4),
  114. "return_pct": round(pnl / account_equity * 100.0, 4),
  115. "return_fraction": pnl / account_equity,
  116. "cost_weight": round(cost_weight, 8),
  117. "margin_used": round(margin_used, 8),
  118. "account_equity_before_exit": round(account_equity, 8),
  119. "reason": reason,
  120. }
  121. )
  122. exits.append({"ts": candle.ts, "price": exit_price, "side": "long", "reason": reason})
  123. return account_equity + pnl, pnl > 0.0
  124. def run_corrected_price_twap(candles: list[Candle], spec: Spec) -> SegmentResult:
  125. closes = pd.Series([candle.close for candle in candles], dtype=float)
  126. trend = closes.rolling(spec.trend_sma).mean().tolist()
  127. rsi_values = compute_rsi(closes, spec.rsi_length)
  128. warmup_bars = max(spec.trend_sma, spec.rsi_length + 1)
  129. equity = INITIAL_EQUITY
  130. ending_equity = equity
  131. peak_equity = equity
  132. max_drawdown = 0.0
  133. wins = 0
  134. trades: list[dict[str, object]] = []
  135. entries: list[dict[str, object]] = []
  136. exits: list[dict[str, object]] = []
  137. equity_curve: list[dict[str, float | int]] = []
  138. position: dict[str, object] | None = None
  139. pending_limits: list[dict[str, float | int]] = []
  140. pending_exit = False
  141. for index in range(warmup_bars, len(candles)):
  142. candle = candles[index]
  143. if pending_exit and position is not None:
  144. equity, won = close_position(trades, exits, position, equity, candle, candle.open, "signal_or_max_hold")
  145. wins += 1 if won else 0
  146. position = None
  147. pending_exit = False
  148. pending_limits = []
  149. active_limits: list[dict[str, float | int]] = []
  150. filled_this_bar = 0
  151. for limit in pending_limits:
  152. if index > int(limit["expires_index"]):
  153. continue
  154. limit_price = float(limit["price"])
  155. if candle.low <= limit_price * (1.0 - spec.fill_buffer) and equity > 0.0:
  156. slice_margin = equity / len(spec.entry_offsets)
  157. filled_this_bar += 1
  158. if position is None:
  159. position = {
  160. "side": "long",
  161. "entry_time": candle.ts,
  162. "entry_price": limit_price,
  163. "entry_index": index,
  164. "margin_used": slice_margin,
  165. "stop_price": limit_price * (1.0 - spec.stop_loss_pct),
  166. }
  167. else:
  168. old_margin = float(position["margin_used"])
  169. new_margin = old_margin + slice_margin
  170. position["entry_price"] = (float(position["entry_price"]) * old_margin + limit_price * slice_margin) / new_margin
  171. position["margin_used"] = new_margin
  172. position["stop_price"] = float(position["entry_price"]) * (1.0 - spec.stop_loss_pct)
  173. entries.append({"ts": candle.ts, "price": limit_price, "side": "long"})
  174. else:
  175. active_limits.append(limit)
  176. pending_limits = active_limits
  177. current_equity = equity
  178. if position is not None and candle.low <= float(position["stop_price"]):
  179. equity, won = close_position(trades, exits, position, equity, candle, float(position["stop_price"]), "stop")
  180. wins += 1 if won else 0
  181. current_equity = equity
  182. position = None
  183. pending_limits = []
  184. if position is not None:
  185. position_equity = mark_to_market(
  186. side="long",
  187. margin_used=float(position["margin_used"]),
  188. entry_price=float(position["entry_price"]),
  189. mark_price=candle.close,
  190. leverage=LEVERAGE,
  191. )
  192. current_equity = equity - float(position["margin_used"]) + position_equity
  193. equity_curve.append(
  194. {
  195. "ts": candle.ts,
  196. "equity": current_equity,
  197. "close": candle.close,
  198. "cash": equity - float(position["margin_used"]),
  199. "margin_used": float(position["margin_used"]),
  200. "open_position_equity": position_equity,
  201. "filled_slices_this_bar": filled_this_bar,
  202. }
  203. )
  204. else:
  205. equity_curve.append(
  206. {
  207. "ts": candle.ts,
  208. "equity": current_equity,
  209. "close": candle.close,
  210. "cash": equity,
  211. "margin_used": 0.0,
  212. "open_position_equity": 0.0,
  213. "filled_slices_this_bar": filled_this_bar,
  214. }
  215. )
  216. peak_equity = max(peak_equity, current_equity)
  217. max_drawdown = max(max_drawdown, (peak_equity - current_equity) / peak_equity)
  218. ending_equity = current_equity
  219. if index == len(candles) - 1 or equity <= 0.0:
  220. continue
  221. current_rsi = rsi_values[index]
  222. current_trend = trend[index]
  223. if current_rsi != current_rsi or current_trend != current_trend:
  224. continue
  225. if position is not None:
  226. held_bars = index - int(position["entry_index"])
  227. if current_rsi >= spec.exit_rsi or held_bars >= spec.max_hold_bars:
  228. pending_exit = True
  229. pending_limits = []
  230. continue
  231. if not pending_limits and candle.close > float(current_trend) and current_rsi <= spec.rsi_threshold:
  232. pending_limits = [
  233. {"price": candle.close * (1.0 - offset), "expires_index": index + spec.entry_valid_bars}
  234. for offset in spec.entry_offsets
  235. ]
  236. trade_count = len(trades)
  237. return SegmentResult(
  238. trade_count=trade_count,
  239. total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
  240. win_rate=wins / trade_count if trade_count else 0.0,
  241. max_drawdown=max_drawdown,
  242. trades=trades,
  243. open_position=position,
  244. candles=candles[warmup_bars:],
  245. equity_curve=equity_curve,
  246. entries=entries,
  247. exits=exits,
  248. )
  249. def cost_adjusted_equity_frame(result: SegmentResult, roundtrip_cost_on_margin: float) -> pd.DataFrame:
  250. rows = [{"ts": pd.to_datetime(result.equity_curve[0]["ts"], unit="ms", utc=True), "equity": INITIAL_EQUITY}]
  251. equity = INITIAL_EQUITY
  252. for trade in result.trades:
  253. equity *= 1.0 + float(trade["return_fraction"]) - roundtrip_cost_on_margin * float(trade["cost_weight"])
  254. rows.append({"ts": pd.to_datetime(str(trade["exit_time"]), utc=True), "equity": equity})
  255. if result.open_position is not None:
  256. rows.append(
  257. {
  258. "ts": pd.to_datetime(result.equity_curve[-1]["ts"], unit="ms", utc=True),
  259. "equity": float(result.equity_curve[-1]["equity"]),
  260. }
  261. )
  262. return pd.DataFrame(rows)
  263. def metrics_from_equity(frame: pd.DataFrame, first_ts: int, last_ts: int) -> dict[str, float]:
  264. years = (last_ts - first_ts) / 86_400_000 / 365
  265. total_return = float(frame["equity"].iloc[-1] / frame["equity"].iloc[0] - 1.0)
  266. annualized_return = (1.0 + total_return) ** (1.0 / years) - 1.0 if total_return > -1.0 and years > 0.0 else 0.0
  267. max_dd = explore.max_drawdown_from_equity([float(value) for value in frame["equity"]])
  268. return {
  269. "total_return": total_return,
  270. "annualized_return": annualized_return,
  271. "max_drawdown": max_dd,
  272. "calmar": annualized_return / max_dd if max_dd else 0.0,
  273. }
  274. def horizon_frame(frame: pd.DataFrame, last_ts: int, offset: pd.DateOffset | None) -> tuple[pd.DataFrame, int]:
  275. if offset is None:
  276. start_ts = int(frame["ts"].iloc[0].timestamp() * 1000)
  277. return frame[["ts", "equity"]].copy(), start_ts
  278. end = pd.to_datetime(last_ts, unit="ms", utc=True)
  279. cutoff = end - offset
  280. before = frame[frame["ts"] <= cutoff]
  281. if len(before):
  282. start_equity = float(before["equity"].iloc[-1])
  283. sliced = pd.concat(
  284. [
  285. pd.DataFrame([{"ts": cutoff, "equity": start_equity}]),
  286. frame[frame["ts"] > cutoff][["ts", "equity"]],
  287. ],
  288. ignore_index=True,
  289. )
  290. return sliced, int(cutoff.timestamp() * 1000)
  291. sliced = frame[["ts", "equity"]].copy()
  292. return sliced, int(sliced["ts"].iloc[0].timestamp() * 1000)
  293. def horizon_rows(result: SegmentResult, spec: Spec, candles: list[Candle], cost_label: str, cost_value: float) -> list[dict[str, object]]:
  294. frame = cost_adjusted_equity_frame(result, cost_value)
  295. rows = []
  296. for label, offset in HORIZONS:
  297. sliced, start_ts = horizon_frame(frame, candles[-1].ts, offset)
  298. metrics = metrics_from_equity(sliced, start_ts, candles[-1].ts)
  299. rows.append(
  300. {
  301. "name": spec.name,
  302. "cost_model": cost_label,
  303. "roundtrip_cost_on_margin": cost_value,
  304. "horizon": label,
  305. "horizon_start": fmt_ts(start_ts),
  306. "horizon_end": fmt_ts(candles[-1].ts),
  307. "trades": result.trade_count,
  308. **metrics,
  309. "trend_sma": spec.trend_sma,
  310. "rsi_length": spec.rsi_length,
  311. "rsi_threshold": spec.rsi_threshold,
  312. "exit_rsi": spec.exit_rsi,
  313. "stop_loss_pct": spec.stop_loss_pct,
  314. "max_hold_bars": spec.max_hold_bars,
  315. "entry_offsets": "-".join(f"{offset:.4f}" for offset in spec.entry_offsets),
  316. "entry_valid_bars": spec.entry_valid_bars,
  317. "fill_buffer": spec.fill_buffer,
  318. }
  319. )
  320. return rows
  321. def accounting_rows(candles: list[Candle], spec: Spec) -> tuple[list[dict[str, object]], SegmentResult, SegmentResult]:
  322. legacy_candidate = explore.build_rsi2_long_guarded_price_twap_candidate(
  323. spec.trend_sma,
  324. spec.rsi_threshold,
  325. spec.exit_rsi,
  326. spec.stop_loss_pct,
  327. spec.max_hold_bars,
  328. spec.entry_offsets,
  329. spec.entry_valid_bars,
  330. spec.fill_buffer,
  331. )
  332. legacy = legacy_candidate.run(candles=candles, leverage=LEVERAGE, warmup_bars=legacy_candidate.warmup_bars)
  333. corrected = run_corrected_price_twap(candles, spec)
  334. corrected_closed = cost_adjusted_equity_frame(corrected, 0.0)
  335. legacy_closed = explore.cost_adjusted_trade_equity_frame(legacy, 0.0)
  336. return (
  337. [
  338. {
  339. "check": "legacy_mtm_vs_legacy_closed_trade",
  340. "legacy_mtm_total_return": legacy.total_return,
  341. "legacy_closed_trade_total_return": float(legacy_closed["equity"].iloc[-1] / INITIAL_EQUITY - 1.0),
  342. "absolute_gap": abs(legacy.total_return - float(legacy_closed["equity"].iloc[-1] / INITIAL_EQUITY + -1.0)),
  343. "pass": False,
  344. "reason": "regular exit replaces account equity with margin equity and drops unused cash when partial TWAP fills occur",
  345. },
  346. {
  347. "check": "corrected_mtm_vs_corrected_closed_trade_gross",
  348. "corrected_mtm_total_return": corrected.total_return,
  349. "corrected_closed_trade_total_return": float(corrected_closed["equity"].iloc[-1] / INITIAL_EQUITY - 1.0),
  350. "absolute_gap": abs(corrected.total_return - float(corrected_closed["equity"].iloc[-1] / INITIAL_EQUITY - 1.0)),
  351. "pass": corrected.open_position is None
  352. and abs(corrected.total_return - float(corrected_closed["equity"].iloc[-1] / INITIAL_EQUITY - 1.0)) < 1e-8,
  353. "reason": "all closed-trade returns are measured against account equity and weighted by margin_used/account_equity",
  354. },
  355. {
  356. "check": "position_sizing",
  357. "max_cost_weight": max(float(trade["cost_weight"]) for trade in corrected.trades) if corrected.trades else 0.0,
  358. "min_cost_weight": min(float(trade["cost_weight"]) for trade in corrected.trades) if corrected.trades else 0.0,
  359. "open_position": corrected.open_position is not None,
  360. "pass": corrected.open_position is None
  361. and all(0.0 < float(trade["cost_weight"]) <= 1.00000001 for trade in corrected.trades),
  362. "reason": "TWAP sizing uses account_equity/number_of_offsets per filled slice; cost is charged only on filled margin",
  363. },
  364. ],
  365. legacy,
  366. corrected,
  367. )
  368. def retest_specs() -> list[Spec]:
  369. specs = {BASE_SPEC.name: BASE_SPEC}
  370. variants = [
  371. {"entry_offsets": (0.002, 0.005, 0.008)},
  372. {"entry_offsets": (0.004, 0.007, 0.010)},
  373. {"entry_valid_bars": 3},
  374. {"trend_sma": 50},
  375. {"trend_sma": 80},
  376. {"rsi_length": 3},
  377. {"exit_rsi": 45.0},
  378. {"stop_loss_pct": 0.010},
  379. {"max_hold_bars": 36},
  380. ]
  381. for values in variants:
  382. spec = Spec(
  383. trend_sma=int(values.get("trend_sma", BASE_SPEC.trend_sma)),
  384. rsi_length=int(values.get("rsi_length", BASE_SPEC.rsi_length)),
  385. rsi_threshold=float(values.get("rsi_threshold", BASE_SPEC.rsi_threshold)),
  386. exit_rsi=float(values.get("exit_rsi", BASE_SPEC.exit_rsi)),
  387. stop_loss_pct=float(values.get("stop_loss_pct", BASE_SPEC.stop_loss_pct)),
  388. max_hold_bars=int(values.get("max_hold_bars", BASE_SPEC.max_hold_bars)),
  389. entry_offsets=tuple(values.get("entry_offsets", BASE_SPEC.entry_offsets)),
  390. entry_valid_bars=int(values.get("entry_valid_bars", BASE_SPEC.entry_valid_bars)),
  391. fill_buffer=float(values.get("fill_buffer", BASE_SPEC.fill_buffer)),
  392. )
  393. specs[spec.name] = spec
  394. return list(specs.values())
  395. def markdown_table(frame: pd.DataFrame, columns: list[str]) -> str:
  396. rows = [["" if pd.isna(value) else str(value) for value in row] for row in frame[columns].itertuples(index=False, name=None)]
  397. return "\n".join(
  398. [
  399. "| " + " | ".join(columns) + " |",
  400. "| " + " | ".join("---" for _ in columns) + " |",
  401. *["| " + " | ".join(row) + " |" for row in rows],
  402. ]
  403. )
  404. def main() -> int:
  405. candles = load_candles()
  406. OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
  407. accounting, legacy, corrected = accounting_rows(candles, BASE_SPEC)
  408. accounting_ok = all(bool(row["pass"]) for row in accounting if row["check"] != "legacy_mtm_vs_legacy_closed_trade")
  409. all_rows: list[dict[str, object]] = []
  410. if accounting_ok:
  411. for spec in retest_specs():
  412. result = run_corrected_price_twap(candles, spec)
  413. for cost_label, cost_value in COSTS.items():
  414. all_rows.extend(horizon_rows(result, spec, candles, cost_label, cost_value))
  415. accounting_frame = pd.DataFrame(accounting)
  416. horizon_frame_out = pd.DataFrame(all_rows)
  417. accounting_frame.to_csv(OUTPUT_DIR / f"{PREFIX}-accounting.csv", index=False)
  418. horizon_frame_out.to_csv(OUTPUT_DIR / f"{PREFIX}-horizons.csv", index=False)
  419. top = pd.DataFrame()
  420. if len(horizon_frame_out):
  421. pivot = horizon_frame_out.pivot_table(
  422. index=[
  423. "name",
  424. "cost_model",
  425. "trades",
  426. "trend_sma",
  427. "rsi_length",
  428. "rsi_threshold",
  429. "exit_rsi",
  430. "stop_loss_pct",
  431. "max_hold_bars",
  432. "entry_offsets",
  433. "entry_valid_bars",
  434. "fill_buffer",
  435. ],
  436. columns="horizon",
  437. values=["total_return", "annualized_return", "max_drawdown", "calmar"],
  438. aggfunc="first",
  439. observed=False,
  440. )
  441. pivot.columns = [f"{metric}_{horizon}" for metric, horizon in pivot.columns]
  442. ranked = pivot.reset_index()
  443. ranked["min_recent_calmar"] = ranked[["calmar_1y", "calmar_6m", "calmar_3m", "calmar_30d", "calmar_21d"]].min(axis=1)
  444. ranked["max_recent_drawdown"] = ranked[["max_drawdown_1y", "max_drawdown_6m", "max_drawdown_3m", "max_drawdown_30d", "max_drawdown_21d"]].max(axis=1)
  445. ranked["min_recent_return"] = ranked[["total_return_1y", "total_return_6m", "total_return_3m", "total_return_30d", "total_return_21d"]].min(axis=1)
  446. ranked = ranked.sort_values(
  447. ["cost_model", "min_recent_return", "min_recent_calmar", "calmar_3y", "annualized_return_full"],
  448. ascending=[True, False, False, False, False],
  449. )
  450. ranked.to_csv(OUTPUT_DIR / f"{PREFIX}-ranked.csv", index=False)
  451. top = ranked.groupby("cost_model", group_keys=False).head(5)
  452. else:
  453. pd.DataFrame().to_csv(OUTPUT_DIR / f"{PREFIX}-ranked.csv", index=False)
  454. base_horizons = horizon_frame_out[horizon_frame_out["name"] == BASE_SPEC.name] if len(horizon_frame_out) else pd.DataFrame()
  455. summary_path = OUTPUT_DIR / f"{PREFIX}-summary.md"
  456. summary_path.write_text(
  457. "\n".join(
  458. [
  459. "# ETH Robust TWAP Accounting Audit",
  460. "",
  461. f"Candidate: `{BASE_SPEC.name}`",
  462. f"Candles: {len(candles)} from {fmt_ts(candles[0].ts)} to {fmt_ts(candles[-1].ts)}",
  463. "",
  464. "## Accounting",
  465. "",
  466. f"- Legacy runner mark-to-market return: {pct(legacy.total_return)}",
  467. f"- Corrected gross mark-to-market return: {pct(corrected.total_return)}",
  468. f"- Corrected open position at end: {corrected.open_position is not None}",
  469. f"- Corrected trades: {corrected.trade_count}",
  470. f"- Accounting status for corrected path: {'PASS' if accounting_ok else 'FAIL'}",
  471. "",
  472. markdown_table(accounting_frame, list(accounting_frame.columns)),
  473. "",
  474. "## Base Candidate Horizons",
  475. "",
  476. markdown_table(
  477. base_horizons.sort_values(["cost_model", "horizon"]),
  478. [
  479. "cost_model",
  480. "horizon",
  481. "total_return",
  482. "annualized_return",
  483. "max_drawdown",
  484. "calmar",
  485. ],
  486. )
  487. if len(base_horizons)
  488. else "Not ranked because accounting failed.",
  489. "",
  490. "## Small Retest Top 5 Per Cost",
  491. "",
  492. markdown_table(
  493. top,
  494. [
  495. "cost_model",
  496. "name",
  497. "trades",
  498. "total_return_full",
  499. "annualized_return_full",
  500. "max_drawdown_full",
  501. "total_return_3y",
  502. "total_return_1y",
  503. "total_return_6m",
  504. "total_return_3m",
  505. "total_return_30d",
  506. "total_return_21d",
  507. "min_recent_return",
  508. ],
  509. )
  510. if len(top)
  511. else "Not ranked because accounting failed.",
  512. "",
  513. "## Files",
  514. "",
  515. f"- `{OUTPUT_DIR / f'{PREFIX}-accounting.csv'}`",
  516. f"- `{OUTPUT_DIR / f'{PREFIX}-horizons.csv'}`",
  517. f"- `{OUTPUT_DIR / f'{PREFIX}-ranked.csv'}`",
  518. f"- `{summary_path}`",
  519. "",
  520. ]
  521. ),
  522. encoding="utf-8",
  523. )
  524. print(f"summary={summary_path}")
  525. print(f"legacy_total_return={legacy.total_return:.8f}")
  526. print(f"corrected_total_return={corrected.total_return:.8f}")
  527. print(f"accounting_ok={accounting_ok}")
  528. return 0 if accounting_ok else 1
  529. if __name__ == "__main__":
  530. raise SystemExit(main())