search_eth_twap_conservative_variants.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. from __future__ import annotations
  2. import argparse
  3. import multiprocessing
  4. import sys
  5. from concurrent.futures import ProcessPoolExecutor, as_completed
  6. from dataclasses import dataclass
  7. from itertools import product
  8. from pathlib import Path
  9. import pandas as pd
  10. ROOT = Path(__file__).resolve().parents[1]
  11. sys.path.insert(0, str(ROOT))
  12. from okx_codex_trader.models import Candle
  13. from okx_codex_trader.sampled_report import SegmentResult, mark_to_market
  14. from scripts.explore_ultrashort import (
  15. CANDLE_CACHE_DIR,
  16. INITIAL_EQUITY,
  17. LEVERAGE,
  18. _compute_rsi,
  19. _format_ts,
  20. annualized_metrics_from_equity,
  21. cost_adjusted_trade_equity_frame,
  22. history_bars_for_years,
  23. load_cached_candles,
  24. max_drawdown_from_equity,
  25. )
  26. SYMBOL = "ETH-USDT-SWAP"
  27. BAR = "15m"
  28. YEARS = 10.0
  29. MAX_HOLD_BARS = 48
  30. OUTPUT_DIR = Path("reports/eth-exploration")
  31. PREFIX = "eth-twap-conservative"
  32. COSTS = {
  33. "maker_maker": 0.0012,
  34. "maker_taker": 0.0021,
  35. "taker_taker": 0.0030,
  36. }
  37. HORIZONS = (
  38. ("3y", pd.DateOffset(years=3)),
  39. ("1y", pd.DateOffset(years=1)),
  40. ("6m", pd.DateOffset(months=6)),
  41. ("3m", pd.DateOffset(months=3)),
  42. )
  43. TREND_SMAS = (50, 60, 80, 120)
  44. RSI_THRESHOLDS = (2.0, 3.0, 4.0)
  45. EXIT_RSIS = (45.0, 50.0, 55.0)
  46. STOP_LOSSES = (0.010, 0.012, 0.015, 0.018)
  47. ENTRY_OFFSET_SETS = (
  48. (0.004, 0.008, 0.012),
  49. (0.005, 0.009, 0.013),
  50. (0.006, 0.010, 0.015),
  51. (0.005, 0.010),
  52. )
  53. ENTRY_VALID_BARS = (2, 3, 4)
  54. FILL_BUFFER = 0.001
  55. PRICE_SLIPPAGE = 0.0005
  56. MAKER_MISS_RATIO = 0.25
  57. CANDLES = None
  58. @dataclass(frozen=True)
  59. class ConservativeResult:
  60. result: SegmentResult
  61. missed_fills: int
  62. fill_attempts: int
  63. def init_worker(candles: list[Candle]) -> None:
  64. global CANDLES
  65. CANDLES = candles
  66. def offset_label(entry_offsets: tuple[float, ...]) -> str:
  67. return "-".join(f"{value:.4f}" for value in entry_offsets)
  68. def strategy_name(spec: dict[str, object]) -> str:
  69. return (
  70. f"rsi2-long-guarded-price-twap-o{offset_label(tuple(spec['entry_offsets']))}"
  71. f"-v{spec['entry_valid_bars']}-t{spec['trend_sma']}-l{spec['rsi_threshold']}"
  72. f"-x{spec['exit_rsi']}-sl{spec['stop_loss_pct']}-mh{MAX_HOLD_BARS}"
  73. f"-fb{FILL_BUFFER:.4f}-ps{PRICE_SLIPPAGE:.4f}-mm25"
  74. )
  75. def candidate_specs() -> list[dict[str, object]]:
  76. specs: list[dict[str, object]] = []
  77. for trend_sma, rsi_threshold, exit_rsi, stop_loss_pct, entry_offsets, entry_valid_bars in product(
  78. TREND_SMAS,
  79. RSI_THRESHOLDS,
  80. EXIT_RSIS,
  81. STOP_LOSSES,
  82. ENTRY_OFFSET_SETS,
  83. ENTRY_VALID_BARS,
  84. ):
  85. specs.append(
  86. {
  87. "trend_sma": trend_sma,
  88. "rsi_threshold": rsi_threshold,
  89. "exit_rsi": exit_rsi,
  90. "stop_loss_pct": stop_loss_pct,
  91. "max_hold_bars": MAX_HOLD_BARS,
  92. "entry_offsets": entry_offsets,
  93. "entry_valid_bars": entry_valid_bars,
  94. "fill_buffer": FILL_BUFFER,
  95. "price_slippage": PRICE_SLIPPAGE,
  96. "maker_miss_ratio": MAKER_MISS_RATIO,
  97. }
  98. )
  99. return specs
  100. def should_miss_fill(fill_attempt: int) -> bool:
  101. return fill_attempt % 4 == 0
  102. def close_position(
  103. *,
  104. trades: list[dict[str, object]],
  105. exits: list[dict[str, object]],
  106. position: dict[str, object],
  107. account_equity: float,
  108. candle: Candle,
  109. exit_price: float,
  110. ) -> tuple[float, bool]:
  111. margin_used = float(position["margin_used"])
  112. exit_equity = mark_to_market(
  113. side="long",
  114. margin_used=margin_used,
  115. entry_price=float(position["entry_price"]),
  116. mark_price=exit_price,
  117. leverage=LEVERAGE,
  118. )
  119. pnl = exit_equity - margin_used
  120. trades.append(
  121. {
  122. "side": "Long",
  123. "entry_time": _format_ts(int(position["entry_time"])),
  124. "exit_time": _format_ts(candle.ts),
  125. "entry_price": round(float(position["entry_price"]), 4),
  126. "exit_price": round(exit_price, 4),
  127. "pnl": round(pnl, 4),
  128. "return_pct": round(pnl / account_equity * 100, 4),
  129. "cost_weight": round(margin_used / account_equity, 8),
  130. }
  131. )
  132. exits.append({"ts": candle.ts, "price": exit_price, "side": "long"})
  133. return account_equity + pnl, pnl > 0.0
  134. def run_conservative_twap_segment(candles: list[Candle], spec: dict[str, object]) -> ConservativeResult:
  135. closes = pd.Series([candle.close for candle in candles], dtype=float)
  136. trend = closes.rolling(int(spec["trend_sma"])).mean().tolist()
  137. rsi_values = _compute_rsi(closes, 2)
  138. equity = INITIAL_EQUITY
  139. ending_equity = equity
  140. peak_equity = equity
  141. max_drawdown = 0.0
  142. wins = 0
  143. trades: list[dict[str, object]] = []
  144. entries: list[dict[str, object]] = []
  145. exits: list[dict[str, object]] = []
  146. equity_curve: list[dict[str, float | int]] = []
  147. position: dict[str, object] | None = None
  148. pending_limits: list[dict[str, float | int]] = []
  149. pending_exit = False
  150. warmup_bars = max(int(spec["trend_sma"]), 3)
  151. entry_offsets = tuple(float(value) for value in spec["entry_offsets"])
  152. fill_attempts = 0
  153. missed_fills = 0
  154. for index in range(warmup_bars, len(candles)):
  155. candle = candles[index]
  156. if pending_exit and position is not None:
  157. equity, won = close_position(
  158. trades=trades,
  159. exits=exits,
  160. position=position,
  161. account_equity=equity,
  162. candle=candle,
  163. exit_price=candle.open * (1.0 - PRICE_SLIPPAGE),
  164. )
  165. wins += 1 if won else 0
  166. position = None
  167. pending_exit = False
  168. pending_limits = []
  169. active_limits: list[dict[str, float | int]] = []
  170. for limit in pending_limits:
  171. if index > int(limit["expires_index"]):
  172. continue
  173. limit_price = float(limit["price"])
  174. if candle.low <= limit_price * (1.0 - FILL_BUFFER) and equity > 0.0:
  175. fill_attempts += 1
  176. if should_miss_fill(fill_attempts):
  177. missed_fills += 1
  178. continue
  179. slice_margin = equity / len(entry_offsets)
  180. actual_entry_price = limit_price * (1.0 + PRICE_SLIPPAGE)
  181. if position is None:
  182. position = {
  183. "side": "long",
  184. "entry_time": candle.ts,
  185. "entry_price": actual_entry_price,
  186. "entry_index": index,
  187. "margin_used": slice_margin,
  188. "stop_price": actual_entry_price * (1.0 - float(spec["stop_loss_pct"])),
  189. }
  190. else:
  191. old_margin = float(position["margin_used"])
  192. new_margin = old_margin + slice_margin
  193. entry_price = (float(position["entry_price"]) * old_margin + actual_entry_price * slice_margin) / new_margin
  194. position["entry_price"] = entry_price
  195. position["margin_used"] = new_margin
  196. position["stop_price"] = entry_price * (1.0 - float(spec["stop_loss_pct"]))
  197. entries.append({"ts": candle.ts, "price": actual_entry_price, "side": "long"})
  198. else:
  199. active_limits.append(limit)
  200. pending_limits = active_limits
  201. current_equity = equity
  202. if position is not None and candle.low <= float(position["stop_price"]):
  203. equity, won = close_position(
  204. trades=trades,
  205. exits=exits,
  206. position=position,
  207. account_equity=equity,
  208. candle=candle,
  209. exit_price=float(position["stop_price"]) * (1.0 - PRICE_SLIPPAGE),
  210. )
  211. wins += 1 if won else 0
  212. current_equity = equity
  213. position = None
  214. pending_limits = []
  215. if position is not None:
  216. position_equity = mark_to_market(
  217. side="long",
  218. margin_used=float(position["margin_used"]),
  219. entry_price=float(position["entry_price"]),
  220. mark_price=candle.close,
  221. leverage=LEVERAGE,
  222. )
  223. current_equity = equity - float(position["margin_used"]) + position_equity
  224. peak_equity = max(peak_equity, current_equity)
  225. max_drawdown = max(max_drawdown, (peak_equity - current_equity) / peak_equity)
  226. equity_curve.append({"ts": candle.ts, "equity": current_equity, "close": candle.close})
  227. ending_equity = current_equity
  228. if index == len(candles) - 1 or equity <= 0.0:
  229. continue
  230. current_rsi = rsi_values[index]
  231. current_trend = trend[index]
  232. if current_rsi != current_rsi or current_trend != current_trend:
  233. continue
  234. if position is not None:
  235. held_bars = index - int(position["entry_index"])
  236. if current_rsi >= float(spec["exit_rsi"]) or held_bars >= MAX_HOLD_BARS:
  237. pending_exit = True
  238. pending_limits = []
  239. continue
  240. if not pending_limits and candle.close > float(current_trend) and current_rsi <= float(spec["rsi_threshold"]):
  241. pending_limits = [
  242. {
  243. "price": candle.close * (1.0 - offset),
  244. "expires_index": index + int(spec["entry_valid_bars"]),
  245. }
  246. for offset in entry_offsets
  247. ]
  248. trade_count = len(trades)
  249. return ConservativeResult(
  250. result=SegmentResult(
  251. trade_count=trade_count,
  252. total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
  253. win_rate=(wins / trade_count) if trade_count else 0.0,
  254. max_drawdown=max_drawdown,
  255. trades=trades,
  256. open_position=position,
  257. candles=candles[warmup_bars:],
  258. equity_curve=equity_curve,
  259. entries=entries,
  260. exits=exits,
  261. ),
  262. missed_fills=missed_fills,
  263. fill_attempts=fill_attempts,
  264. )
  265. def horizon_metrics(frame: pd.DataFrame, last_ts: int) -> list[dict[str, object]]:
  266. rows: list[dict[str, object]] = []
  267. end_time = pd.to_datetime(last_ts, unit="ms", utc=True)
  268. for label, offset in HORIZONS:
  269. cutoff = end_time - offset
  270. before_cutoff = frame[frame["ts"] <= cutoff]
  271. if len(before_cutoff):
  272. start_equity = float(before_cutoff["equity"].iloc[-1])
  273. start_time = cutoff
  274. horizon_frame = pd.concat(
  275. [
  276. pd.DataFrame([{"ts": start_time, "equity": start_equity}]),
  277. frame[frame["ts"] > cutoff][["ts", "equity"]],
  278. ],
  279. ignore_index=True,
  280. )
  281. else:
  282. horizon_frame = frame[["ts", "equity"]].copy()
  283. start_time = pd.Timestamp(horizon_frame["ts"].iloc[0])
  284. rows.append(
  285. {
  286. "horizon": label,
  287. "horizon_start": start_time.strftime("%Y-%m-%d %H:%M"),
  288. "horizon_end": end_time.strftime("%Y-%m-%d %H:%M"),
  289. **annualized_metrics_from_equity(horizon_frame, int(start_time.timestamp() * 1000), last_ts),
  290. }
  291. )
  292. return rows
  293. def rolling_365_worst(frame: pd.DataFrame, last_ts: int) -> dict[str, object]:
  294. daily = frame.set_index("ts")["equity"].resample("1D").last().ffill().dropna()
  295. windows: list[dict[str, object]] = []
  296. for end_index in range(365, len(daily)):
  297. window = daily.iloc[end_index - 365 : end_index + 1]
  298. total_return = float(window.iloc[-1] / window.iloc[0] - 1.0)
  299. max_drawdown = max_drawdown_from_equity([float(value) for value in window])
  300. windows.append(
  301. {
  302. "worst_365_start": window.index[0].strftime("%Y-%m-%d"),
  303. "worst_365_end": window.index[-1].strftime("%Y-%m-%d"),
  304. "worst_365_total_return": total_return,
  305. "worst_365_max_drawdown": max_drawdown,
  306. }
  307. )
  308. worst = min(windows, key=lambda row: row["worst_365_total_return"])
  309. return {"sample_end": _format_ts(last_ts), **worst}
  310. def evaluate_spec(spec: dict[str, object]) -> tuple[list[dict[str, object]], list[dict[str, object]], list[dict[str, object]], str, int]:
  311. if CANDLES is None:
  312. raise RuntimeError("candles are not initialized")
  313. candles = CANDLES
  314. conservative = run_conservative_twap_segment(candles, spec)
  315. result = conservative.result
  316. gross_years = (candles[-1].ts - candles[0].ts) / 86_400_000 / 365
  317. gross_annualized = (1.0 + result.total_return) ** (1.0 / gross_years) - 1.0 if result.total_return > -1.0 else 0.0
  318. entry_offsets = tuple(float(value) for value in spec["entry_offsets"])
  319. name = strategy_name(spec)
  320. base_row = {
  321. "symbol": SYMBOL,
  322. "bar": BAR,
  323. "name": name,
  324. "first_candle": _format_ts(candles[0].ts),
  325. "last_candle": _format_ts(candles[-1].ts),
  326. "actual_bars": len(candles),
  327. "trades": result.trade_count,
  328. "fill_attempts": conservative.fill_attempts,
  329. "missed_fills": conservative.missed_fills,
  330. "actual_miss_ratio": conservative.missed_fills / conservative.fill_attempts if conservative.fill_attempts else 0.0,
  331. "gross_total_return": result.total_return,
  332. "gross_annualized_return": gross_annualized,
  333. "gross_max_drawdown_mark_to_market": result.max_drawdown,
  334. **spec,
  335. "entry_offsets": offset_label(entry_offsets),
  336. }
  337. total_rows: list[dict[str, object]] = []
  338. horizon_rows: list[dict[str, object]] = []
  339. rolling_rows: list[dict[str, object]] = []
  340. for cost_label, roundtrip_cost in COSTS.items():
  341. net_equity = cost_adjusted_trade_equity_frame(result, roundtrip_cost)
  342. cost_row = {
  343. **base_row,
  344. "cost_model": cost_label,
  345. "roundtrip_cost_on_margin": roundtrip_cost,
  346. }
  347. total_rows.append({**cost_row, **annualized_metrics_from_equity(net_equity, candles[0].ts, candles[-1].ts)})
  348. for horizon_row in horizon_metrics(net_equity, candles[-1].ts):
  349. horizon_rows.append({**cost_row, **horizon_row})
  350. rolling_rows.append({**cost_row, **rolling_365_worst(net_equity, candles[-1].ts)})
  351. return total_rows, horizon_rows, rolling_rows, name, result.trade_count
  352. def run_search(workers: int) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
  353. cached, _ = load_cached_candles(CANDLE_CACHE_DIR, SYMBOL, BAR)
  354. candles = cached[-history_bars_for_years(BAR, YEARS) :]
  355. specs = candidate_specs()
  356. total_rows: list[dict[str, object]] = []
  357. horizon_rows: list[dict[str, object]] = []
  358. rolling_rows: list[dict[str, object]] = []
  359. with ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context("fork"), initializer=init_worker, initargs=(candles,)) as executor:
  360. futures = [executor.submit(evaluate_spec, spec) for spec in specs]
  361. for index, future in enumerate(as_completed(futures), start=1):
  362. spec_totals, spec_horizons, spec_rolling, name, trade_count = future.result()
  363. total_rows.extend(spec_totals)
  364. horizon_rows.extend(spec_horizons)
  365. rolling_rows.extend(spec_rolling)
  366. print(f"{index}/{len(specs)} {name} trades={trade_count}", flush=True)
  367. totals = pd.DataFrame(total_rows)
  368. horizons = pd.DataFrame(horizon_rows)
  369. rolling = pd.DataFrame(rolling_rows)
  370. horizons["horizon"] = pd.Categorical(horizons["horizon"], categories=["3y", "1y", "6m", "3m"], ordered=True)
  371. ranked = rank_candidates(totals, horizons, rolling)
  372. totals = totals.sort_values(["cost_model", "net_calmar", "net_annualized_return"], ascending=[True, False, False])
  373. horizons = horizons.sort_values(["cost_model", "horizon", "net_calmar", "net_annualized_return"], ascending=[True, True, False, False])
  374. rolling = rolling.sort_values(["cost_model", "worst_365_total_return"], ascending=[True, False])
  375. return totals, horizons, rolling, ranked
  376. def rank_candidates(totals: pd.DataFrame, horizons: pd.DataFrame, rolling: pd.DataFrame) -> pd.DataFrame:
  377. key_columns = ["name"]
  378. maker_totals = totals[totals["cost_model"] == "maker_taker"].copy()
  379. horizon_pivot = horizons[horizons["cost_model"] == "maker_taker"].pivot_table(
  380. index=key_columns,
  381. columns="horizon",
  382. values=["net_total_return", "net_annualized_return", "net_max_drawdown", "net_calmar"],
  383. aggfunc="first",
  384. observed=False,
  385. )
  386. horizon_pivot.columns = [f"{metric}_{horizon}" for metric, horizon in horizon_pivot.columns]
  387. maker_rolling = rolling[rolling["cost_model"] == "maker_taker"][
  388. key_columns + ["worst_365_start", "worst_365_end", "worst_365_total_return", "worst_365_max_drawdown"]
  389. ]
  390. ranked = maker_totals.merge(horizon_pivot.reset_index(), on=key_columns).merge(maker_rolling, on=key_columns)
  391. ranked["all_horizons_positive"] = ranked[
  392. ["net_total_return_3y", "net_total_return_1y", "net_total_return_6m", "net_total_return_3m"]
  393. ].min(axis=1) > 0.0
  394. ranked["rolling_365_pass"] = ranked["worst_365_total_return"] >= -0.05
  395. ranked["qualified"] = ranked["all_horizons_positive"] & ranked["rolling_365_pass"]
  396. ranked["max_horizon_drawdown"] = ranked[
  397. ["net_max_drawdown_3y", "net_max_drawdown_1y", "net_max_drawdown_6m", "net_max_drawdown_3m"]
  398. ].max(axis=1)
  399. ranked["min_horizon_total_return"] = ranked[
  400. ["net_total_return_3y", "net_total_return_1y", "net_total_return_6m", "net_total_return_3m"]
  401. ].min(axis=1)
  402. ranked = ranked.sort_values(
  403. [
  404. "qualified",
  405. "all_horizons_positive",
  406. "rolling_365_pass",
  407. "min_horizon_total_return",
  408. "net_max_drawdown",
  409. "max_horizon_drawdown",
  410. "worst_365_max_drawdown",
  411. "worst_365_total_return",
  412. "net_annualized_return",
  413. ],
  414. ascending=[False, False, False, False, True, True, True, False, False],
  415. )
  416. return ranked
  417. def markdown_table(frame: pd.DataFrame, columns: list[str]) -> str:
  418. rows = [["" if pd.isna(value) else str(value) for value in row] for row in frame[columns].itertuples(index=False, name=None)]
  419. return "\n".join(
  420. [
  421. "| " + " | ".join(columns) + " |",
  422. "| " + " | ".join("---" for _ in columns) + " |",
  423. *["| " + " | ".join(row) + " |" for row in rows],
  424. ]
  425. )
  426. def markdown_summary(totals: pd.DataFrame, horizons: pd.DataFrame, rolling: pd.DataFrame, ranked: pd.DataFrame) -> str:
  427. qualified = ranked[ranked["qualified"]].copy()
  428. top = qualified.head(10) if len(qualified) else ranked.head(10)
  429. top_names = set(top["name"])
  430. horizon_top = horizons[(horizons["cost_model"] == "maker_taker") & (horizons["name"].isin(top_names))].sort_values(["name", "horizon"])
  431. rolling_top = rolling[(rolling["cost_model"] == "maker_taker") & (rolling["name"].isin(top_names))].sort_values("name")
  432. if len(qualified):
  433. best = qualified.iloc[0]
  434. decision = (
  435. f"Found {len(qualified)} qualified maker_taker candidates. Top candidate `{best['name']}`: "
  436. f"10y annualized={float(best['net_annualized_return']):.4f}, 10y maxDD={float(best['net_max_drawdown']):.4f}, "
  437. f"worst rolling365={float(best['worst_365_total_return']):.4f}, max horizon DD={float(best['max_horizon_drawdown']):.4f}."
  438. )
  439. else:
  440. all_horizon_count = int(ranked["all_horizons_positive"].sum())
  441. rolling_count = int(ranked["rolling_365_pass"].sum())
  442. best = ranked.iloc[0]
  443. decision = (
  444. "No maker_taker candidate met both requirements: 3y/1y/6m/3m all positive and worst rolling365 >= -5%. "
  445. f"Counts: all-horizon-positive={all_horizon_count}, rolling365-pass={rolling_count}. "
  446. f"Nearest miss `{best['name']}` has min horizon total return={float(best['min_horizon_total_return']):.4f}, "
  447. f"worst rolling365={float(best['worst_365_total_return']):.4f}, 10y maxDD={float(best['net_max_drawdown']):.4f}."
  448. )
  449. return "\n".join(
  450. [
  451. "# ETH TWAP Conservative Variant Search",
  452. "",
  453. "Scope: continuous 10y ETH 15m backtest, sliced into 3y/1y/6m/3m from one equity curve.",
  454. "",
  455. "Fixed conservative fill scenario: fill_buffer=0.001, price_slippage=0.0005 on entries/exits, deterministic maker_miss=25% by skipping every fourth fill attempt.",
  456. "",
  457. "Grid: trend 50/60/80/120; rsi 2/3/4; exit 45/50/55; stop 0.010/0.012/0.015/0.018; offsets 0.004/0.008/0.012, 0.005/0.009/0.013, 0.006/0.010/0.015, and 2-slice 0.005/0.010; valid 2/3/4.",
  458. "",
  459. f"Decision: {decision}",
  460. "",
  461. "## Top maker_taker candidates",
  462. "",
  463. markdown_table(
  464. top,
  465. [
  466. "qualified",
  467. "name",
  468. "trades",
  469. "fill_attempts",
  470. "missed_fills",
  471. "actual_miss_ratio",
  472. "trend_sma",
  473. "rsi_threshold",
  474. "exit_rsi",
  475. "stop_loss_pct",
  476. "entry_offsets",
  477. "entry_valid_bars",
  478. "net_annualized_return",
  479. "net_max_drawdown",
  480. "net_calmar",
  481. "min_horizon_total_return",
  482. "max_horizon_drawdown",
  483. "worst_365_start",
  484. "worst_365_end",
  485. "worst_365_total_return",
  486. "worst_365_max_drawdown",
  487. ],
  488. ),
  489. "",
  490. "## Top maker_taker horizons",
  491. "",
  492. markdown_table(
  493. horizon_top,
  494. [
  495. "name",
  496. "horizon",
  497. "net_total_return",
  498. "net_annualized_return",
  499. "net_max_drawdown",
  500. "net_calmar",
  501. ],
  502. ),
  503. "",
  504. "## Top maker_taker rolling365",
  505. "",
  506. markdown_table(
  507. rolling_top,
  508. [
  509. "name",
  510. "worst_365_start",
  511. "worst_365_end",
  512. "worst_365_total_return",
  513. "worst_365_max_drawdown",
  514. ],
  515. ),
  516. "",
  517. ]
  518. )
  519. def main() -> int:
  520. parser = argparse.ArgumentParser()
  521. parser.add_argument("--workers", type=int, default=6)
  522. args = parser.parse_args()
  523. OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
  524. totals, horizons, rolling, ranked = run_search(args.workers)
  525. totals_path = OUTPUT_DIR / f"{PREFIX}-totals.csv"
  526. horizons_path = OUTPUT_DIR / f"{PREFIX}-horizons.csv"
  527. rolling_path = OUTPUT_DIR / f"{PREFIX}-rolling365.csv"
  528. ranked_path = OUTPUT_DIR / f"{PREFIX}-ranked.csv"
  529. summary_path = OUTPUT_DIR / f"{PREFIX}-summary.md"
  530. totals.to_csv(totals_path, index=False)
  531. horizons.to_csv(horizons_path, index=False)
  532. rolling.to_csv(rolling_path, index=False)
  533. ranked.to_csv(ranked_path, index=False)
  534. summary_path.write_text(markdown_summary(totals, horizons, rolling, ranked), encoding="utf-8")
  535. print(f"wrote {totals_path}")
  536. print(f"wrote {horizons_path}")
  537. print(f"wrote {rolling_path}")
  538. print(f"wrote {ranked_path}")
  539. print(f"wrote {summary_path}")
  540. print(ranked.head(10).to_string(index=False))
  541. return 0
  542. if __name__ == "__main__":
  543. raise SystemExit(main())