search_eth_bb_squeeze_risk_10y.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. HORIZONS = (
  25. ("3y", pd.DateOffset(years=3)),
  26. ("1y", pd.DateOffset(years=1)),
  27. ("6m", pd.DateOffset(months=6)),
  28. ("3m", pd.DateOffset(months=3)),
  29. )
  30. @dataclass(frozen=True)
  31. class Variant:
  32. band_length: int
  33. bandwidth_lookback: int
  34. bandwidth_quantile: float
  35. stop_loss_pct: float
  36. take_profit_pct: float | None
  37. extreme_take_profit_pct: float | None
  38. extreme_band_extension: float | None
  39. extreme_reentry_bars: int | None
  40. side_mode: str
  41. btc_filter: str
  42. eth_vol_cap: float | None
  43. dd_overlay: float | None
  44. cooldown_bars: int
  45. @property
  46. def name(self) -> str:
  47. tp = "none" if self.take_profit_pct is None else f"{self.take_profit_pct:g}"
  48. xtp = "none" if self.extreme_take_profit_pct is None else f"{self.extreme_take_profit_pct:g}"
  49. xband = "none" if self.extreme_band_extension is None else f"{self.extreme_band_extension:g}"
  50. tre = "none" if self.extreme_reentry_bars is None else str(self.extreme_reentry_bars)
  51. vol = "none" if self.eth_vol_cap is None else f"{self.eth_vol_cap:g}"
  52. dd = "none" if self.dd_overlay is None else f"{self.dd_overlay:g}"
  53. return (
  54. f"bb-squeeze-l{self.band_length}-bw{self.bandwidth_lookback}"
  55. f"-q{self.bandwidth_quantile:g}-sl{self.stop_loss_pct:g}-tp{tp}"
  56. f"-xtp{xtp}-xb{xband}-tre{tre}"
  57. f"-{self.side_mode}-{self.btc_filter}-vc{vol}-dd{dd}-cd{self.cooldown_bars}"
  58. )
  59. def _format_ts(ts: int) -> str:
  60. return pd.to_datetime(ts, unit="ms", utc=True).strftime("%Y-%m-%d %H:%M")
  61. def _load_candles(symbol: str, bar: str) -> list[Candle]:
  62. frame = pd.read_csv(DATA_DIR / symbol / f"{bar}.csv")
  63. return [
  64. Candle(
  65. symbol=symbol,
  66. ts=int(row.ts),
  67. open=float(row.open),
  68. high=float(row.high),
  69. low=float(row.low),
  70. close=float(row.close),
  71. volume=float(row.volume),
  72. )
  73. for row in frame.itertuples(index=False)
  74. ]
  75. def _align_pair(left: list[Candle], right: list[Candle]) -> tuple[list[Candle], list[Candle]]:
  76. right_by_ts = {candle.ts: candle for candle in right}
  77. left_out: list[Candle] = []
  78. right_out: list[Candle] = []
  79. for candle in left:
  80. other = right_by_ts.get(candle.ts)
  81. if other is not None:
  82. left_out.append(candle)
  83. right_out.append(other)
  84. return left_out, right_out
  85. def _close_position(
  86. *,
  87. trades: list[dict[str, object]],
  88. exits: list[dict[str, object]],
  89. position: dict[str, object],
  90. candle: Candle,
  91. exit_price: float,
  92. ) -> tuple[float, bool]:
  93. margin_used = float(position["margin_used"])
  94. exit_equity = trade_equity(
  95. side=str(position["side"]),
  96. margin_used=margin_used,
  97. entry_price=float(position["entry_price"]),
  98. exit_price=exit_price,
  99. leverage=LEVERAGE,
  100. )
  101. pnl = exit_equity - margin_used
  102. trades.append(
  103. {
  104. "side": "Long" if position["side"] == "long" else "Short",
  105. "entry_time": _format_ts(int(position["entry_time"])),
  106. "exit_time": _format_ts(candle.ts),
  107. "entry_price": round(float(position["entry_price"]), 4),
  108. "exit_price": round(exit_price, 4),
  109. "pnl": round(pnl, 4),
  110. "return_pct": round(pnl / margin_used * 100.0, 4),
  111. "cost_weight": 1.0,
  112. }
  113. )
  114. exits.append({"ts": candle.ts, "price": exit_price, "side": position["side"]})
  115. return exit_equity, pnl > 0.0
  116. def run_variant(eth: list[Candle], btc: list[Candle], variant: Variant) -> SegmentResult:
  117. eth_close = pd.Series([candle.close for candle in eth], dtype=float)
  118. btc_close = pd.Series([candle.close for candle in btc], dtype=float)
  119. middle_series = eth_close.rolling(variant.band_length).mean()
  120. stdev_series = eth_close.rolling(variant.band_length).std(ddof=0)
  121. upper = (middle_series + 2.0 * stdev_series).tolist()
  122. lower = (middle_series - 2.0 * stdev_series).tolist()
  123. middle = middle_series.tolist()
  124. bandwidth = ((pd.Series(upper) - pd.Series(lower)) / middle_series).tolist()
  125. threshold = pd.Series(bandwidth, dtype=float).rolling(variant.bandwidth_lookback).quantile(variant.bandwidth_quantile).tolist()
  126. btc_sma = btc_close.rolling(480).mean().tolist()
  127. btc_momentum = (btc_close / btc_close.shift(96) - 1.0).tolist()
  128. eth_realized_vol = eth_close.pct_change().rolling(96).std(ddof=0).tolist()
  129. warmup_bars = max(variant.band_length, variant.bandwidth_lookback, 480, 96)
  130. equity = INITIAL_EQUITY
  131. ending_equity = equity
  132. peak_equity = equity
  133. max_drawdown = 0.0
  134. wins = 0
  135. trades: list[dict[str, object]] = []
  136. entries: list[dict[str, object]] = []
  137. exits: list[dict[str, object]] = []
  138. equity_curve: list[dict[str, float | int]] = []
  139. position: dict[str, object] | None = None
  140. pending_entry_side: str | None = None
  141. pending_exit = False
  142. reentry_side: str | None = None
  143. reentry_until = -1
  144. cooldown_until = -1
  145. for index in range(warmup_bars, len(eth)):
  146. candle = eth[index]
  147. if pending_exit and position is not None:
  148. equity, won = _close_position(trades=trades, exits=exits, position=position, candle=candle, exit_price=candle.open)
  149. wins += int(won)
  150. position = None
  151. pending_exit = False
  152. cooldown_until = index + variant.cooldown_bars
  153. if pending_entry_side is not None and position is None and equity > 0.0:
  154. position = {
  155. "side": pending_entry_side,
  156. "entry_time": candle.ts,
  157. "entry_price": candle.open,
  158. "margin_used": equity,
  159. "stop_price": candle.open * (1.0 - variant.stop_loss_pct if pending_entry_side == "long" else 1.0 + variant.stop_loss_pct),
  160. "take_price": None
  161. if variant.take_profit_pct is None
  162. else candle.open * (1.0 + variant.take_profit_pct if pending_entry_side == "long" else 1.0 - variant.take_profit_pct),
  163. "extreme_take_price": None
  164. if variant.extreme_take_profit_pct is None
  165. else candle.open * (1.0 + variant.extreme_take_profit_pct if pending_entry_side == "long" else 1.0 - variant.extreme_take_profit_pct),
  166. }
  167. entries.append({"ts": candle.ts, "price": candle.open, "side": pending_entry_side})
  168. pending_entry_side = None
  169. current_equity = equity
  170. if position is not None:
  171. side = str(position["side"])
  172. stop_hit = (side == "long" and candle.low <= float(position["stop_price"])) or (
  173. side == "short" and candle.high >= float(position["stop_price"])
  174. )
  175. take_price = position["take_price"]
  176. take_hit = take_price is not None and (
  177. (side == "long" and candle.high >= float(take_price)) or (side == "short" and candle.low <= float(take_price))
  178. )
  179. extreme_take_price = position["extreme_take_price"]
  180. extreme_take_hit = extreme_take_price is not None and (
  181. (side == "long" and candle.high >= float(extreme_take_price)) or (
  182. side == "short" and candle.low <= float(extreme_take_price)
  183. )
  184. )
  185. if stop_hit or take_hit or extreme_take_hit:
  186. exit_side = side
  187. if stop_hit:
  188. exit_price = float(position["stop_price"])
  189. elif take_hit:
  190. exit_price = float(take_price)
  191. else:
  192. exit_price = float(extreme_take_price)
  193. equity, won = _close_position(trades=trades, exits=exits, position=position, candle=candle, exit_price=exit_price)
  194. wins += int(won)
  195. current_equity = equity
  196. position = None
  197. if extreme_take_hit and not stop_hit and not take_hit and variant.extreme_reentry_bars is not None:
  198. reentry_side = exit_side
  199. reentry_until = index + variant.extreme_reentry_bars
  200. else:
  201. cooldown_until = index + variant.cooldown_bars
  202. if position is not None:
  203. current_equity = mark_to_market(
  204. side=str(position["side"]),
  205. margin_used=float(position["margin_used"]),
  206. entry_price=float(position["entry_price"]),
  207. mark_price=candle.close,
  208. leverage=LEVERAGE,
  209. )
  210. peak_equity = max(peak_equity, current_equity)
  211. max_drawdown = max(max_drawdown, (peak_equity - current_equity) / peak_equity)
  212. equity_curve.append({"ts": candle.ts, "equity": current_equity, "close": candle.close})
  213. ending_equity = current_equity
  214. if index == len(eth) - 1 or equity <= 0.0:
  215. continue
  216. values = (middle[index], upper[index], lower[index], bandwidth[index], threshold[index])
  217. if any(value != value for value in values):
  218. continue
  219. if position is None and reentry_side is not None:
  220. if index > reentry_until:
  221. reentry_side = None
  222. elif (reentry_side == "long" and float(middle[index]) < candle.close <= float(upper[index])) or (
  223. reentry_side == "short" and float(lower[index]) <= candle.close < float(middle[index])
  224. ):
  225. pending_entry_side = reentry_side
  226. reentry_side = None
  227. continue
  228. if position is not None:
  229. middle_exit = (position["side"] == "long" and candle.close < float(middle[index])) or (
  230. position["side"] == "short" and candle.close > float(middle[index])
  231. )
  232. extreme_band_exit = False
  233. if variant.extreme_band_extension is not None:
  234. band_half_width = float(upper[index]) - float(middle[index])
  235. long_extreme = float(upper[index]) + band_half_width * variant.extreme_band_extension
  236. short_extreme = float(lower[index]) - band_half_width * variant.extreme_band_extension
  237. extreme_band_exit = (position["side"] == "long" and candle.close >= long_extreme) or (
  238. position["side"] == "short" and candle.close <= short_extreme
  239. )
  240. if middle_exit or extreme_band_exit:
  241. pending_exit = True
  242. continue
  243. if index < cooldown_until:
  244. continue
  245. if variant.eth_vol_cap is not None and float(eth_realized_vol[index]) > variant.eth_vol_cap:
  246. continue
  247. if variant.dd_overlay is not None and (peak_equity - current_equity) / peak_equity > variant.dd_overlay:
  248. continue
  249. if variant.btc_filter == "btc-up" and not (btc_close.iloc[index] > float(btc_sma[index])):
  250. continue
  251. if variant.btc_filter == "btc-up-momo" and not (btc_close.iloc[index] > float(btc_sma[index]) and float(btc_momentum[index]) > 0.0):
  252. continue
  253. if bandwidth[index] <= threshold[index]:
  254. if candle.close > float(upper[index]):
  255. pending_entry_side = "long"
  256. elif variant.side_mode == "both" and candle.close < float(lower[index]):
  257. pending_entry_side = "short"
  258. trade_count = len(trades)
  259. return SegmentResult(
  260. trade_count=trade_count,
  261. total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
  262. win_rate=wins / trade_count if trade_count else 0.0,
  263. max_drawdown=max_drawdown,
  264. trades=trades,
  265. open_position=position,
  266. candles=eth[warmup_bars:],
  267. equity_curve=equity_curve,
  268. entries=entries,
  269. exits=exits,
  270. )
  271. def cost_equity_frame(result: SegmentResult, cost: float) -> pd.DataFrame:
  272. rows = [{"ts": pd.to_datetime(result.equity_curve[0]["ts"], unit="ms", utc=True), "equity": INITIAL_EQUITY}]
  273. equity = INITIAL_EQUITY
  274. for trade in result.trades:
  275. equity *= 1.0 + float(trade["return_pct"]) / 100.0 - cost * float(trade.get("cost_weight", 1.0))
  276. rows.append({"ts": pd.to_datetime(str(trade["exit_time"]), utc=True), "equity": equity})
  277. return pd.DataFrame(rows)
  278. def max_drawdown(values: list[float]) -> float:
  279. peak = values[0]
  280. dd = 0.0
  281. for value in values:
  282. peak = max(peak, value)
  283. dd = max(dd, (peak - value) / peak if peak else 0.0)
  284. return dd
  285. def equity_metrics(frame: pd.DataFrame, first_ts: int, last_ts: int) -> dict[str, float]:
  286. years = (last_ts - first_ts) / 86_400_000 / 365
  287. total_return = float(frame["equity"].iloc[-1] / frame["equity"].iloc[0] - 1.0)
  288. annualized = (1.0 + total_return) ** (1.0 / years) - 1.0 if total_return > -1.0 and years > 0.0 else 0.0
  289. dd = max_drawdown([float(value) for value in frame["equity"]])
  290. return {
  291. "net_total_return": total_return,
  292. "net_annualized_return": annualized,
  293. "net_max_drawdown": dd,
  294. "net_calmar": annualized / dd if dd else 0.0,
  295. }
  296. def horizon_rows(frame: pd.DataFrame, last_ts: int) -> list[dict[str, object]]:
  297. rows: list[dict[str, object]] = []
  298. end_time = pd.to_datetime(last_ts, unit="ms", utc=True)
  299. for label, offset in HORIZONS:
  300. cutoff = end_time - offset
  301. before = frame[frame["ts"] <= cutoff]
  302. if len(before):
  303. start_equity = float(before["equity"].iloc[-1])
  304. start_time = cutoff
  305. after = frame[frame["ts"] > cutoff]
  306. horizon_frame = pd.concat([pd.DataFrame([{"ts": cutoff, "equity": start_equity}]), after[["ts", "equity"]]], ignore_index=True)
  307. else:
  308. horizon_frame = frame[["ts", "equity"]].copy()
  309. start_time = pd.Timestamp(horizon_frame["ts"].iloc[0])
  310. rows.append(
  311. {
  312. "horizon": label,
  313. "horizon_start": start_time.strftime("%Y-%m-%d %H:%M"),
  314. "horizon_end": end_time.strftime("%Y-%m-%d %H:%M"),
  315. **equity_metrics(horizon_frame, int(start_time.timestamp() * 1000), last_ts),
  316. }
  317. )
  318. return rows
  319. def worst_month(frame: pd.DataFrame) -> tuple[str, float]:
  320. monthly = frame.set_index("ts")["equity"].resample("ME").last().ffill().pct_change().dropna()
  321. if not len(monthly):
  322. return "", 0.0
  323. idx = monthly.idxmin()
  324. return idx.strftime("%Y-%m"), float(monthly.loc[idx])
  325. def build_variants() -> list[Variant]:
  326. bases = (
  327. (96, 480, 0.15),
  328. (96, 960, 0.25),
  329. (48, 960, 0.25),
  330. (48, 480, 0.15),
  331. )
  332. variants: list[Variant] = []
  333. for length, bandwidth_lookback, quantile in bases:
  334. for side_mode in ("long", "both"):
  335. for btc_filter in ("none", "btc-up", "btc-up-momo"):
  336. for eth_vol_cap in (None, 0.006):
  337. for dd_overlay in (None, 0.25):
  338. for stop_loss_pct, take_profit_pct in (
  339. (0.006, 0.012),
  340. (0.008, 0.018),
  341. (0.010, None),
  342. ):
  343. for extreme_take_profit_pct, extreme_band_extension, extreme_reentry_bars in (
  344. (None, None, None),
  345. (0.025, None, None),
  346. (0.035, None, None),
  347. (0.025, None, 96),
  348. (0.035, None, 96),
  349. (None, 0.75, None),
  350. (0.025, 0.75, None),
  351. ):
  352. variants.append(
  353. Variant(
  354. band_length=length,
  355. bandwidth_lookback=bandwidth_lookback,
  356. bandwidth_quantile=quantile,
  357. stop_loss_pct=stop_loss_pct,
  358. take_profit_pct=take_profit_pct,
  359. extreme_take_profit_pct=extreme_take_profit_pct,
  360. extreme_band_extension=extreme_band_extension,
  361. extreme_reentry_bars=extreme_reentry_bars,
  362. side_mode=side_mode,
  363. btc_filter=btc_filter,
  364. eth_vol_cap=eth_vol_cap,
  365. dd_overlay=dd_overlay,
  366. cooldown_bars=24,
  367. )
  368. )
  369. return variants
  370. def format_cell(value: object) -> str:
  371. if isinstance(value, float):
  372. return f"{value:.6g}"
  373. return str(value).replace("|", "\\|")
  374. def markdown_table(frame: pd.DataFrame) -> str:
  375. columns = list(frame.columns)
  376. rows = [columns, ["---" for _ in columns]]
  377. for record in frame.to_dict("records"):
  378. rows.append([record[column] for column in columns])
  379. return "\n".join("| " + " | ".join(format_cell(value) for value in row) + " |" for row in rows)
  380. def write_report(
  381. *,
  382. summary: pd.DataFrame,
  383. horizon: pd.DataFrame,
  384. output_files: list[Path],
  385. command: str,
  386. first_ts: int,
  387. last_ts: int,
  388. requested_years: float,
  389. ) -> str:
  390. primary = summary[summary["cost"] == PRIMARY_COST]
  391. top_calmar = primary.head(10)
  392. top_worst_month = primary.sort_values(
  393. ["worst_month_return", "net_calmar", "net_annualized_return"],
  394. ascending=[False, False, False],
  395. ).head(10)
  396. acceptable = primary[(primary["net_max_drawdown"] <= 0.45) & (primary["worst_month_return"] >= -0.25) & (primary["net_calmar"] > 1.0)]
  397. best = primary.iloc[0] if len(primary) else None
  398. horizon_top = (
  399. horizon[horizon["cost"] == PRIMARY_COST]
  400. .sort_values(["horizon", "net_calmar", "net_annualized_return"], ascending=[True, False, False])
  401. .groupby("horizon", observed=True)
  402. .head(3)
  403. )
  404. verdict = (
  405. "Yes: at least one variant met MDD <= 45%, worst month >= -25%, and Calmar > 1.0."
  406. if len(acceptable)
  407. else "No: this run did not find a BB squeeze variant with acceptable drawdown under MDD <= 45% and worst month >= -25%."
  408. )
  409. lines = [
  410. "# ETH BB squeeze breakout risk 10y exploration",
  411. "",
  412. f"Run command: `{command}`",
  413. f"Requested years: {requested_years:g}",
  414. f"Actual continuous local history: `{_format_ts(first_ts)}` to `{_format_ts(last_ts)}`.",
  415. "",
  416. "Output files:",
  417. *[f"- `{path}`" for path in output_files],
  418. "",
  419. "Cost model: maker_taker is the primary ranking cost; maker_maker and taker_taker are included for sensitivity.",
  420. "Objective: reduce drawdown, not maximize total return.",
  421. "",
  422. "Top 10 by Calmar:",
  423. markdown_table(
  424. top_calmar[
  425. [
  426. "name",
  427. "trades",
  428. "net_total_return",
  429. "net_annualized_return",
  430. "net_max_drawdown",
  431. "net_calmar",
  432. "worst_month",
  433. "worst_month_return",
  434. ]
  435. ]
  436. ),
  437. "",
  438. "Top 10 by worst month:",
  439. markdown_table(
  440. top_worst_month[
  441. [
  442. "name",
  443. "trades",
  444. "net_total_return",
  445. "net_annualized_return",
  446. "net_max_drawdown",
  447. "net_calmar",
  448. "worst_month",
  449. "worst_month_return",
  450. ]
  451. ]
  452. ),
  453. "",
  454. "Recent horizon leaders:",
  455. markdown_table(
  456. horizon_top[
  457. [
  458. "horizon",
  459. "name",
  460. "trades",
  461. "net_total_return",
  462. "net_annualized_return",
  463. "net_max_drawdown",
  464. "net_calmar",
  465. ]
  466. ]
  467. ),
  468. "",
  469. "Verdict:",
  470. f"- {verdict}",
  471. ]
  472. if best is not None:
  473. lines.append(
  474. f"- Best Calmar variant is `{best['name']}`: Calmar {format_cell(best['net_calmar'])}, MDD {format_cell(best['net_max_drawdown'])}, worst month {best['worst_month']} {format_cell(best['worst_month_return'])}, trades {best['trades']}."
  475. )
  476. if len(acceptable):
  477. lines.extend(
  478. [
  479. "",
  480. "Acceptable drawdown candidates:",
  481. markdown_table(
  482. acceptable.head(10)[
  483. [
  484. "name",
  485. "trades",
  486. "net_annualized_return",
  487. "net_max_drawdown",
  488. "net_calmar",
  489. "worst_month_return",
  490. ]
  491. ]
  492. ),
  493. ]
  494. )
  495. return "\n".join(lines) + "\n"
  496. def main() -> int:
  497. parser = argparse.ArgumentParser()
  498. parser.add_argument("--bar", default=BAR)
  499. parser.add_argument("--years", type=float, default=YEARS)
  500. parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
  501. args = parser.parse_args()
  502. eth = _load_candles(ETH_SYMBOL, args.bar)
  503. btc = _load_candles(BTC_SYMBOL, args.bar)
  504. eth, btc = _align_pair(eth, btc)
  505. requested_bars = int(args.years * 365 * 24 * 60 / 15)
  506. eth = eth[-requested_bars:]
  507. btc = btc[-requested_bars:]
  508. summary_rows: list[dict[str, object]] = []
  509. horizon_output_rows: list[dict[str, object]] = []
  510. variants = build_variants()
  511. for index, variant in enumerate(variants, start=1):
  512. result = run_variant(eth, btc, variant)
  513. if not result.equity_curve:
  514. print(f"skip {index}/{len(variants)} {variant.name}")
  515. continue
  516. for cost_name, cost in COSTS:
  517. frame = cost_equity_frame(result, cost)
  518. metrics = equity_metrics(frame, eth[0].ts, eth[-1].ts)
  519. month, month_return = worst_month(frame)
  520. row = {
  521. "family": "bb_squeeze_breakout_risk",
  522. "cost": cost_name,
  523. "symbol": ETH_SYMBOL,
  524. "signal_symbol": BTC_SYMBOL if variant.btc_filter != "none" else "",
  525. "bar": args.bar,
  526. "name": variant.name,
  527. "band_length": variant.band_length,
  528. "bandwidth_lookback": variant.bandwidth_lookback,
  529. "bandwidth_quantile": variant.bandwidth_quantile,
  530. "stop_loss_pct": variant.stop_loss_pct,
  531. "take_profit_pct": variant.take_profit_pct,
  532. "extreme_take_profit_pct": variant.extreme_take_profit_pct,
  533. "extreme_band_extension": variant.extreme_band_extension,
  534. "extreme_reentry_bars": variant.extreme_reentry_bars,
  535. "side_mode": variant.side_mode,
  536. "btc_filter": variant.btc_filter,
  537. "eth_vol_cap": variant.eth_vol_cap,
  538. "dd_overlay": variant.dd_overlay,
  539. "cooldown_bars": variant.cooldown_bars,
  540. "first_candle": _format_ts(eth[0].ts),
  541. "last_candle": _format_ts(eth[-1].ts),
  542. "years": (eth[-1].ts - eth[0].ts) / 86_400_000 / 365,
  543. "trades": result.trade_count,
  544. "gross_total_return": result.total_return,
  545. "gross_max_drawdown_mark_to_market": result.max_drawdown,
  546. "worst_month": month,
  547. "worst_month_return": month_return,
  548. **metrics,
  549. }
  550. summary_rows.append(row)
  551. for horizon_row in horizon_rows(frame, eth[-1].ts):
  552. horizon_output_rows.append(
  553. {
  554. "family": "bb_squeeze_breakout_risk",
  555. "cost": cost_name,
  556. "symbol": ETH_SYMBOL,
  557. "signal_symbol": BTC_SYMBOL if variant.btc_filter != "none" else "",
  558. "bar": args.bar,
  559. "name": variant.name,
  560. "trades": result.trade_count,
  561. **horizon_row,
  562. }
  563. )
  564. print(f"done {index}/{len(variants)} {variant.name}")
  565. summary = pd.DataFrame(summary_rows).sort_values(
  566. ["cost", "net_calmar", "worst_month_return", "net_annualized_return"],
  567. ascending=[True, False, False, False],
  568. )
  569. primary = summary[summary["cost"] == PRIMARY_COST]
  570. summary = pd.concat([primary, summary[summary["cost"] != PRIMARY_COST]], ignore_index=True)
  571. horizon = pd.DataFrame(horizon_output_rows)
  572. horizon["horizon"] = pd.Categorical(horizon["horizon"], categories=[label for label, _ in HORIZONS], ordered=True)
  573. horizon = horizon.sort_values(["cost", "horizon", "net_calmar", "net_annualized_return"], ascending=[True, True, False, False])
  574. args.output_dir.mkdir(parents=True, exist_ok=True)
  575. prefix = "eth-bb-squeeze-risk-10y"
  576. summary_path = args.output_dir / f"{prefix}-summary.csv"
  577. horizon_path = args.output_dir / f"{prefix}-horizon.csv"
  578. top_calmar_path = args.output_dir / f"{prefix}-top10-calmar.csv"
  579. top_worst_month_path = args.output_dir / f"{prefix}-top10-worst-month.csv"
  580. report_path = args.output_dir / f"{prefix}-report.md"
  581. output_files = [summary_path, horizon_path, top_calmar_path, top_worst_month_path, report_path]
  582. summary.to_csv(summary_path, index=False)
  583. horizon.to_csv(horizon_path, index=False)
  584. primary.head(10).to_csv(top_calmar_path, index=False)
  585. primary.sort_values(["worst_month_return", "net_calmar", "net_annualized_return"], ascending=[False, False, False]).head(10).to_csv(
  586. top_worst_month_path,
  587. index=False,
  588. )
  589. command = f"rtk .venv/bin/python {Path(__file__).as_posix()} --bar {args.bar} --years {args.years}"
  590. report_path.write_text(
  591. write_report(
  592. summary=summary,
  593. horizon=horizon,
  594. output_files=output_files,
  595. command=command,
  596. first_ts=eth[0].ts,
  597. last_ts=eth[-1].ts,
  598. requested_years=args.years,
  599. ),
  600. encoding="utf-8",
  601. )
  602. print(primary.head(10).to_string(index=False))
  603. return 0
  604. if __name__ == "__main__":
  605. raise SystemExit(main())