search_t_overlay_other_strategies.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. @dataclass(frozen=True)
  25. class StrategySpec:
  26. family: str
  27. symbol: str
  28. signal_symbol: str
  29. name: str
  30. params: dict[str, float | int | str]
  31. reentry_bars: int
  32. reentry_pullback_pct: float
  33. def _format_ts(ts: int) -> str:
  34. return pd.to_datetime(ts, unit="ms", utc=True).strftime("%Y-%m-%d %H:%M")
  35. def _load_candles(symbol: str, bar: str) -> list[Candle]:
  36. frame = pd.read_csv(DATA_DIR / symbol / f"{bar}.csv")
  37. return [
  38. Candle(symbol=symbol, ts=int(row.ts), open=float(row.open), high=float(row.high), low=float(row.low), close=float(row.close), volume=float(row.volume))
  39. for row in frame.itertuples(index=False)
  40. ]
  41. def _align_pair(left: list[Candle], right: list[Candle]) -> tuple[list[Candle], list[Candle]]:
  42. right_by_ts = {candle.ts: candle for candle in right}
  43. left_out: list[Candle] = []
  44. right_out: list[Candle] = []
  45. for candle in left:
  46. other = right_by_ts.get(candle.ts)
  47. if other is not None:
  48. left_out.append(candle)
  49. right_out.append(other)
  50. return left_out, right_out
  51. def _close_trade(trades: list[dict[str, object]], exits: list[dict[str, object]], position: dict[str, object], candle: Candle, exit_price: float, reason: str) -> tuple[float, bool]:
  52. margin_used = float(position["margin_used"])
  53. exit_equity = trade_equity(
  54. side=str(position["side"]),
  55. margin_used=margin_used,
  56. entry_price=float(position["entry_price"]),
  57. exit_price=exit_price,
  58. leverage=LEVERAGE,
  59. )
  60. pnl = exit_equity - margin_used
  61. trades.append(
  62. {
  63. "side": "Long" if position["side"] == "long" else "Short",
  64. "entry_time": _format_ts(int(position["entry_time"])),
  65. "exit_time": _format_ts(candle.ts),
  66. "entry_price": round(float(position["entry_price"]), 4),
  67. "exit_price": round(exit_price, 4),
  68. "pnl": round(pnl, 4),
  69. "return_pct": round(pnl / margin_used * 100.0, 4),
  70. "cost_weight": 1.0,
  71. "entry_kind": position["entry_kind"],
  72. "exit_reason": reason,
  73. }
  74. )
  75. exits.append({"ts": candle.ts, "price": exit_price, "side": position["side"]})
  76. return exit_equity, pnl > 0.0
  77. def rsi(series: pd.Series, length: int) -> pd.Series:
  78. delta = series.diff()
  79. gain = delta.clip(lower=0.0).ewm(alpha=1 / length, adjust=False).mean()
  80. loss = (-delta.clip(upper=0.0)).ewm(alpha=1 / length, adjust=False).mean()
  81. rs = gain / loss.replace(0.0, pd.NA)
  82. return 100.0 - (100.0 / (1.0 + rs))
  83. def true_range(frame: pd.DataFrame) -> pd.Series:
  84. high = frame["high"]
  85. low = frame["low"]
  86. close = frame["close"]
  87. return pd.concat([high - low, (high - close.shift(1)).abs(), (low - close.shift(1)).abs()], axis=1).max(axis=1)
  88. def build_signals(spec: StrategySpec, frame: pd.DataFrame) -> tuple[pd.Series, pd.Series]:
  89. close = frame["close"]
  90. open_ = frame["open"]
  91. high = frame["high"]
  92. low = frame["low"]
  93. p = spec.params
  94. if spec.family == "range_momentum":
  95. lookback = int(p["lookback"])
  96. entry_high = high.shift(1).rolling(lookback).max()
  97. entry_low = low.shift(1).rolling(lookback).min()
  98. return (close > entry_high).fillna(False), (close < entry_low).fillna(False)
  99. if spec.family == "btc_lead_eth_lag":
  100. sig_close = frame["sig_close"]
  101. lead = int(p["lead_lookback"])
  102. btc_ret = sig_close / sig_close.shift(lead) - 1.0
  103. eth_ret = close / close.shift(lead) - 1.0
  104. entry = (btc_ret >= float(p["btc_return_threshold"])) & (eth_ret < btc_ret - float(p["lag_gap"]))
  105. exit_ = pd.Series(False, index=frame.index)
  106. return entry.fillna(False), exit_
  107. if spec.family == "short_bb_upper_rejection":
  108. trend = close.rolling(int(p["trend"])).mean()
  109. mid = close.rolling(int(p["bb"])).mean()
  110. std = close.rolling(int(p["bb"])).std(ddof=0)
  111. upper = mid + std * float(p["std"])
  112. atr = true_range(frame).rolling(int(p["atr"])).mean()
  113. entry = (close < trend) & (high >= upper) & (close < upper) & (close < open_) & atr.notna() & (atr > 0)
  114. exit_ = (close <= mid) | (close > trend)
  115. return entry.fillna(False), exit_.fillna(False)
  116. raise ValueError(f"unknown family {spec.family}")
  117. def run_strategy(candles: list[Candle], spec: StrategySpec, with_t: bool) -> tuple[SegmentResult, dict[str, int]]:
  118. frame = pd.DataFrame([c.__dict__ for c in candles])
  119. if spec.signal_symbol != spec.symbol:
  120. signal = _load_candles(spec.signal_symbol, BAR)
  121. left, right = _align_pair(candles, signal)
  122. candles = left
  123. frame = pd.DataFrame([c.__dict__ for c in left])
  124. frame["sig_close"] = [c.close for c in right]
  125. entry_signal, exit_signal = build_signals(spec, frame)
  126. warmup = max(int(value) for key, value in spec.params.items() if isinstance(value, int) and key not in {"max_hold"})
  127. equity = INITIAL_EQUITY
  128. ending_equity = equity
  129. peak_equity = equity
  130. max_drawdown = 0.0
  131. wins = 0
  132. trades: list[dict[str, object]] = []
  133. entries: list[dict[str, object]] = []
  134. exits: list[dict[str, object]] = []
  135. equity_curve: list[dict[str, float | int]] = []
  136. position: dict[str, object] | None = None
  137. pending_entry: dict[str, str] | None = None
  138. pending_exit = False
  139. reentry: dict[str, object] | None = None
  140. stats = {"take_exits": 0, "reentries": 0}
  141. for index in range(warmup, len(candles)):
  142. candle = candles[index]
  143. if pending_exit and position is not None:
  144. equity, won = _close_trade(trades, exits, position, candle, candle.open, "signal_exit")
  145. wins += int(won)
  146. position = None
  147. pending_exit = False
  148. if pending_entry is not None and position is None and equity > 0.0:
  149. side = pending_entry["side"]
  150. stop = float(spec.params["stop"])
  151. take = float(spec.params["take"])
  152. position = {
  153. "side": side,
  154. "entry_kind": pending_entry["kind"],
  155. "entry_time": candle.ts,
  156. "entry_price": candle.open,
  157. "entry_index": index,
  158. "margin_used": equity,
  159. "stop_price": candle.open * (1.0 - stop if side == "long" else 1.0 + stop),
  160. "take_price": candle.open * (1.0 + take if side == "long" else 1.0 - take),
  161. }
  162. entries.append({"ts": candle.ts, "price": candle.open, "side": side})
  163. stats["reentries"] += int(pending_entry["kind"] == "reentry")
  164. pending_entry = None
  165. current_equity = equity
  166. if position is not None:
  167. side = str(position["side"])
  168. stop_hit = (side == "long" and candle.low <= float(position["stop_price"])) or (side == "short" and candle.high >= float(position["stop_price"]))
  169. take_hit = (side == "long" and candle.high >= float(position["take_price"])) or (side == "short" and candle.low <= float(position["take_price"]))
  170. if stop_hit or take_hit:
  171. reason = "stop" if stop_hit else "take"
  172. exit_price = float(position["stop_price"] if stop_hit else position["take_price"])
  173. equity, won = _close_trade(trades, exits, position, candle, exit_price, reason)
  174. wins += int(won)
  175. current_equity = equity
  176. if take_hit and not stop_hit and with_t:
  177. stats["take_exits"] += 1
  178. reentry = {"side": side, "until": index + spec.reentry_bars, "anchor": exit_price}
  179. position = None
  180. if position is not None:
  181. current_equity = mark_to_market(side=str(position["side"]), margin_used=float(position["margin_used"]), entry_price=float(position["entry_price"]), mark_price=candle.close, leverage=LEVERAGE)
  182. peak_equity = max(peak_equity, current_equity)
  183. max_drawdown = max(max_drawdown, (peak_equity - current_equity) / peak_equity)
  184. equity_curve.append({"ts": candle.ts, "equity": current_equity, "close": candle.close})
  185. ending_equity = current_equity
  186. if index == len(candles) - 1 or equity <= 0.0:
  187. continue
  188. if position is None and reentry is not None:
  189. side = str(reentry["side"])
  190. anchor = float(reentry["anchor"])
  191. if index > int(reentry["until"]):
  192. reentry = None
  193. elif (side == "long" and candle.close <= anchor * (1.0 - spec.reentry_pullback_pct)) or (
  194. side == "short" and candle.close >= anchor * (1.0 + spec.reentry_pullback_pct)
  195. ):
  196. pending_entry = {"side": side, "kind": "reentry"}
  197. reentry = None
  198. continue
  199. if position is not None:
  200. held = index - int(position["entry_index"])
  201. if bool(exit_signal.iloc[index]) or held >= int(spec.params["max_hold"]):
  202. pending_exit = True
  203. continue
  204. if reentry is not None:
  205. continue
  206. if bool(entry_signal.iloc[index]):
  207. side = "short" if spec.family == "short_bb_upper_rejection" else "long"
  208. if spec.family == "range_momentum":
  209. side = "long" if frame.iloc[index]["close"] > frame.iloc[max(index - 1, 0)]["close"] else "short"
  210. pending_entry = {"side": side, "kind": "initial"}
  211. result = SegmentResult(
  212. trade_count=len(trades),
  213. total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
  214. win_rate=wins / len(trades) if trades else 0.0,
  215. max_drawdown=max_drawdown,
  216. trades=trades,
  217. open_position=position,
  218. candles=candles[warmup:],
  219. equity_curve=equity_curve,
  220. entries=entries,
  221. exits=exits,
  222. )
  223. return result, stats
  224. def cost_metrics(result: SegmentResult, cost: float, first_ts: int, last_ts: int) -> dict[str, float]:
  225. equity = INITIAL_EQUITY
  226. peak = equity
  227. dd = 0.0
  228. for trade in result.trades:
  229. equity *= 1.0 + float(trade["return_pct"]) / 100.0 - cost
  230. peak = max(peak, equity)
  231. dd = max(dd, (peak - equity) / peak)
  232. years = (last_ts - first_ts) / 86_400_000 / 365
  233. total = equity / INITIAL_EQUITY - 1.0
  234. ann = (1.0 + total) ** (1.0 / years) - 1.0 if total > -1 and years > 0 else 0.0
  235. return {"net_total_return": total, "net_annualized_return": ann, "net_max_drawdown": dd, "net_calmar": ann / dd if dd else 0.0}
  236. def specs() -> list[StrategySpec]:
  237. return [
  238. StrategySpec("range_momentum", ETH_SYMBOL, ETH_SYMBOL, "range-momo-eth-l10-tp0.006-sl0.004", {"lookback": 10, "take": 0.006, "stop": 0.004, "max_hold": 9999}, 48, 0.002),
  239. StrategySpec("btc_lead_eth_lag", ETH_SYMBOL, BTC_SYMBOL, "btc-lead-eth-lag-lb6-br0.006-gap0.002-tp0.012-sl0.006", {"lead_lookback": 6, "btc_return_threshold": 0.006, "lag_gap": 0.002, "take": 0.012, "stop": 0.006, "max_hold": 12}, 48, 0.003),
  240. StrategySpec("short_bb_upper_rejection", ETH_SYMBOL, ETH_SYMBOL, "short-bb-upper-rejection-eth", {"trend": 96, "bb": 48, "atr": 48, "std": 1.5, "take": 0.010, "stop": 0.006, "max_hold": 12}, 48, 0.002),
  241. ]
  242. def main() -> int:
  243. parser = argparse.ArgumentParser()
  244. parser.add_argument("--bar", default=BAR)
  245. parser.add_argument("--years", type=float, default=YEARS)
  246. parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
  247. args = parser.parse_args()
  248. candles = _load_candles(ETH_SYMBOL, args.bar)
  249. candles = candles[-int(args.years * 365 * 24 * 60 / 15) :]
  250. rows: list[dict[str, object]] = []
  251. for spec in specs():
  252. for with_t in (False, True):
  253. result, stats = run_strategy(candles, spec, with_t)
  254. for cost_name, cost in COSTS:
  255. rows.append(
  256. {
  257. "family": spec.family,
  258. "cost": cost_name,
  259. "name": spec.name + ("-t" if with_t else "-base"),
  260. "with_t": with_t,
  261. "trades": result.trade_count,
  262. "win_rate": result.win_rate,
  263. "gross_total_return": result.total_return,
  264. "gross_max_drawdown": result.max_drawdown,
  265. **stats,
  266. **cost_metrics(result, cost, candles[0].ts, candles[-1].ts),
  267. }
  268. )
  269. output = pd.DataFrame(rows).sort_values(["cost", "net_calmar", "net_annualized_return"], ascending=[True, False, False])
  270. args.output_dir.mkdir(parents=True, exist_ok=True)
  271. path = args.output_dir / "other-strategies-t-overlay-summary.csv"
  272. output.to_csv(path, index=False)
  273. print(output[output.cost.eq(PRIMARY_COST)].to_string(index=False))
  274. return 0
  275. if __name__ == "__main__":
  276. raise SystemExit(main())