validate_eth_robust_twap_external.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. from __future__ import annotations
  2. import csv
  3. import sys
  4. from dataclasses import dataclass
  5. from pathlib import Path
  6. import pandas as pd
  7. ROOT = Path(__file__).resolve().parents[1]
  8. sys.path.insert(0, str(ROOT))
  9. from okx_codex_trader.models import Candle
  10. from scripts import explore_ultrashort as explore
  11. SYMBOL = "ETH-USDT-SWAP"
  12. BAR = "15m"
  13. STRATEGY = "ETH Robust Price TWAP 15m"
  14. OUTPUT_DIR = Path("reports/eth-exploration")
  15. PREFIX = "eth-robust-twap-validation"
  16. INITIAL_EQUITY = 10_000.0
  17. LEVERAGE = 3
  18. YEARS = 10.0
  19. TREND_SMA = 60
  20. RSI_THRESHOLD = 3.0
  21. EXIT_RSI = 50.0
  22. STOP_LOSS_PCT = 0.012
  23. MAX_HOLD_BARS = 48
  24. ENTRY_OFFSETS = (0.003, 0.006, 0.009)
  25. ENTRY_VALID_BARS = 4
  26. FILL_BUFFER = 0.0
  27. COSTS = {
  28. "maker_maker": 0.0012,
  29. "maker_taker": 0.0021,
  30. "taker_taker": 0.0030,
  31. }
  32. HORIZONS = (
  33. ("3y", pd.DateOffset(years=3)),
  34. ("1y", pd.DateOffset(years=1)),
  35. ("6m", pd.DateOffset(months=6)),
  36. ("3m", pd.DateOffset(months=3)),
  37. )
  38. @dataclass
  39. class ExternalResult:
  40. trades: list[dict[str, object]]
  41. equity_curve: list[dict[str, object]]
  42. trade_count: int
  43. total_return: float
  44. win_rate: float
  45. max_drawdown: float
  46. def fmt_ts(ts: int) -> str:
  47. return pd.to_datetime(ts, unit="ms", utc=True).strftime("%Y-%m-%d %H:%M")
  48. def pct(value: float) -> str:
  49. return f"{value * 100:.2f}%"
  50. def parse_pct(value: object) -> float:
  51. return float(str(value).rstrip("%")) / 100.0
  52. def load_candles() -> list[Candle]:
  53. candles, _ = explore.load_cached_candles(explore.CANDLE_CACHE_DIR, SYMBOL, BAR)
  54. requested = explore.history_bars_for_years(BAR, YEARS)
  55. return candles[-requested:] if len(candles) > requested else candles
  56. def compute_rsi(closes: list[float], length: int) -> list[float]:
  57. series = pd.Series(closes, dtype=float)
  58. deltas = series.diff()
  59. gains = deltas.clip(lower=0.0)
  60. losses = -deltas.clip(upper=0.0)
  61. rsi = [float("nan")] * len(closes)
  62. if len(closes) <= length:
  63. return rsi
  64. average_gain = float(gains.iloc[1 : length + 1].mean())
  65. average_loss = float(losses.iloc[1 : length + 1].mean())
  66. for index in range(length, len(closes)):
  67. if index > length:
  68. average_gain = ((average_gain * (length - 1)) + float(gains.iloc[index])) / length
  69. average_loss = ((average_loss * (length - 1)) + float(losses.iloc[index])) / length
  70. if average_loss == 0.0:
  71. rsi[index] = 100.0 if average_gain > 0.0 else 50.0
  72. else:
  73. relative_strength = average_gain / average_loss
  74. rsi[index] = 100.0 - (100.0 / (1.0 + relative_strength))
  75. return rsi
  76. def trade_equity(entry_price: float, exit_price: float, margin_used: float) -> float:
  77. return margin_used + margin_used * LEVERAGE * ((exit_price - entry_price) / entry_price)
  78. def max_drawdown(values: list[float]) -> float:
  79. peak = values[0]
  80. drawdown = 0.0
  81. for value in values:
  82. peak = max(peak, value)
  83. drawdown = max(drawdown, (peak - value) / peak if peak else 0.0)
  84. return drawdown
  85. def external_backtest(candles: list[Candle], warmup_bars: int) -> ExternalResult:
  86. closes = [candle.close for candle in candles]
  87. trend = pd.Series(closes, dtype=float).rolling(TREND_SMA).mean().tolist()
  88. rsi = compute_rsi(closes, 2)
  89. account_equity = INITIAL_EQUITY
  90. ending_equity = INITIAL_EQUITY
  91. peak_equity = INITIAL_EQUITY
  92. worst_drawdown = 0.0
  93. wins = 0
  94. trades: list[dict[str, object]] = []
  95. equity_curve: list[dict[str, object]] = []
  96. position: dict[str, object] | None = None
  97. pending_limits: list[dict[str, float | int]] = []
  98. pending_exit = False
  99. for index in range(warmup_bars, len(candles)):
  100. candle = candles[index]
  101. if pending_exit and position is not None:
  102. margin_used = float(position["margin_used"])
  103. exit_equity = trade_equity(float(position["entry_price"]), candle.open, margin_used)
  104. pnl = exit_equity - margin_used
  105. trades.append(
  106. {
  107. "side": "Long",
  108. "entry_time": fmt_ts(int(position["entry_time"])),
  109. "exit_time": fmt_ts(candle.ts),
  110. "entry_price": round(float(position["entry_price"]), 4),
  111. "exit_price": round(candle.open, 4),
  112. "pnl": round(pnl, 4),
  113. "return_pct": round(pnl / margin_used * 100.0, 4),
  114. }
  115. )
  116. account_equity = exit_equity
  117. wins += 1 if pnl > 0.0 else 0
  118. position = None
  119. pending_exit = False
  120. pending_limits = []
  121. active_limits: list[dict[str, float | int]] = []
  122. for limit in pending_limits:
  123. if index > int(limit["expires_index"]):
  124. continue
  125. limit_price = float(limit["price"])
  126. if candle.low <= limit_price * (1.0 - FILL_BUFFER) and account_equity > 0.0:
  127. slice_margin = account_equity / len(ENTRY_OFFSETS)
  128. if position is None:
  129. position = {
  130. "entry_time": candle.ts,
  131. "entry_price": limit_price,
  132. "entry_index": index,
  133. "margin_used": slice_margin,
  134. "stop_price": limit_price * (1.0 - STOP_LOSS_PCT),
  135. }
  136. else:
  137. old_margin = float(position["margin_used"])
  138. new_margin = old_margin + slice_margin
  139. entry_price = (float(position["entry_price"]) * old_margin + limit_price * slice_margin) / new_margin
  140. position["entry_price"] = entry_price
  141. position["margin_used"] = new_margin
  142. position["stop_price"] = entry_price * (1.0 - STOP_LOSS_PCT)
  143. else:
  144. active_limits.append(limit)
  145. pending_limits = active_limits
  146. current_equity = account_equity
  147. if position is not None and candle.low <= float(position["stop_price"]):
  148. margin_used = float(position["margin_used"])
  149. exit_price = float(position["stop_price"])
  150. exit_equity = trade_equity(float(position["entry_price"]), exit_price, margin_used)
  151. pnl = exit_equity - margin_used
  152. trades.append(
  153. {
  154. "side": "Long",
  155. "entry_time": fmt_ts(int(position["entry_time"])),
  156. "exit_time": fmt_ts(candle.ts),
  157. "entry_price": round(float(position["entry_price"]), 4),
  158. "exit_price": round(exit_price, 4),
  159. "pnl": round(pnl, 4),
  160. "return_pct": round(pnl / account_equity * 100.0, 4),
  161. "cost_weight": round(margin_used / account_equity, 8),
  162. }
  163. )
  164. account_equity += pnl
  165. current_equity = account_equity
  166. wins += 1 if pnl > 0.0 else 0
  167. position = None
  168. pending_limits = []
  169. if position is not None:
  170. position_equity = trade_equity(float(position["entry_price"]), candle.close, float(position["margin_used"]))
  171. current_equity = account_equity - float(position["margin_used"]) + position_equity
  172. peak_equity = max(peak_equity, current_equity)
  173. worst_drawdown = max(worst_drawdown, (peak_equity - current_equity) / peak_equity)
  174. equity_curve.append({"ts": candle.ts, "equity": current_equity, "close": candle.close})
  175. ending_equity = current_equity
  176. if index == len(candles) - 1 or account_equity <= 0.0:
  177. continue
  178. if rsi[index] != rsi[index] or trend[index] != trend[index]:
  179. continue
  180. if position is not None:
  181. held_bars = index - int(position["entry_index"])
  182. if rsi[index] >= EXIT_RSI or held_bars >= MAX_HOLD_BARS:
  183. pending_exit = True
  184. pending_limits = []
  185. continue
  186. if not pending_limits and candle.close > float(trend[index]) and rsi[index] <= RSI_THRESHOLD:
  187. pending_limits = [
  188. {"price": candle.close * (1.0 - offset), "expires_index": index + ENTRY_VALID_BARS}
  189. for offset in ENTRY_OFFSETS
  190. ]
  191. return ExternalResult(
  192. trades=trades,
  193. equity_curve=equity_curve,
  194. trade_count=len(trades),
  195. total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
  196. win_rate=wins / len(trades) if trades else 0.0,
  197. max_drawdown=worst_drawdown,
  198. )
  199. def cost_equity_frame(trades: list[dict[str, object]], first_ts: int, roundtrip_cost: float) -> pd.DataFrame:
  200. rows = [{"ts": pd.to_datetime(first_ts, unit="ms", utc=True), "equity": INITIAL_EQUITY}]
  201. equity = INITIAL_EQUITY
  202. for trade in trades:
  203. equity *= 1.0 + float(trade["return_pct"]) / 100.0 - roundtrip_cost * float(trade.get("cost_weight", 1.0))
  204. rows.append({"ts": pd.to_datetime(str(trade["exit_time"]), utc=True), "equity": equity})
  205. return pd.DataFrame(rows)
  206. def annualized_metrics(frame: pd.DataFrame, first_ts: int, last_ts: int) -> dict[str, float]:
  207. years = (last_ts - first_ts) / 86_400_000 / 365
  208. total_return = float(frame["equity"].iloc[-1] / frame["equity"].iloc[0] - 1.0)
  209. annualized = (1.0 + total_return) ** (1.0 / years) - 1.0 if total_return > -1.0 and years > 0.0 else 0.0
  210. drawdown = max_drawdown([float(value) for value in frame["equity"]])
  211. return {
  212. "return": total_return,
  213. "annualized": annualized,
  214. "max_dd": drawdown,
  215. "calmar": annualized / drawdown if drawdown else 0.0,
  216. }
  217. def normalize_from_cutoff(frame: pd.DataFrame, cutoff: pd.Timestamp) -> pd.DataFrame:
  218. recent = frame[frame["ts"] >= cutoff][["ts", "equity"]].copy()
  219. if recent.empty:
  220. recent = frame[["ts", "equity"]].copy()
  221. recent["equity"] = recent["equity"] / float(recent["equity"].iloc[0]) * INITIAL_EQUITY
  222. return recent
  223. def horizon_metrics(frame: pd.DataFrame, last_ts: int) -> list[dict[str, object]]:
  224. rows: list[dict[str, object]] = []
  225. end = pd.to_datetime(last_ts, unit="ms", utc=True)
  226. for label, offset in HORIZONS:
  227. cutoff = end - offset
  228. horizon = normalize_from_cutoff(frame, cutoff)
  229. metrics = annualized_metrics(horizon, int(horizon["ts"].iloc[0].timestamp() * 1000), last_ts)
  230. rows.append({"horizon": label, "start": horizon["ts"].iloc[0].strftime("%Y-%m-%d %H:%M"), **metrics})
  231. return rows
  232. def monthly_rows(frame: pd.DataFrame, label: str) -> list[dict[str, object]]:
  233. month_end = frame.set_index("ts")["equity"].resample("ME").last().ffill()
  234. month_start = month_end.shift(1)
  235. if len(month_end):
  236. month_start.iloc[0] = float(frame["equity"].iloc[0])
  237. rows = []
  238. for period, end_equity, start_equity in zip(month_end.index, month_end, month_start, strict=True):
  239. rows.append(
  240. {
  241. "cost": label,
  242. "period": period.tz_localize(None).to_period("M").strftime("%Y-%m"),
  243. "return": float(end_equity / start_equity - 1.0),
  244. "end_equity": float(end_equity),
  245. }
  246. )
  247. return rows
  248. def trade_stats(trades: list[dict[str, object]]) -> dict[str, float | int]:
  249. returns = [float(trade["return_pct"]) / 100.0 for trade in trades]
  250. wins = [value for value in returns if value > 0.0]
  251. losses = [value for value in returns if value < 0.0]
  252. max_consecutive_losses = 0
  253. current_losses = 0
  254. for value in returns:
  255. if value < 0.0:
  256. current_losses += 1
  257. max_consecutive_losses = max(max_consecutive_losses, current_losses)
  258. else:
  259. current_losses = 0
  260. avg_win = sum(wins) / len(wins) if wins else 0.0
  261. avg_loss = abs(sum(losses) / len(losses)) if losses else 0.0
  262. return {
  263. "trades": len(trades),
  264. "win_rate": len(wins) / len(returns) if returns else 0.0,
  265. "avg_return": sum(returns) / len(returns) if returns else 0.0,
  266. "payoff_ratio": avg_win / avg_loss if avg_loss else 0.0,
  267. "profit_factor": sum(wins) / abs(sum(losses)) if losses else 0.0,
  268. "max_consecutive_losses": max_consecutive_losses,
  269. }
  270. def compare_report_rows(cost_rows: list[dict[str, object]], recent_metrics: dict[str, object]) -> list[dict[str, object]]:
  271. comparisons: list[dict[str, object]] = []
  272. recent_summary = pd.read_csv("reports/ultrashort/ultrashort-recent-summary.csv")
  273. recent_row = recent_summary[recent_summary["strategy"] == STRATEGY].iloc[0]
  274. for key in ("3y_return", "3y_annualized", "3y_max_dd"):
  275. local = float(recent_metrics[key])
  276. report = parse_pct(recent_row[key])
  277. comparisons.append(
  278. {
  279. "source": "ultrashort-recent-summary.csv",
  280. "field": key,
  281. "local": local,
  282. "report": report,
  283. "diff": local - report,
  284. "flag": abs(local - report) > 0.001,
  285. }
  286. )
  287. cost_summary = pd.read_csv("reports/ultrashort/ultrashort-cost-scenarios.csv")
  288. for local_row in cost_rows:
  289. report_row = cost_summary[(cost_summary["strategy"] == STRATEGY) & (cost_summary["cost"] == local_row["cost"])].iloc[0]
  290. for key in ("return", "annualized", "max_dd"):
  291. local = float(local_row[key])
  292. report = parse_pct(report_row[key])
  293. comparisons.append(
  294. {
  295. "source": "ultrashort-cost-scenarios.csv",
  296. "field": f"{local_row['cost']} {key}",
  297. "local": local,
  298. "report": report,
  299. "diff": local - report,
  300. "flag": abs(local - report) > 0.001,
  301. }
  302. )
  303. return comparisons
  304. def main() -> int:
  305. candles = load_candles()
  306. candidate = explore.build_rsi2_long_guarded_price_twap_candidate(
  307. TREND_SMA,
  308. RSI_THRESHOLD,
  309. EXIT_RSI,
  310. STOP_LOSS_PCT,
  311. MAX_HOLD_BARS,
  312. ENTRY_OFFSETS,
  313. ENTRY_VALID_BARS,
  314. FILL_BUFFER,
  315. )
  316. main_result = candidate.run(candles=candles, leverage=LEVERAGE, warmup_bars=candidate.warmup_bars)
  317. external_result = external_backtest(candles, candidate.warmup_bars)
  318. OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
  319. cost_rows = []
  320. horizon_rows_out = []
  321. monthly_out = []
  322. equity_rows = [
  323. {
  324. "equity_type": "mark_to_market",
  325. "cost": "gross",
  326. "ts": pd.to_datetime(point["ts"], unit="ms", utc=True),
  327. "equity": point["equity"],
  328. "close": point["close"],
  329. }
  330. for point in main_result.equity_curve
  331. ]
  332. for cost_name, cost_value in COSTS.items():
  333. frame = explore.cost_adjusted_trade_equity_frame(main_result, cost_value)
  334. equity_rows.extend(
  335. {
  336. "equity_type": "closed_trade_cost_adjusted",
  337. "cost": cost_name,
  338. "ts": row.ts,
  339. "equity": row.equity,
  340. "close": "",
  341. }
  342. for row in frame.itertuples(index=False)
  343. )
  344. metrics = explore.annualized_metrics_from_equity(frame, int(frame["ts"].iloc[0].timestamp() * 1000), candles[-1].ts)
  345. cost_rows.append(
  346. {
  347. "cost": cost_name,
  348. "roundtrip_cost_on_margin": cost_value,
  349. "return": metrics["net_total_return"],
  350. "annualized": metrics["net_annualized_return"],
  351. "max_dd": metrics["net_max_drawdown"],
  352. "calmar": metrics["net_calmar"],
  353. }
  354. )
  355. for row in horizon_metrics(frame, candles[-1].ts):
  356. horizon_rows_out.append({"cost": cost_name, **row})
  357. monthly_out.extend(monthly_rows(frame, cost_name))
  358. maker_taker = explore.cost_adjusted_trade_equity_frame(main_result, COSTS["maker_taker"])
  359. cutoff_3y = pd.to_datetime(candles[-1].ts, unit="ms", utc=True) - pd.DateOffset(years=3)
  360. recent_3y = normalize_from_cutoff(maker_taker, cutoff_3y)
  361. recent_3y_metrics = annualized_metrics(recent_3y, int(recent_3y["ts"].iloc[0].timestamp() * 1000), candles[-1].ts)
  362. recent_metrics = {
  363. "3y_return": recent_3y_metrics["return"],
  364. "3y_annualized": recent_3y_metrics["annualized"],
  365. "3y_max_dd": recent_3y_metrics["max_dd"],
  366. }
  367. comparisons = compare_report_rows(cost_rows, recent_metrics)
  368. main_first = main_result.trades[:50]
  369. external_first = external_result.trades[:50]
  370. trade_compare_rows = []
  371. for index, (main_trade, external_trade) in enumerate(zip(main_first, external_first, strict=True), start=1):
  372. fields = ("entry_time", "exit_time", "entry_price", "exit_price")
  373. trade_compare_rows.append(
  374. {
  375. "index": index,
  376. **{f"main_{field}": main_trade[field] for field in fields},
  377. **{f"external_{field}": external_trade[field] for field in fields},
  378. "match": all(main_trade[field] == external_trade[field] for field in fields),
  379. }
  380. )
  381. stats = trade_stats(main_result.trades)
  382. gross_metrics = {
  383. "return": main_result.total_return,
  384. "annualized": (1.0 + main_result.total_return) ** (1.0 / ((candles[-1].ts - candles[0].ts) / 86_400_000 / 365)) - 1.0,
  385. "max_dd": main_result.max_drawdown,
  386. "calmar": 0.0,
  387. }
  388. gross_metrics["calmar"] = gross_metrics["annualized"] / gross_metrics["max_dd"] if gross_metrics["max_dd"] else 0.0
  389. metrics_rows = [
  390. {"section": "gross_10y", **gross_metrics},
  391. {"section": "trades", **stats},
  392. {
  393. "section": "external_delta",
  394. "trades": external_result.trade_count - main_result.trade_count,
  395. "return": external_result.total_return - main_result.total_return,
  396. "win_rate": external_result.win_rate - main_result.win_rate,
  397. "max_dd": external_result.max_drawdown - main_result.max_drawdown,
  398. },
  399. ]
  400. worst_month = min(monthly_out, key=lambda row: row["return"])
  401. main_trade_count_match = external_result.trade_count == main_result.trade_count
  402. first_50_match = all(bool(row["match"]) for row in trade_compare_rows)
  403. flagged = [row for row in comparisons if row["flag"]]
  404. pd.DataFrame(equity_rows).to_csv(OUTPUT_DIR / f"{PREFIX}-equity.csv", index=False)
  405. pd.DataFrame(metrics_rows).to_csv(OUTPUT_DIR / f"{PREFIX}-metrics.csv", index=False)
  406. pd.DataFrame(cost_rows).to_csv(OUTPUT_DIR / f"{PREFIX}-costs.csv", index=False)
  407. pd.DataFrame(horizon_rows_out).to_csv(OUTPUT_DIR / f"{PREFIX}-horizons.csv", index=False)
  408. pd.DataFrame(monthly_out).to_csv(OUTPUT_DIR / f"{PREFIX}-monthly.csv", index=False)
  409. pd.DataFrame(comparisons).to_csv(OUTPUT_DIR / f"{PREFIX}-comparison.csv", index=False)
  410. pd.DataFrame(trade_compare_rows).to_csv(OUTPUT_DIR / f"{PREFIX}-first50-trades.csv", index=False)
  411. summary = OUTPUT_DIR / f"{PREFIX}-summary.md"
  412. summary.write_text(
  413. "\n".join(
  414. [
  415. "# ETH Robust Price TWAP 15m Validation",
  416. "",
  417. f"Candidate: `{candidate.name}`",
  418. f"Candles: {len(candles)} from {fmt_ts(candles[0].ts)} to {fmt_ts(candles[-1].ts)}",
  419. f"Params: trend={TREND_SMA}, rsi={RSI_THRESHOLD:g}, exit={EXIT_RSI:g}, stop={STOP_LOSS_PCT}, max_hold={MAX_HOLD_BARS}, offsets={ENTRY_OFFSETS}, valid={ENTRY_VALID_BARS}, fill_buffer={FILL_BUFFER:g}",
  420. "",
  421. "## Main Runner",
  422. "",
  423. f"- Mark-to-market 10y return: {pct(main_result.total_return)}",
  424. f"- Mark-to-market 10y annualized: {pct(gross_metrics['annualized'])}",
  425. f"- Mark-to-market max drawdown: {pct(main_result.max_drawdown)}",
  426. f"- Trades: {main_result.trade_count}",
  427. f"- Win rate: {pct(float(stats['win_rate']))}",
  428. f"- Average trade return: {pct(float(stats['avg_return']))}",
  429. f"- Payoff ratio: {float(stats['payoff_ratio']):.4f}",
  430. f"- Profit factor: {float(stats['profit_factor']):.4f}",
  431. f"- Max consecutive losses: {int(stats['max_consecutive_losses'])}",
  432. f"- Worst month: {worst_month['cost']} {worst_month['period']} {pct(float(worst_month['return']))}",
  433. "",
  434. "## Cost Scenarios",
  435. "",
  436. "| cost | return | annualized | max_dd | calmar |",
  437. "| --- | --- | --- | --- | --- |",
  438. *[
  439. f"| {row['cost']} | {pct(float(row['return']))} | {pct(float(row['annualized']))} | {pct(float(row['max_dd']))} | {float(row['calmar']):.2f} |"
  440. for row in cost_rows
  441. ],
  442. "",
  443. "## Report Comparison",
  444. "",
  445. f"- Differences over 0.1%: {len(flagged)}",
  446. f"- First 50 independent trades match: {first_50_match}",
  447. f"- Independent full trade count matches: {main_trade_count_match}",
  448. f"- Note: report CSV rows are closed-trade cost-adjusted equity, not the runner's open-position mark-to-market `total_return`.",
  449. f"- Finding: the runner's mark-to-market `total_return` collapses to {pct(main_result.total_return)} while the closed-trade cost equity used by the report is positive; this is a separate accounting-path issue from the CSV reproduction.",
  450. "",
  451. "## Generated Files",
  452. "",
  453. f"- `{OUTPUT_DIR / f'{PREFIX}-summary.md'}`",
  454. f"- `{OUTPUT_DIR / f'{PREFIX}-metrics.csv'}`",
  455. f"- `{OUTPUT_DIR / f'{PREFIX}-costs.csv'}`",
  456. f"- `{OUTPUT_DIR / f'{PREFIX}-horizons.csv'}`",
  457. f"- `{OUTPUT_DIR / f'{PREFIX}-monthly.csv'}`",
  458. f"- `{OUTPUT_DIR / f'{PREFIX}-comparison.csv'}`",
  459. f"- `{OUTPUT_DIR / f'{PREFIX}-first50-trades.csv'}`",
  460. f"- `{OUTPUT_DIR / f'{PREFIX}-equity.csv'}`",
  461. "",
  462. ]
  463. ),
  464. encoding="utf-8",
  465. )
  466. print(f"summary={summary}")
  467. print(f"flagged_differences={len(flagged)}")
  468. print(f"first_50_independent_trades_match={first_50_match}")
  469. print(f"independent_trade_count_match={main_trade_count_match}")
  470. return 1 if flagged or not first_50_match or not main_trade_count_match else 0
  471. if __name__ == "__main__":
  472. raise SystemExit(main())