search_eth_bb_squeeze_exit_management.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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.candles import align_candles_by_ts, load_candles_csv
  9. from okx_codex_trader.models import Candle
  10. from okx_codex_trader.research_metrics import (
  11. DEFAULT_COSTS,
  12. DEFAULT_INITIAL_EQUITY,
  13. DEFAULT_PRIMARY_COST,
  14. cost_equity_frame,
  15. equity_metrics,
  16. format_utc_ts,
  17. trade_stats,
  18. )
  19. from okx_codex_trader.sampled_report import SegmentResult, mark_to_market, trade_equity
  20. from okx_codex_trader.time_rules import entry_allowed, is_us_open_window
  21. ETH_SYMBOL = "ETH-USDT-SWAP"
  22. BTC_SYMBOL = "BTC-USDT-SWAP"
  23. BAR = "15m"
  24. YEARS = 10.0
  25. LEVERAGE = 3
  26. INITIAL_EQUITY = DEFAULT_INITIAL_EQUITY
  27. DATA_DIR = Path("data/okx-candles")
  28. OUTPUT_DIR = Path("reports/eth-exploration")
  29. PRIMARY_COST = DEFAULT_PRIMARY_COST
  30. COSTS = DEFAULT_COSTS
  31. HORIZONS = (
  32. ("full", None),
  33. ("3y", pd.DateOffset(years=3)),
  34. ("1y", pd.DateOffset(years=1)),
  35. ("6m", pd.DateOffset(months=6)),
  36. ("3m", pd.DateOffset(months=3)),
  37. ("21d", pd.DateOffset(days=21)),
  38. )
  39. @dataclass(frozen=True)
  40. class ExitRule:
  41. breakeven_trigger_pct: float | None
  42. breakeven_lock_pct: float
  43. trail_trigger_pct: float | None
  44. trail_giveback_pct: float | None
  45. @property
  46. def name(self) -> str:
  47. be = "none" if self.breakeven_trigger_pct is None else f"{self.breakeven_trigger_pct:g}-{self.breakeven_lock_pct:g}"
  48. tr = "none" if self.trail_trigger_pct is None else f"{self.trail_trigger_pct:g}-{self.trail_giveback_pct:g}"
  49. return f"be{be}-trail{tr}"
  50. def _format_ts(ts: int) -> str:
  51. return format_utc_ts(ts)
  52. def favorable_move(side: str, entry_price: float, candle: Candle) -> float:
  53. if side == "long":
  54. return candle.high / entry_price - 1.0
  55. return entry_price / candle.low - 1.0
  56. def stop_price_for_rule(position: dict[str, object], rule: ExitRule) -> tuple[float, str]:
  57. side = str(position["side"])
  58. entry = float(position["entry_price"])
  59. base_stop = float(position["stop_price"])
  60. mfe = float(position["mfe_pct"])
  61. protected = base_stop
  62. reason = "stop"
  63. if rule.breakeven_trigger_pct is not None and mfe >= rule.breakeven_trigger_pct:
  64. be_stop = entry * (1.0 + rule.breakeven_lock_pct if side == "long" else 1.0 - rule.breakeven_lock_pct)
  65. protected = max(protected, be_stop) if side == "long" else min(protected, be_stop)
  66. reason = "breakeven"
  67. if rule.trail_trigger_pct is not None and rule.trail_giveback_pct is not None and mfe >= rule.trail_trigger_pct:
  68. trail_stop = entry * (1.0 + mfe - rule.trail_giveback_pct if side == "long" else 1.0 - mfe + rule.trail_giveback_pct)
  69. improved = trail_stop > protected if side == "long" else trail_stop < protected
  70. if improved:
  71. protected = trail_stop
  72. reason = "trailing"
  73. return protected, reason if protected != base_stop else "stop"
  74. def exit_price_and_reason(position: dict[str, object], candle: Candle, rule: ExitRule) -> tuple[float, str] | None:
  75. side = str(position["side"])
  76. protected_stop, stop_reason = stop_price_for_rule(position, rule)
  77. take = float(position["take_price"])
  78. if side == "long":
  79. if candle.open <= protected_stop:
  80. return candle.open, f"{stop_reason}_gap" if stop_reason != "stop" else "stop_gap"
  81. if candle.open >= take:
  82. return candle.open, "take_gap"
  83. if candle.low <= protected_stop:
  84. return protected_stop, stop_reason
  85. if candle.high >= take:
  86. return take, "take_profit"
  87. else:
  88. if candle.open >= protected_stop:
  89. return candle.open, f"{stop_reason}_gap" if stop_reason != "stop" else "stop_gap"
  90. if candle.open <= take:
  91. return candle.open, "take_gap"
  92. if candle.high >= protected_stop:
  93. return protected_stop, stop_reason
  94. if candle.low <= take:
  95. return take, "take_profit"
  96. return None
  97. def close_position(
  98. *,
  99. trades: list[dict[str, object]],
  100. exits: list[dict[str, object]],
  101. position: dict[str, object],
  102. candle: Candle,
  103. exit_price: float,
  104. reason: str,
  105. ) -> tuple[float, bool]:
  106. margin_used = float(position["margin_used"])
  107. exit_equity = trade_equity(
  108. side=str(position["side"]),
  109. margin_used=margin_used,
  110. entry_price=float(position["entry_price"]),
  111. exit_price=exit_price,
  112. leverage=LEVERAGE,
  113. )
  114. pnl = exit_equity - margin_used
  115. trades.append(
  116. {
  117. "side": "Long" if position["side"] == "long" else "Short",
  118. "entry_time": _format_ts(int(position["entry_time"])),
  119. "exit_time": _format_ts(candle.ts),
  120. "exit_ts": candle.ts,
  121. "entry_price": round(float(position["entry_price"]), 4),
  122. "exit_price": round(exit_price, 4),
  123. "pnl": round(pnl, 4),
  124. "return_pct": round(pnl / margin_used * 100.0, 4),
  125. "cost_weight": 1.0,
  126. "exit_reason": reason,
  127. "mfe_pct": round(float(position["mfe_pct"]) * 100.0, 4),
  128. }
  129. )
  130. exits.append({"ts": candle.ts, "price": exit_price, "side": position["side"]})
  131. return exit_equity, pnl > 0.0
  132. def run_variant(eth: list[Candle], btc: list[Candle], rule: ExitRule) -> SegmentResult:
  133. eth_close = pd.Series([candle.close for candle in eth], dtype=float)
  134. btc_close = pd.Series([candle.close for candle in btc], dtype=float)
  135. middle_series = eth_close.rolling(96).mean()
  136. stdev_series = eth_close.rolling(96).std(ddof=0)
  137. upper_values = middle_series + 2.0 * stdev_series
  138. lower_values = middle_series - 2.0 * stdev_series
  139. bandwidth = (upper_values - lower_values) / middle_series
  140. threshold = bandwidth.rolling(960).quantile(0.25)
  141. btc_sma = btc_close.rolling(480).mean()
  142. eth_vol = eth_close.pct_change().rolling(96).std(ddof=0)
  143. warmup_bars = 960
  144. equity = INITIAL_EQUITY
  145. ending_equity = equity
  146. peak_equity = equity
  147. max_drawdown = 0.0
  148. wins = 0
  149. trades: list[dict[str, object]] = []
  150. entries: list[dict[str, object]] = []
  151. exits: list[dict[str, object]] = []
  152. equity_curve: list[dict[str, float | int]] = []
  153. position: dict[str, object] | None = None
  154. pending_entry_side: str | None = None
  155. pending_exit = False
  156. middle_exit_streak = 0
  157. cooldown_until = -1
  158. for index in range(warmup_bars, len(eth)):
  159. candle = eth[index]
  160. if pending_exit and position is not None:
  161. equity, won = close_position(
  162. trades=trades,
  163. exits=exits,
  164. position=position,
  165. candle=candle,
  166. exit_price=candle.open,
  167. reason="signal_middle",
  168. )
  169. wins += int(won)
  170. position = None
  171. pending_exit = False
  172. middle_exit_streak = 0
  173. cooldown_until = index + 24
  174. if pending_entry_side is not None and position is None and equity > 0.0:
  175. entry_price = candle.open
  176. position = {
  177. "side": pending_entry_side,
  178. "entry_time": candle.ts,
  179. "entry_price": entry_price,
  180. "margin_used": equity,
  181. "stop_price": entry_price * (0.99 if pending_entry_side == "long" else 1.01),
  182. "take_price": entry_price * (1.03 if pending_entry_side == "long" else 0.97),
  183. "mfe_pct": 0.0,
  184. }
  185. entries.append({"ts": candle.ts, "price": entry_price, "side": pending_entry_side})
  186. pending_entry_side = None
  187. current_equity = equity
  188. if position is not None:
  189. risk_exit = exit_price_and_reason(position, candle, rule)
  190. if risk_exit is not None:
  191. exit_price, reason = risk_exit
  192. equity, won = close_position(trades=trades, exits=exits, position=position, candle=candle, exit_price=exit_price, reason=reason)
  193. wins += int(won)
  194. current_equity = equity
  195. position = None
  196. middle_exit_streak = 0
  197. cooldown_until = index + 24
  198. if position is not None:
  199. position["mfe_pct"] = max(float(position["mfe_pct"]), favorable_move(str(position["side"]), float(position["entry_price"]), candle))
  200. current_equity = mark_to_market(
  201. side=str(position["side"]),
  202. margin_used=float(position["margin_used"]),
  203. entry_price=float(position["entry_price"]),
  204. mark_price=candle.close,
  205. leverage=LEVERAGE,
  206. )
  207. peak_equity = max(peak_equity, current_equity)
  208. max_drawdown = max(max_drawdown, (peak_equity - current_equity) / peak_equity)
  209. equity_curve.append({"ts": candle.ts, "equity": current_equity, "close": candle.close})
  210. ending_equity = current_equity
  211. if index == len(eth) - 1 or equity <= 0.0:
  212. continue
  213. values = (middle_series.iloc[index], upper_values.iloc[index], lower_values.iloc[index], bandwidth.iloc[index], threshold.iloc[index], btc_sma.iloc[index], eth_vol.iloc[index])
  214. if any(value != value for value in values):
  215. continue
  216. if position is not None:
  217. side = str(position["side"])
  218. middle_exit = (side == "long" and candle.close < float(middle_series.iloc[index]) * 0.999) or (
  219. side == "short" and candle.close > float(middle_series.iloc[index]) * 1.001
  220. )
  221. if middle_exit and is_us_open_window(candle.ts):
  222. middle_exit = False
  223. middle_exit_streak = middle_exit_streak + 1 if middle_exit else 0
  224. if middle_exit_streak >= 1:
  225. pending_exit = True
  226. continue
  227. if index < cooldown_until:
  228. continue
  229. if float(eth_vol.iloc[index]) > 0.006:
  230. continue
  231. if not entry_allowed(candle.ts, "weekday"):
  232. continue
  233. if not btc_close.iloc[index] > float(btc_sma.iloc[index]):
  234. continue
  235. if bandwidth.iloc[index] <= threshold.iloc[index]:
  236. if candle.close > float(upper_values.iloc[index]):
  237. pending_entry_side = "long"
  238. elif candle.close < float(lower_values.iloc[index]):
  239. pending_entry_side = "short"
  240. return SegmentResult(
  241. trade_count=len(trades),
  242. total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
  243. win_rate=wins / len(trades) if trades else 0.0,
  244. max_drawdown=max_drawdown,
  245. trades=trades,
  246. open_position=position,
  247. candles=eth[warmup_bars:],
  248. equity_curve=equity_curve,
  249. entries=entries,
  250. exits=exits,
  251. )
  252. def build_rules() -> list[ExitRule]:
  253. rules = [ExitRule(None, 0.0, None, None)]
  254. for trigger in (0.003, 0.005, 0.008, 0.01):
  255. for lock in (0.0, 0.001):
  256. rules.append(ExitRule(trigger, lock, None, None))
  257. for trigger in (0.003, 0.005, 0.008, 0.01):
  258. for giveback in (0.002, 0.003, 0.005):
  259. if giveback < trigger:
  260. rules.append(ExitRule(None, 0.0, trigger, giveback))
  261. for be_trigger in (0.003, 0.005, 0.008):
  262. for trail_trigger in (0.008, 0.01, 0.015):
  263. if trail_trigger > be_trigger:
  264. for giveback in (0.003, 0.005):
  265. rules.append(ExitRule(be_trigger, 0.0, trail_trigger, giveback))
  266. rules.append(ExitRule(be_trigger, 0.001, trail_trigger, giveback))
  267. return sorted(set(rules), key=lambda rule: rule.name)
  268. def window_frame(frame: pd.DataFrame, label: str, offset: pd.DateOffset | None, last_ts: int) -> tuple[pd.DataFrame, int]:
  269. if offset is None:
  270. start_ts = int(pd.Timestamp(frame["ts"].iloc[0]).timestamp() * 1000)
  271. return frame[["ts", "equity"]].copy(), start_ts
  272. end_time = pd.to_datetime(last_ts, unit="ms", utc=True)
  273. cutoff = end_time - offset
  274. before = frame[frame["ts"] <= cutoff]
  275. if len(before):
  276. start_equity = float(before["equity"].iloc[-1])
  277. after = frame[frame["ts"] > cutoff]
  278. scoped = pd.concat([pd.DataFrame([{"ts": cutoff, "equity": start_equity}]), after[["ts", "equity"]]], ignore_index=True)
  279. else:
  280. scoped = frame[["ts", "equity"]].copy()
  281. return scoped, int(pd.Timestamp(scoped["ts"].iloc[0]).timestamp() * 1000)
  282. def window_trades(trades: list[dict[str, object]], start_ts: int, last_ts: int) -> list[dict[str, object]]:
  283. return [trade for trade in trades if start_ts < int(trade["exit_ts"]) <= last_ts]
  284. def exit_reason_rows(name: str, trades: list[dict[str, object]]) -> list[dict[str, object]]:
  285. rows: list[dict[str, object]] = []
  286. for reason, group in pd.DataFrame(trades).groupby("exit_reason") if trades else []:
  287. group_trades = group.to_dict("records")
  288. stats = trade_stats(group_trades)
  289. rows.append(
  290. {
  291. "name": name,
  292. "exit_reason": reason,
  293. "trades": len(group_trades),
  294. "wins": int((group["return_pct"].astype(float) > 0.0).sum()),
  295. "losses": int((group["return_pct"].astype(float) < 0.0).sum()),
  296. "sum_return_pct": float(group["return_pct"].astype(float).sum()),
  297. **stats,
  298. }
  299. )
  300. return rows
  301. def format_cell(value: object) -> str:
  302. if isinstance(value, float):
  303. return f"{value:.6g}"
  304. return str(value).replace("|", "\\|")
  305. def markdown_table(frame: pd.DataFrame) -> str:
  306. rows = [list(frame.columns), ["---" for _ in frame.columns]]
  307. rows.extend(frame.astype(object).where(pd.notna(frame), "").values.tolist())
  308. return "\n".join("| " + " | ".join(format_cell(value) for value in row) + " |" for row in rows)
  309. def write_report(summary: pd.DataFrame, horizons: pd.DataFrame, reasons: pd.DataFrame, command: str, first_ts: int, last_ts: int) -> str:
  310. primary = summary[summary["cost"] == PRIMARY_COST]
  311. top = primary.head(5)
  312. baseline = primary[primary["name"] == "benone-trailnone"].iloc[0]
  313. top_names = set(top["name"])
  314. top_horizons = horizons[(horizons["cost"] == PRIMARY_COST) & (horizons["name"].isin(top_names))]
  315. top_reasons = reasons[reasons["name"].isin(top_names | {"benone-trailnone"})]
  316. return (
  317. "# ETH BB squeeze exit management task C\n\n"
  318. f"Run command: `{command}`\n"
  319. f"Aligned local history: `{_format_ts(first_ts)}` to `{_format_ts(last_ts)}`.\n"
  320. "Entry logic is fixed to the current live baseline: ETH 15m, band 96, bandwidth 960 q0.25, 1% stop, 3% take, middle exit 0.1% x1, vol cap 0.006, cooldown 24, BTC-up, NY weekday entries, skip US-open middle exits, both sides.\n\n"
  321. "Exit priority: pending middle exit at next open, then entry fill; while holding, open gaps are checked before intrabar checks, protected stop/stop-loss is conservative before take-profit, then middle exit can schedule next-open exit. Dynamic protection uses MFE confirmed before the current candle.\n\n"
  322. "## Baseline\n\n"
  323. + markdown_table(pd.DataFrame([baseline])[["name", "trades", "win_rate", "avg_return_pct", "payoff_ratio", "profit_factor", "net_total_return", "net_annualized_return", "net_max_drawdown", "net_calmar"]])
  324. + "\n\n## Top 5 by full maker_taker Calmar\n\n"
  325. + markdown_table(top[["name", "trades", "win_rate", "avg_return_pct", "payoff_ratio", "profit_factor", "net_total_return", "net_annualized_return", "net_max_drawdown", "net_calmar"]])
  326. + "\n\n## Top 5 horizons\n\n"
  327. + markdown_table(top_horizons[["name", "horizon", "trades", "win_rate", "avg_return_pct", "payoff_ratio", "profit_factor", "net_total_return", "net_annualized_return", "net_max_drawdown", "net_calmar"]])
  328. + "\n\n## Exit reason distribution\n\n"
  329. + markdown_table(top_reasons[["name", "exit_reason", "trades", "wins", "losses", "sum_return_pct", "avg_return_pct", "payoff_ratio", "profit_factor"]])
  330. + "\n\n## Recommendation\n\n"
  331. "Do not update live from this task unless a candidate beats the baseline on full-window Calmar and does not degrade 1y, 6m, 3m, and 21d net total return versus baseline. See CSV outputs for the strict comparison.\n"
  332. )
  333. def main() -> int:
  334. parser = argparse.ArgumentParser()
  335. parser.add_argument("--bar", default=BAR)
  336. parser.add_argument("--years", type=float, default=YEARS)
  337. parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
  338. args = parser.parse_args()
  339. eth = load_candles_csv(DATA_DIR, ETH_SYMBOL, args.bar)
  340. btc = load_candles_csv(DATA_DIR, BTC_SYMBOL, args.bar)
  341. eth, btc = align_candles_by_ts(eth, btc)
  342. requested_bars = int(args.years * 365 * 24 * 60 / 15)
  343. eth = eth[-requested_bars:]
  344. btc = btc[-requested_bars:]
  345. summary_rows: list[dict[str, object]] = []
  346. horizon_rows: list[dict[str, object]] = []
  347. reason_rows: list[dict[str, object]] = []
  348. for index, rule in enumerate(build_rules(), start=1):
  349. result = run_variant(eth, btc, rule)
  350. stats = trade_stats(result.trades)
  351. reason_rows.extend(exit_reason_rows(rule.name, result.trades))
  352. for cost_name, cost in COSTS:
  353. frame = cost_equity_frame(result, cost)
  354. full_metrics = equity_metrics(frame, eth[0].ts, eth[-1].ts)
  355. summary_rows.append(
  356. {
  357. "cost": cost_name,
  358. "symbol": ETH_SYMBOL,
  359. "signal_symbol": BTC_SYMBOL,
  360. "bar": args.bar,
  361. "name": rule.name,
  362. "breakeven_trigger_pct": rule.breakeven_trigger_pct,
  363. "breakeven_lock_pct": rule.breakeven_lock_pct,
  364. "trail_trigger_pct": rule.trail_trigger_pct,
  365. "trail_giveback_pct": rule.trail_giveback_pct,
  366. "first_candle": _format_ts(eth[0].ts),
  367. "last_candle": _format_ts(eth[-1].ts),
  368. "trades": result.trade_count,
  369. "win_rate": result.win_rate,
  370. "gross_total_return": result.total_return,
  371. "gross_max_drawdown_mark_to_market": result.max_drawdown,
  372. **stats,
  373. **full_metrics,
  374. }
  375. )
  376. for label, offset in HORIZONS:
  377. scoped, start_ts = window_frame(frame, label, offset, eth[-1].ts)
  378. scoped_trades = window_trades(result.trades, start_ts, eth[-1].ts)
  379. horizon_rows.append(
  380. {
  381. "cost": cost_name,
  382. "symbol": ETH_SYMBOL,
  383. "bar": args.bar,
  384. "name": rule.name,
  385. "horizon": label,
  386. "horizon_start": pd.to_datetime(start_ts, unit="ms", utc=True).strftime("%Y-%m-%d %H:%M"),
  387. "horizon_end": _format_ts(eth[-1].ts),
  388. "trades": len(scoped_trades),
  389. "win_rate": sum(1 for trade in scoped_trades if float(trade["return_pct"]) > 0.0) / len(scoped_trades) if scoped_trades else 0.0,
  390. **trade_stats(scoped_trades),
  391. **equity_metrics(scoped, start_ts, eth[-1].ts),
  392. }
  393. )
  394. print(f"done {index}/{len(build_rules())} {rule.name}", flush=True)
  395. summary = pd.DataFrame(summary_rows).sort_values(["cost", "net_calmar", "net_annualized_return"], ascending=[True, False, False])
  396. primary = summary[summary["cost"] == PRIMARY_COST]
  397. summary = pd.concat([primary, summary[summary["cost"] != PRIMARY_COST]], ignore_index=True)
  398. horizons = pd.DataFrame(horizon_rows)
  399. horizons["horizon"] = pd.Categorical(horizons["horizon"], categories=[label for label, _ in HORIZONS], ordered=True)
  400. horizons = horizons.sort_values(["cost", "horizon", "net_calmar", "net_total_return"], ascending=[True, True, False, False])
  401. reasons = pd.DataFrame(reason_rows).sort_values(["name", "exit_reason"])
  402. args.output_dir.mkdir(parents=True, exist_ok=True)
  403. prefix = "eth-bb-squeeze-exit-management"
  404. summary_path = args.output_dir / f"{prefix}-summary.csv"
  405. horizon_path = args.output_dir / f"{prefix}-horizons.csv"
  406. reason_path = args.output_dir / f"{prefix}-exit-reasons.csv"
  407. report_path = args.output_dir / f"{prefix}-report.md"
  408. summary.to_csv(summary_path, index=False)
  409. horizons.to_csv(horizon_path, index=False)
  410. reasons.to_csv(reason_path, index=False)
  411. command = f"rtk .venv/bin/python {Path(__file__).as_posix()} --bar {args.bar} --years {args.years} --output-dir {args.output_dir.as_posix()}"
  412. report_path.write_text(write_report(summary, horizons, reasons, command, eth[0].ts, eth[-1].ts), encoding="utf-8")
  413. print(primary.head(5).to_string(index=False))
  414. return 0
  415. if __name__ == "__main__":
  416. raise SystemExit(main())