search_eth_bb_squeeze_t_gates.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. from __future__ import annotations
  2. import argparse
  3. import sys
  4. from dataclasses import dataclass
  5. from pathlib import Path
  6. import pandas as pd
  7. sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
  8. from okx_codex_trader.models import Candle
  9. from okx_codex_trader.sampled_report import SegmentResult, mark_to_market, trade_equity
  10. ETH_SYMBOL = "ETH-USDT-SWAP"
  11. BTC_SYMBOL = "BTC-USDT-SWAP"
  12. BAR = "15m"
  13. YEARS = 10.0
  14. LEVERAGE = 3
  15. INITIAL_EQUITY = 10_000.0
  16. DATA_DIR = Path("data/okx-candles")
  17. OUTPUT_DIR = Path("reports/eth-exploration")
  18. PRIMARY_COST = "maker_taker"
  19. COSTS = (
  20. ("maker_maker", 0.0012),
  21. ("maker_taker", 0.0021),
  22. ("taker_taker", 0.0030),
  23. )
  24. @dataclass(frozen=True)
  25. class Variant:
  26. band_length: int
  27. bandwidth_lookback: int
  28. bandwidth_quantile: float
  29. stop_loss_pct: float
  30. extreme_take_profit_pct: float
  31. side_mode: str
  32. entry_btc_filter: str
  33. entry_eth_vol_cap: float | None
  34. dd_overlay: float | None
  35. cooldown_bars: int
  36. reentry_bars: int
  37. gate_mode: str
  38. middle_exit_buffer_pct: float
  39. middle_exit_confirm_bars: int
  40. high_eth_vol_floor: float
  41. far_band_extension: float
  42. recent_profit_threshold: float
  43. @property
  44. def name(self) -> str:
  45. vol_cap = "none" if self.entry_eth_vol_cap is None else f"{self.entry_eth_vol_cap:g}"
  46. dd = "none" if self.dd_overlay is None else f"{self.dd_overlay:g}"
  47. return (
  48. f"bb-squeeze-t-l{self.band_length}-bw{self.bandwidth_lookback}"
  49. f"-q{self.bandwidth_quantile:g}-sl{self.stop_loss_pct:g}"
  50. f"-xtp{self.extreme_take_profit_pct:g}-{self.side_mode}-{self.entry_btc_filter}"
  51. f"-vc{vol_cap}-dd{dd}-cd{self.cooldown_bars}"
  52. f"-tre{self.reentry_bars}-{self.gate_mode}"
  53. f"-mxbuf{self.middle_exit_buffer_pct:g}-mxc{self.middle_exit_confirm_bars}"
  54. f"-hv{self.high_eth_vol_floor:g}-fb{self.far_band_extension:g}"
  55. f"-rp{self.recent_profit_threshold:g}"
  56. )
  57. def _format_ts(ts: int) -> str:
  58. return pd.to_datetime(ts, unit="ms", utc=True).strftime("%Y-%m-%d %H:%M")
  59. def _load_candles(symbol: str, bar: str) -> list[Candle]:
  60. frame = pd.read_csv(DATA_DIR / symbol / f"{bar}.csv")
  61. return [
  62. Candle(
  63. symbol=symbol,
  64. ts=int(row.ts),
  65. open=float(row.open),
  66. high=float(row.high),
  67. low=float(row.low),
  68. close=float(row.close),
  69. volume=float(row.volume),
  70. )
  71. for row in frame.itertuples(index=False)
  72. ]
  73. def _align_pair(left: list[Candle], right: list[Candle]) -> tuple[list[Candle], list[Candle]]:
  74. right_by_ts = {candle.ts: candle for candle in right}
  75. left_out: list[Candle] = []
  76. right_out: list[Candle] = []
  77. for candle in left:
  78. other = right_by_ts.get(candle.ts)
  79. if other is not None:
  80. left_out.append(candle)
  81. right_out.append(other)
  82. return left_out, right_out
  83. def _close_position(
  84. *,
  85. trades: list[dict[str, object]],
  86. exits: list[dict[str, object]],
  87. position: dict[str, object],
  88. candle: Candle,
  89. exit_price: float,
  90. reason: str,
  91. ) -> tuple[float, bool]:
  92. margin_used = float(position["margin_used"])
  93. exit_equity = trade_equity(
  94. side=str(position["side"]),
  95. margin_used=margin_used,
  96. entry_price=float(position["entry_price"]),
  97. exit_price=exit_price,
  98. leverage=LEVERAGE,
  99. )
  100. pnl = exit_equity - margin_used
  101. trades.append(
  102. {
  103. "side": "Long" if position["side"] == "long" else "Short",
  104. "entry_time": _format_ts(int(position["entry_time"])),
  105. "exit_time": _format_ts(candle.ts),
  106. "entry_price": round(float(position["entry_price"]), 4),
  107. "exit_price": round(exit_price, 4),
  108. "pnl": round(pnl, 4),
  109. "return_pct": round(pnl / margin_used * 100.0, 4),
  110. "cost_weight": 1.0,
  111. "entry_kind": position["entry_kind"],
  112. "exit_reason": reason,
  113. }
  114. )
  115. exits.append({"ts": candle.ts, "price": exit_price, "side": position["side"]})
  116. return exit_equity, pnl > 0.0
  117. def _gate_passes(
  118. *,
  119. variant: Variant,
  120. side: str,
  121. anchor_price: float,
  122. candle: Candle,
  123. btc_momentum: float,
  124. eth_realized_vol: float,
  125. upper: float,
  126. lower: float,
  127. middle: float,
  128. ) -> tuple[bool, dict[str, bool]]:
  129. band_half_width = upper - middle
  130. btc_against = (side == "long" and btc_momentum < 0.0) or (side == "short" and btc_momentum > 0.0)
  131. high_eth_vol = eth_realized_vol >= variant.high_eth_vol_floor
  132. far_band_close = (side == "long" and candle.close >= upper + band_half_width * variant.far_band_extension) or (
  133. side == "short" and candle.close <= lower - band_half_width * variant.far_band_extension
  134. )
  135. recent_profit_spike = (side == "long" and candle.close / anchor_price - 1.0 >= variant.recent_profit_threshold) or (
  136. side == "short" and anchor_price / candle.close - 1.0 >= variant.recent_profit_threshold
  137. )
  138. flags = {
  139. "btc_against": btc_against,
  140. "high_eth_vol": high_eth_vol,
  141. "far_band_close": far_band_close,
  142. "recent_profit_spike": recent_profit_spike,
  143. }
  144. required = variant.gate_mode.split("+")
  145. return all(flags[name] for name in required), flags
  146. def run_variant(eth: list[Candle], btc: list[Candle], variant: Variant) -> tuple[SegmentResult, dict[str, int]]:
  147. eth_close = pd.Series([candle.close for candle in eth], dtype=float)
  148. btc_close = pd.Series([candle.close for candle in btc], dtype=float)
  149. middle_series = eth_close.rolling(variant.band_length).mean()
  150. stdev_series = eth_close.rolling(variant.band_length).std(ddof=0)
  151. upper_values = middle_series + 2.0 * stdev_series
  152. lower_values = middle_series - 2.0 * stdev_series
  153. middle = middle_series.tolist()
  154. upper = upper_values.tolist()
  155. lower = lower_values.tolist()
  156. bandwidth = ((upper_values - lower_values) / middle_series).tolist()
  157. threshold = pd.Series(bandwidth, dtype=float).rolling(variant.bandwidth_lookback).quantile(variant.bandwidth_quantile).tolist()
  158. btc_sma = btc_close.rolling(480).mean().tolist()
  159. btc_momentum = (btc_close / btc_close.shift(96) - 1.0).tolist()
  160. eth_realized_vol = eth_close.pct_change().rolling(96).std(ddof=0).tolist()
  161. warmup_bars = max(variant.band_length, variant.bandwidth_lookback, 480, 96)
  162. equity = INITIAL_EQUITY
  163. ending_equity = equity
  164. peak_equity = equity
  165. max_drawdown = 0.0
  166. wins = 0
  167. trades: list[dict[str, object]] = []
  168. entries: list[dict[str, object]] = []
  169. exits: list[dict[str, object]] = []
  170. equity_curve: list[dict[str, float | int]] = []
  171. position: dict[str, object] | None = None
  172. pending_entry: dict[str, str] | None = None
  173. pending_exit = False
  174. middle_exit_streak = 0
  175. reentry: dict[str, object] | None = None
  176. cooldown_until = -1
  177. gate_stats = {
  178. "extreme_take_exits": 0,
  179. "reentry_windows": 0,
  180. "reentry_entries": 0,
  181. "btc_against_hits": 0,
  182. "high_eth_vol_hits": 0,
  183. "far_band_close_hits": 0,
  184. "recent_profit_spike_hits": 0,
  185. "all_gate_hits": 0,
  186. }
  187. for index in range(warmup_bars, len(eth)):
  188. candle = eth[index]
  189. if pending_exit and position is not None:
  190. equity, won = _close_position(
  191. trades=trades,
  192. exits=exits,
  193. position=position,
  194. candle=candle,
  195. exit_price=candle.open,
  196. reason="middle_exit",
  197. )
  198. wins += int(won)
  199. position = None
  200. pending_exit = False
  201. middle_exit_streak = 0
  202. cooldown_until = index + variant.cooldown_bars
  203. if pending_entry is not None and position is None and equity > 0.0:
  204. side = pending_entry["side"]
  205. position = {
  206. "side": side,
  207. "entry_kind": pending_entry["kind"],
  208. "entry_time": candle.ts,
  209. "entry_price": candle.open,
  210. "margin_used": equity,
  211. "stop_price": candle.open * (1.0 - variant.stop_loss_pct if side == "long" else 1.0 + variant.stop_loss_pct),
  212. "extreme_take_price": candle.open
  213. * (1.0 + variant.extreme_take_profit_pct if side == "long" else 1.0 - variant.extreme_take_profit_pct),
  214. }
  215. entries.append({"ts": candle.ts, "price": candle.open, "side": side})
  216. if pending_entry["kind"] == "reentry":
  217. gate_stats["reentry_entries"] += 1
  218. pending_entry = None
  219. current_equity = equity
  220. if position is not None:
  221. side = str(position["side"])
  222. stop_hit = (side == "long" and candle.low <= float(position["stop_price"])) or (
  223. side == "short" and candle.high >= float(position["stop_price"])
  224. )
  225. extreme_take_hit = (side == "long" and candle.high >= float(position["extreme_take_price"])) or (
  226. side == "short" and candle.low <= float(position["extreme_take_price"])
  227. )
  228. if stop_hit or extreme_take_hit:
  229. reason = "stop" if stop_hit else "extreme_take_profit"
  230. exit_price = float(position["stop_price"] if stop_hit else position["extreme_take_price"])
  231. exit_side = side
  232. equity, won = _close_position(
  233. trades=trades,
  234. exits=exits,
  235. position=position,
  236. candle=candle,
  237. exit_price=exit_price,
  238. reason=reason,
  239. )
  240. wins += int(won)
  241. current_equity = equity
  242. position = None
  243. middle_exit_streak = 0
  244. if extreme_take_hit and not stop_hit:
  245. gate_stats["extreme_take_exits"] += 1
  246. gate_stats["reentry_windows"] += 1
  247. reentry = {
  248. "side": exit_side,
  249. "until": index + variant.reentry_bars,
  250. "anchor_price": exit_price,
  251. }
  252. else:
  253. cooldown_until = index + variant.cooldown_bars
  254. if position is not None:
  255. current_equity = mark_to_market(
  256. side=str(position["side"]),
  257. margin_used=float(position["margin_used"]),
  258. entry_price=float(position["entry_price"]),
  259. mark_price=candle.close,
  260. leverage=LEVERAGE,
  261. )
  262. peak_equity = max(peak_equity, current_equity)
  263. max_drawdown = max(max_drawdown, (peak_equity - current_equity) / peak_equity)
  264. equity_curve.append({"ts": candle.ts, "equity": current_equity, "close": candle.close})
  265. ending_equity = current_equity
  266. if index == len(eth) - 1 or equity <= 0.0:
  267. continue
  268. values = (middle[index], upper[index], lower[index], bandwidth[index], threshold[index], btc_sma[index], btc_momentum[index], eth_realized_vol[index])
  269. if any(value != value for value in values):
  270. continue
  271. if position is None and reentry is not None:
  272. if index > int(reentry["until"]):
  273. reentry = None
  274. else:
  275. passed, flags = _gate_passes(
  276. variant=variant,
  277. side=str(reentry["side"]),
  278. anchor_price=float(reentry["anchor_price"]),
  279. candle=candle,
  280. btc_momentum=float(btc_momentum[index]),
  281. eth_realized_vol=float(eth_realized_vol[index]),
  282. upper=float(upper[index]),
  283. lower=float(lower[index]),
  284. middle=float(middle[index]),
  285. )
  286. for key, value in flags.items():
  287. gate_stats[f"{key}_hits"] += int(value)
  288. gate_stats["all_gate_hits"] += int(passed)
  289. if passed:
  290. pending_entry = {"side": str(reentry["side"]), "kind": "reentry"}
  291. reentry = None
  292. continue
  293. if position is not None:
  294. middle_exit = (
  295. position["side"] == "long" and candle.close < float(middle[index]) * (1.0 - variant.middle_exit_buffer_pct)
  296. ) or (
  297. position["side"] == "short" and candle.close > float(middle[index]) * (1.0 + variant.middle_exit_buffer_pct)
  298. )
  299. middle_exit_streak = middle_exit_streak + 1 if middle_exit else 0
  300. if middle_exit_streak >= variant.middle_exit_confirm_bars:
  301. pending_exit = True
  302. continue
  303. if reentry is not None or index < cooldown_until:
  304. continue
  305. if variant.entry_eth_vol_cap is not None and float(eth_realized_vol[index]) > variant.entry_eth_vol_cap:
  306. continue
  307. if variant.dd_overlay is not None and (peak_equity - current_equity) / peak_equity > variant.dd_overlay:
  308. continue
  309. if variant.entry_btc_filter == "btc-up" and not (btc_close.iloc[index] > float(btc_sma[index])):
  310. continue
  311. if variant.entry_btc_filter == "btc-up-momo" and not (
  312. btc_close.iloc[index] > float(btc_sma[index]) and float(btc_momentum[index]) > 0.0
  313. ):
  314. continue
  315. if bandwidth[index] <= threshold[index]:
  316. if candle.close > float(upper[index]):
  317. pending_entry = {"side": "long", "kind": "initial"}
  318. elif variant.side_mode == "both" and candle.close < float(lower[index]):
  319. pending_entry = {"side": "short", "kind": "initial"}
  320. trade_count = len(trades)
  321. result = SegmentResult(
  322. trade_count=trade_count,
  323. total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
  324. win_rate=wins / trade_count if trade_count else 0.0,
  325. max_drawdown=max_drawdown,
  326. trades=trades,
  327. open_position=position,
  328. candles=eth[warmup_bars:],
  329. equity_curve=equity_curve,
  330. entries=entries,
  331. exits=exits,
  332. )
  333. return result, gate_stats
  334. def cost_equity_frame(result: SegmentResult, cost: float) -> pd.DataFrame:
  335. rows = [{"ts": pd.to_datetime(result.equity_curve[0]["ts"], unit="ms", utc=True), "equity": INITIAL_EQUITY}]
  336. equity = INITIAL_EQUITY
  337. for trade in result.trades:
  338. equity *= 1.0 + float(trade["return_pct"]) / 100.0 - cost * float(trade.get("cost_weight", 1.0))
  339. rows.append({"ts": pd.to_datetime(str(trade["exit_time"]), utc=True), "equity": equity})
  340. return pd.DataFrame(rows)
  341. def max_drawdown(values: list[float]) -> float:
  342. peak = values[0]
  343. dd = 0.0
  344. for value in values:
  345. peak = max(peak, value)
  346. dd = max(dd, (peak - value) / peak if peak else 0.0)
  347. return dd
  348. def equity_metrics(frame: pd.DataFrame, first_ts: int, last_ts: int) -> dict[str, float]:
  349. years = (last_ts - first_ts) / 86_400_000 / 365
  350. total_return = float(frame["equity"].iloc[-1] / frame["equity"].iloc[0] - 1.0)
  351. annualized = (1.0 + total_return) ** (1.0 / years) - 1.0 if total_return > -1.0 and years > 0.0 else 0.0
  352. dd = max_drawdown([float(value) for value in frame["equity"]])
  353. return {
  354. "net_total_return": total_return,
  355. "net_annualized_return": annualized,
  356. "net_max_drawdown": dd,
  357. "net_calmar": annualized / dd if dd else 0.0,
  358. }
  359. def worst_month(frame: pd.DataFrame) -> tuple[str, float]:
  360. monthly = frame.set_index("ts")["equity"].resample("ME").last().ffill().pct_change().dropna()
  361. if not len(monthly):
  362. return "", 0.0
  363. idx = monthly.idxmin()
  364. return idx.strftime("%Y-%m"), float(monthly.loc[idx])
  365. def build_variants() -> list[Variant]:
  366. bases = (
  367. (96, 960, 0.25, "long", "btc-up-momo", 0.006, 0.25),
  368. (96, 960, 0.25, "both", "btc-up-momo", 0.006, 0.25),
  369. (96, 960, 0.25, "both", "btc-up", 0.006, 0.25),
  370. (48, 960, 0.25, "long", "btc-up-momo", None, 0.25),
  371. (48, 960, 0.25, "long", "btc-up", 0.006, 0.25),
  372. (96, 480, 0.15, "both", "none", 0.006, None),
  373. )
  374. gate_modes = (
  375. "btc_against",
  376. "high_eth_vol",
  377. "far_band_close",
  378. "recent_profit_spike",
  379. "btc_against+high_eth_vol",
  380. "far_band_close+recent_profit_spike",
  381. "btc_against+far_band_close+recent_profit_spike",
  382. )
  383. variants: list[Variant] = []
  384. for length, bandwidth_lookback, quantile, side_mode, btc_filter, vol_cap, dd_overlay in bases:
  385. for extreme_take_profit_pct in (0.025, 0.035):
  386. for reentry_bars in (48, 96, 192):
  387. for gate_mode in gate_modes:
  388. for middle_exit_buffer_pct, middle_exit_confirm_bars in (
  389. (0.0, 1),
  390. (0.001, 1),
  391. (0.002, 1),
  392. (0.0, 2),
  393. (0.001, 2),
  394. ):
  395. variants.append(
  396. Variant(
  397. band_length=length,
  398. bandwidth_lookback=bandwidth_lookback,
  399. bandwidth_quantile=quantile,
  400. stop_loss_pct=0.01,
  401. extreme_take_profit_pct=extreme_take_profit_pct,
  402. side_mode=side_mode,
  403. entry_btc_filter=btc_filter,
  404. entry_eth_vol_cap=vol_cap,
  405. dd_overlay=dd_overlay,
  406. cooldown_bars=24,
  407. reentry_bars=reentry_bars,
  408. gate_mode=gate_mode,
  409. middle_exit_buffer_pct=middle_exit_buffer_pct,
  410. middle_exit_confirm_bars=middle_exit_confirm_bars,
  411. high_eth_vol_floor=0.006,
  412. far_band_extension=0.25,
  413. recent_profit_threshold=0.008,
  414. )
  415. )
  416. return variants
  417. def format_cell(value: object) -> str:
  418. if isinstance(value, float):
  419. return f"{value:.6g}"
  420. return str(value).replace("|", "\\|")
  421. def markdown_table(frame: pd.DataFrame) -> str:
  422. columns = list(frame.columns)
  423. rows = [columns, ["---" for _ in columns]]
  424. for record in frame.to_dict("records"):
  425. rows.append([record[column] for column in columns])
  426. return "\n".join("| " + " | ".join(format_cell(value) for value in row) + " |" for row in rows)
  427. def write_report(*, summary: pd.DataFrame, command: str, first_ts: int, last_ts: int, requested_years: float) -> str:
  428. primary = summary[summary["cost"] == PRIMARY_COST]
  429. top_calmar = primary.head(10)
  430. top_reentry = primary.sort_values(
  431. ["reentry_entries", "net_calmar", "net_annualized_return"],
  432. ascending=[False, False, False],
  433. ).head(10)
  434. best = primary.iloc[0] if len(primary) else None
  435. lines = [
  436. "# ETH BB squeeze conditional T gate exploration",
  437. "",
  438. f"Run command: `{command}`",
  439. f"Requested years: {requested_years:g}",
  440. f"Actual continuous local history: `{_format_ts(first_ts)}` to `{_format_ts(last_ts)}`.",
  441. "",
  442. "Output files:",
  443. "- `reports/eth-exploration/eth-bb-squeeze-t-gates-summary.csv`",
  444. "- `reports/eth-exploration/eth-bb-squeeze-t-gates-report.md`",
  445. "",
  446. "Gate semantics: after an extreme take-profit exit, the script opens a same-side reentry window. A reentry is placed only when the selected gate expression is true.",
  447. "",
  448. "Top 10 by maker_taker Calmar:",
  449. markdown_table(
  450. top_calmar[
  451. [
  452. "name",
  453. "trades",
  454. "reentry_entries",
  455. "net_total_return",
  456. "net_annualized_return",
  457. "net_max_drawdown",
  458. "net_calmar",
  459. "worst_month",
  460. "worst_month_return",
  461. ]
  462. ]
  463. ),
  464. "",
  465. "Top 10 by actual reentry count:",
  466. markdown_table(
  467. top_reentry[
  468. [
  469. "name",
  470. "trades",
  471. "reentry_windows",
  472. "reentry_entries",
  473. "all_gate_hits",
  474. "net_annualized_return",
  475. "net_max_drawdown",
  476. "net_calmar",
  477. ]
  478. ]
  479. ),
  480. "",
  481. "Verdict:",
  482. ]
  483. if best is None:
  484. lines.append("- No result rows were produced.")
  485. else:
  486. lines.append(
  487. f"- Best maker_taker Calmar: `{best['name']}` with Calmar {format_cell(best['net_calmar'])}, "
  488. f"annualized {format_cell(best['net_annualized_return'])}, MDD {format_cell(best['net_max_drawdown'])}, "
  489. f"worst month {best['worst_month']} {format_cell(best['worst_month_return'])}, "
  490. f"reentries {best['reentry_entries']}."
  491. )
  492. return "\n".join(lines) + "\n"
  493. def main() -> int:
  494. parser = argparse.ArgumentParser()
  495. parser.add_argument("--bar", default=BAR)
  496. parser.add_argument("--years", type=float, default=YEARS)
  497. parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
  498. args = parser.parse_args()
  499. eth = _load_candles(ETH_SYMBOL, args.bar)
  500. btc = _load_candles(BTC_SYMBOL, args.bar)
  501. eth, btc = _align_pair(eth, btc)
  502. requested_bars = int(args.years * 365 * 24 * 60 / 15)
  503. eth = eth[-requested_bars:]
  504. btc = btc[-requested_bars:]
  505. summary_rows: list[dict[str, object]] = []
  506. variants = build_variants()
  507. for index, variant in enumerate(variants, start=1):
  508. result, gate_stats = run_variant(eth, btc, variant)
  509. if not result.equity_curve:
  510. print(f"skip {index}/{len(variants)} {variant.name}")
  511. continue
  512. for cost_name, cost in COSTS:
  513. frame = cost_equity_frame(result, cost)
  514. metrics = equity_metrics(frame, eth[0].ts, eth[-1].ts)
  515. month, month_return = worst_month(frame)
  516. summary_rows.append(
  517. {
  518. "family": "bb_squeeze_conditional_t_gates",
  519. "cost": cost_name,
  520. "symbol": ETH_SYMBOL,
  521. "signal_symbol": BTC_SYMBOL,
  522. "bar": args.bar,
  523. "name": variant.name,
  524. "band_length": variant.band_length,
  525. "bandwidth_lookback": variant.bandwidth_lookback,
  526. "bandwidth_quantile": variant.bandwidth_quantile,
  527. "stop_loss_pct": variant.stop_loss_pct,
  528. "extreme_take_profit_pct": variant.extreme_take_profit_pct,
  529. "side_mode": variant.side_mode,
  530. "entry_btc_filter": variant.entry_btc_filter,
  531. "entry_eth_vol_cap": variant.entry_eth_vol_cap,
  532. "dd_overlay": variant.dd_overlay,
  533. "cooldown_bars": variant.cooldown_bars,
  534. "reentry_bars": variant.reentry_bars,
  535. "gate_mode": variant.gate_mode,
  536. "middle_exit_buffer_pct": variant.middle_exit_buffer_pct,
  537. "middle_exit_confirm_bars": variant.middle_exit_confirm_bars,
  538. "high_eth_vol_floor": variant.high_eth_vol_floor,
  539. "far_band_extension": variant.far_band_extension,
  540. "recent_profit_threshold": variant.recent_profit_threshold,
  541. "first_candle": _format_ts(eth[0].ts),
  542. "last_candle": _format_ts(eth[-1].ts),
  543. "years": (eth[-1].ts - eth[0].ts) / 86_400_000 / 365,
  544. "trades": result.trade_count,
  545. "gross_total_return": result.total_return,
  546. "gross_max_drawdown_mark_to_market": result.max_drawdown,
  547. "worst_month": month,
  548. "worst_month_return": month_return,
  549. **gate_stats,
  550. **metrics,
  551. }
  552. )
  553. print(f"done {index}/{len(variants)} {variant.name}")
  554. summary = pd.DataFrame(summary_rows).sort_values(
  555. ["cost", "net_calmar", "worst_month_return", "net_annualized_return"],
  556. ascending=[True, False, False, False],
  557. )
  558. primary = summary[summary["cost"] == PRIMARY_COST]
  559. summary = pd.concat([primary, summary[summary["cost"] != PRIMARY_COST]], ignore_index=True)
  560. args.output_dir.mkdir(parents=True, exist_ok=True)
  561. summary_path = args.output_dir / "eth-bb-squeeze-t-gates-summary.csv"
  562. report_path = args.output_dir / "eth-bb-squeeze-t-gates-report.md"
  563. summary.to_csv(summary_path, index=False)
  564. command = f"rtk .venv/bin/python {Path(__file__).as_posix()} --bar {args.bar} --years {args.years}"
  565. report_path.write_text(
  566. write_report(
  567. summary=summary,
  568. command=command,
  569. first_ts=eth[0].ts,
  570. last_ts=eth[-1].ts,
  571. requested_years=args.years,
  572. ),
  573. encoding="utf-8",
  574. )
  575. print(primary.head(10).to_string(index=False))
  576. return 0
  577. if __name__ == "__main__":
  578. raise SystemExit(main())