search_eth_high_freq_short_bidir_candidates.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. from __future__ import annotations
  2. import argparse
  3. import json
  4. from dataclasses import dataclass
  5. from pathlib import Path
  6. import pandas as pd
  7. DATA_DIR = Path("data/okx-candles")
  8. OUT_DIR = Path("reports/ultrashort")
  9. SYMBOL = "ETH-USDT-SWAP"
  10. INITIAL_EQUITY = 10_000.0
  11. LEVERAGE = 3.0
  12. TAKER_FEE = 0.0004
  13. HORIZONS = (
  14. ("full", None),
  15. ("3y", pd.DateOffset(years=3)),
  16. ("1y", pd.DateOffset(years=1)),
  17. ("3m", pd.DateOffset(months=3)),
  18. ("1m", pd.DateOffset(months=1)),
  19. ("2w", pd.DateOffset(weeks=2)),
  20. )
  21. @dataclass(frozen=True)
  22. class Candidate:
  23. family: str
  24. bar: str
  25. params: dict[str, float | int | str]
  26. @property
  27. def name(self) -> str:
  28. body = "-".join(f"{key}{value:g}" if isinstance(value, float) else f"{key}{value}" for key, value in self.params.items())
  29. return f"{self.family}-{self.bar}-{body}"
  30. def load_frame(bar: str, years: float) -> pd.DataFrame:
  31. frame = pd.read_csv(DATA_DIR / SYMBOL / f"{bar}.csv")
  32. frame["dt"] = pd.to_datetime(frame["ts"], unit="ms", utc=True)
  33. frame = frame.sort_values("ts").drop_duplicates("ts", keep="last")
  34. cutoff = frame["dt"].iloc[-1] - pd.DateOffset(days=int(years * 365))
  35. return frame[frame["dt"] >= cutoff].reset_index(drop=True)
  36. def rsi(close: pd.Series, length: int) -> pd.Series:
  37. delta = close.diff()
  38. gain = delta.clip(lower=0.0).rolling(length).mean()
  39. loss = (-delta.clip(upper=0.0)).rolling(length).mean()
  40. return 100.0 - 100.0 / (1.0 + gain / loss)
  41. def build_candidates(bars: list[str]) -> list[Candidate]:
  42. candidates: list[Candidate] = []
  43. for bar in bars:
  44. for window in (48, 96):
  45. for entry_z in (1.5,):
  46. for hold in (12,):
  47. base = {"window": window, "entry_z": entry_z, "exit_z": 0.20, "stop": 0.006, "take": 0.009, "hold": hold}
  48. candidates.append(Candidate("vwap_bidir", bar, base))
  49. candidates.append(Candidate("vwap_short", bar, base))
  50. for trend in (96, 192):
  51. for entry in (90,):
  52. for hold in (12,):
  53. candidates.append(
  54. Candidate(
  55. "rsi_short",
  56. bar,
  57. {"trend": trend, "entry": entry, "exit": 45, "stop": 0.0075, "take": 0.010, "hold": hold},
  58. )
  59. )
  60. for entry in (10,):
  61. for hold in (12,):
  62. candidates.append(
  63. Candidate(
  64. "rsi_bidir",
  65. bar,
  66. {"trend": trend, "entry": entry, "exit": 55, "stop": 0.0075, "take": 0.010, "hold": hold},
  67. )
  68. )
  69. for lookback in (48, 96):
  70. for hold in (12,):
  71. candidates.append(
  72. Candidate(
  73. "breakdown_short",
  74. bar,
  75. {"lookback": lookback, "stop": 0.006, "take": 0.012, "hold": hold},
  76. )
  77. )
  78. return candidates
  79. def signal_columns(frame: pd.DataFrame, candidate: Candidate) -> tuple[pd.Series, pd.Series]:
  80. close = frame["close"]
  81. false = pd.Series(False, index=frame.index)
  82. params = candidate.params
  83. if candidate.family in ("vwap_bidir", "vwap_short"):
  84. window = int(params["window"])
  85. volume = frame["volume"]
  86. vwap = (close * volume).rolling(window).sum() / volume.rolling(window).sum()
  87. stdev = close.rolling(window).std(ddof=0)
  88. zscore = (close - vwap) / stdev
  89. short_entry = zscore >= float(params["entry_z"])
  90. long_entry = zscore <= -float(params["entry_z"])
  91. entry = pd.Series("", index=frame.index, dtype=object)
  92. entry.loc[short_entry] = "short"
  93. if candidate.family == "vwap_bidir":
  94. entry.loc[long_entry] = "long"
  95. exit_ = (zscore.abs() <= float(params["exit_z"]))
  96. return entry, exit_
  97. if candidate.family in ("rsi_short", "rsi_bidir"):
  98. trend = close.rolling(int(params["trend"])).mean()
  99. value = rsi(close, 2)
  100. entry = pd.Series("", index=frame.index, dtype=object)
  101. entry.loc[(close < trend) & (value >= float(params["entry"]))] = "short"
  102. if candidate.family == "rsi_bidir":
  103. entry.loc[(close > trend) & (value <= float(params["entry"]))] = "long"
  104. exit_ = (value <= 100.0 - float(params["exit"])) | (value >= float(params["exit"]))
  105. return entry, exit_
  106. lookback = int(params["lookback"])
  107. prior_low = frame["low"].shift(1).rolling(lookback).min()
  108. entry = pd.Series("", index=frame.index, dtype=object)
  109. entry.loc[close < prior_low] = "short"
  110. return entry, false
  111. def close_return(side: str, entry: float, exit_price: float) -> float:
  112. price_return = exit_price / entry - 1.0 if side == "long" else entry / exit_price - 1.0
  113. return LEVERAGE * price_return - LEVERAGE * TAKER_FEE * (1.0 + exit_price / entry)
  114. def mark_return(side: str, entry: float, close: float) -> float:
  115. price_return = close / entry - 1.0 if side == "long" else entry / close - 1.0
  116. return LEVERAGE * price_return - LEVERAGE * TAKER_FEE
  117. def backtest(frame: pd.DataFrame, candidate: Candidate) -> tuple[pd.Series, pd.DataFrame]:
  118. entry_signal, exit_signal = signal_columns(frame, candidate)
  119. warmup = max(int(value) for key, value in candidate.params.items() if key in {"window", "trend", "lookback"}) + 2
  120. equity = INITIAL_EQUITY
  121. position: dict[str, object] | None = None
  122. pending_entry = ""
  123. pending_exit = False
  124. curve: list[tuple[pd.Timestamp, float]] = []
  125. trades: list[dict[str, object]] = []
  126. rows = list(frame.itertuples(index=False))
  127. for index in range(warmup, len(rows)):
  128. candle = rows[index]
  129. if pending_exit and position is not None:
  130. net = close_return(str(position["side"]), float(position["entry"]), float(candle.open))
  131. equity *= 1.0 + net
  132. trades.append({"entry_time": position["entry_time"], "exit_time": candle.dt, "side": position["side"], "return": net})
  133. position = None
  134. pending_exit = False
  135. if pending_entry and position is None and equity > 0.0:
  136. position = {"side": pending_entry, "entry": float(candle.open), "entry_index": index, "entry_time": candle.dt}
  137. pending_entry = ""
  138. mark = equity
  139. if position is not None:
  140. side = str(position["side"])
  141. entry = float(position["entry"])
  142. stop = float(candidate.params["stop"])
  143. take = float(candidate.params["take"])
  144. stop_price = entry * (1.0 - stop if side == "long" else 1.0 + stop)
  145. take_price = entry * (1.0 + take if side == "long" else 1.0 - take)
  146. stop_hit = candle.low <= stop_price if side == "long" else candle.high >= stop_price
  147. take_hit = candle.high >= take_price if side == "long" else candle.low <= take_price
  148. if stop_hit or take_hit:
  149. exit_price = stop_price if stop_hit else take_price
  150. net = close_return(side, entry, exit_price)
  151. equity *= 1.0 + net
  152. trades.append({"entry_time": position["entry_time"], "exit_time": candle.dt, "side": side, "return": net})
  153. position = None
  154. mark = equity
  155. else:
  156. mark = equity * (1.0 + mark_return(side, entry, float(candle.close)))
  157. curve.append((candle.dt, mark))
  158. if index == len(rows) - 1 or equity <= 0.0:
  159. continue
  160. next_entry = str(entry_signal.iloc[index])
  161. if position is not None:
  162. reverse = bool(next_entry) and next_entry != position["side"]
  163. stale = index - int(position["entry_index"]) >= int(candidate.params["hold"])
  164. if bool(exit_signal.iloc[index]) or reverse or stale:
  165. pending_exit = True
  166. pending_entry = next_entry if reverse else ""
  167. elif next_entry:
  168. pending_entry = next_entry
  169. if position is not None:
  170. final = rows[-1]
  171. net = close_return(str(position["side"]), float(position["entry"]), float(final.close))
  172. equity *= 1.0 + net
  173. trades.append({"entry_time": position["entry_time"], "exit_time": final.dt, "side": position["side"], "return": net})
  174. curve.append((final.dt, equity))
  175. return pd.Series(dict(curve)).sort_index(), pd.DataFrame(trades)
  176. def scoped(equity: pd.Series, trades: pd.DataFrame, offset: pd.DateOffset | None) -> tuple[pd.Series, pd.DataFrame]:
  177. if offset is None:
  178. return equity, trades
  179. start = equity.index[-1] - offset
  180. scoped_equity = equity[equity.index >= start]
  181. if len(scoped_equity) < 2:
  182. scoped_equity = equity
  183. scoped_trades = trades[trades["entry_time"] >= scoped_equity.index[0]] if len(trades) else trades
  184. return scoped_equity, scoped_trades
  185. def metrics(equity: pd.Series, trades: pd.DataFrame) -> dict[str, float | int]:
  186. total = float(equity.iloc[-1] / equity.iloc[0] - 1.0)
  187. years = (equity.index[-1] - equity.index[0]).total_seconds() / 31_536_000
  188. annual = (1.0 + total) ** (1.0 / years) - 1.0 if total > -1.0 and years > 0 else 0.0
  189. drawdown = float(((equity.cummax() - equity) / equity.cummax()).max())
  190. returns = trades["return"] if len(trades) else pd.Series(dtype=float)
  191. wins = returns[returns > 0.0]
  192. losses = returns[returns < 0.0]
  193. return {
  194. "total_return": total,
  195. "annualized_return": annual,
  196. "max_drawdown": drawdown,
  197. "calmar": annual / drawdown if drawdown else 0.0,
  198. "trades": int(len(trades)),
  199. "short_trades": int((trades["side"] == "short").sum()) if len(trades) else 0,
  200. "long_trades": int((trades["side"] == "long").sum()) if len(trades) else 0,
  201. "profit_factor": float(wins.sum() / abs(losses.sum())) if len(losses) else (999.0 if len(wins) else 0.0),
  202. "win_rate": float(len(wins) / len(returns)) if len(returns) else 0.0,
  203. }
  204. def summarize(candidate: Candidate, equity: pd.Series, trades: pd.DataFrame) -> dict[str, object]:
  205. row: dict[str, object] = {
  206. "symbol": SYMBOL,
  207. "bar": candidate.bar,
  208. "family": candidate.family,
  209. "name": candidate.name,
  210. "params_json": json.dumps(candidate.params, separators=(",", ":")),
  211. "first_time": equity.index[0].strftime("%Y-%m-%d %H:%M"),
  212. "last_time": equity.index[-1].strftime("%Y-%m-%d %H:%M"),
  213. }
  214. for label, offset in HORIZONS:
  215. part_equity, part_trades = scoped(equity, trades, offset)
  216. for key, value in metrics(part_equity, part_trades).items():
  217. row[f"{label}_{key}"] = value
  218. row["recent_trigger_score"] = int(row["3m_trades"]) + int(row["1m_trades"]) * 2 + int(row["2w_trades"]) * 4
  219. observe = (
  220. int(row["3m_trades"]) >= 12
  221. and int(row["1m_trades"]) >= 4
  222. and int(row["2w_trades"]) >= 1
  223. and float(row["3y_total_return"]) > 0.0
  224. and float(row["1y_total_return"]) > 0.0
  225. and float(row["3y_max_drawdown"]) <= 0.35
  226. and float(row["1y_max_drawdown"]) <= 0.25
  227. )
  228. row["readonly_observe"] = "yes" if observe else "no"
  229. return row
  230. def markdown_table(frame: pd.DataFrame) -> str:
  231. def cell(value: object) -> str:
  232. if isinstance(value, float):
  233. return f"{value:.4f}"
  234. return str(value).replace("|", "\\|")
  235. rows = [list(frame.columns), ["---" for _ in frame.columns]]
  236. rows.extend(frame.astype(object).where(pd.notna(frame), "").values.tolist())
  237. return "\n".join("| " + " | ".join(cell(value) for value in row) + " |" for row in rows)
  238. def write_report(totals: pd.DataFrame, paths: list[Path], command: str) -> str:
  239. selected = totals[totals["readonly_observe"] == "yes"].head(12)
  240. recent = totals.sort_values(["recent_trigger_score", "3y_calmar", "1y_calmar"], ascending=[False, False, False]).head(12)
  241. least_bad = totals.sort_values(
  242. ["3y_total_return", "1y_total_return", "3m_total_return", "3m_trades"],
  243. ascending=[False, False, False, False],
  244. ).head(12)
  245. cols = [
  246. "family",
  247. "bar",
  248. "name",
  249. "full_total_return",
  250. "full_max_drawdown",
  251. "full_trades",
  252. "3y_total_return",
  253. "3y_max_drawdown",
  254. "3y_trades",
  255. "1y_total_return",
  256. "1y_max_drawdown",
  257. "1y_trades",
  258. "3m_trades",
  259. "1m_trades",
  260. "2w_trades",
  261. "readonly_observe",
  262. ]
  263. return "\n".join(
  264. [
  265. "# ETH high-frequency short/bidirectional candidate search",
  266. "",
  267. f"Run command: `{command}`",
  268. "Scope: local OKX ETH candle CSV only; no live executor, deployment, private API, or order path touched.",
  269. f"Cost model: taker fee `{TAKER_FEE}` each side on `{LEVERAGE:g}x` notional; entries execute on next open.",
  270. "",
  271. "Output files:",
  272. *[f"- `{path}`" for path in paths],
  273. "",
  274. "Selection rule for `readonly_observe`: 3m >= 12 trades, 1m >= 4 trades, 2w >= 1 trade, positive 3y/1y return, 3y MDD <= 35%, 1y MDD <= 25%.",
  275. "",
  276. "## Read-only observation candidates",
  277. "",
  278. markdown_table(selected[cols]) if len(selected) else "No candidates passed the read-only observation rule.",
  279. "",
  280. "## Least-bad risk rows",
  281. "",
  282. markdown_table(least_bad[cols]),
  283. "",
  284. "## Most recently active candidates",
  285. "",
  286. markdown_table(recent[cols]),
  287. ]
  288. ) + "\n"
  289. def main() -> int:
  290. parser = argparse.ArgumentParser()
  291. parser.add_argument("--bars", nargs="+", default=["3m", "5m", "15m"])
  292. parser.add_argument("--output-dir", type=Path, default=OUT_DIR)
  293. parser.add_argument("--years", type=float, default=3.0)
  294. args = parser.parse_args()
  295. rows: list[dict[str, object]] = []
  296. frames = {bar: load_frame(bar, args.years) for bar in args.bars}
  297. for candidate in build_candidates(args.bars):
  298. equity, trades = backtest(frames[candidate.bar], candidate)
  299. if len(equity) < 2:
  300. continue
  301. rows.append(summarize(candidate, equity, trades))
  302. totals = pd.DataFrame(rows).sort_values(
  303. ["readonly_observe", "3m_trades", "1m_trades", "2w_trades", "3y_calmar", "1y_calmar"],
  304. ascending=[False, False, False, False, False, False],
  305. )
  306. args.output_dir.mkdir(parents=True, exist_ok=True)
  307. totals_path = args.output_dir / "eth-highfreq-short-bidir-candidates.csv"
  308. top_path = args.output_dir / "eth-highfreq-short-bidir-top.csv"
  309. report_path = args.output_dir / "eth-highfreq-short-bidir-report.md"
  310. paths = [totals_path, top_path, report_path]
  311. totals.to_csv(totals_path, index=False)
  312. totals.head(50).to_csv(top_path, index=False)
  313. command = f"rtk .venv/bin/python {Path(__file__).as_posix()} --bars {' '.join(args.bars)} --years {args.years:g}"
  314. report_path.write_text(write_report(totals, paths, command), encoding="utf-8")
  315. print(totals.head(20).to_string(index=False))
  316. return 0
  317. if __name__ == "__main__":
  318. raise SystemExit(main())