search_eth_bb_squeeze_risk_10y.py 23 KB

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