search_eth_robust_twap_fill_slippage.py 24 KB

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