| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784 |
- from __future__ import annotations
- import argparse
- import sys
- from collections import Counter
- from dataclasses import dataclass
- from pathlib import Path
- import pandas as pd
- sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
- from okx_codex_trader.models import Candle
- from okx_codex_trader.sampled_report import SegmentResult, mark_to_market, trade_equity
- ETH_SYMBOL = "ETH-USDT-SWAP"
- BTC_SYMBOL = "BTC-USDT-SWAP"
- BAR = "15m"
- YEARS = 10.0
- LEVERAGE = 3
- INITIAL_EQUITY = 10_000.0
- DATA_DIR = Path("data/okx-candles")
- OUTPUT_DIR = Path("reports/eth-exploration")
- PRIMARY_COST = "maker_taker"
- COSTS = (
- ("maker_maker", 0.0012),
- ("maker_taker", 0.0021),
- ("taker_taker", 0.0030),
- )
- HORIZONS = (
- ("full", None),
- ("3y", pd.DateOffset(years=3)),
- ("1y", pd.DateOffset(years=1)),
- ("6m", pd.DateOffset(months=6)),
- ("3m", pd.DateOffset(months=3)),
- ("30d", pd.DateOffset(days=30)),
- )
- @dataclass(frozen=True)
- class Variant:
- band_length: int
- bandwidth_lookback: int
- bandwidth_quantile: float
- side_mode: str
- btc_filter: str
- eth_vol_cap: float | None
- cooldown_bars: int
- stop_loss_pct: float
- trend_momentum_bars: int
- trend_middle_buffer_pct: float
- trend_middle_confirm_bars: int
- neutral_middle_buffer_pct: float
- neutral_middle_confirm_bars: int
- protect_trigger_pct: float
- protect_lock_pct: float
- protect_trail_giveback_pct: float
- protect_middle_confirm_bars: int
- fast_vol_pct: float
- fast_bandwidth_ratio: float
- fast_middle_buffer_pct: float
- fast_middle_confirm_bars: int
- max_hold_bars: int
- @property
- def name(self) -> str:
- vol = "none" if self.eth_vol_cap is None else f"{self.eth_vol_cap:g}"
- return (
- f"eth-adaptive-state-exit-l{self.band_length}-bw{self.bandwidth_lookback}"
- f"-q{self.bandwidth_quantile:g}-{self.side_mode}-{self.btc_filter}-vc{vol}"
- f"-sl{self.stop_loss_pct:g}-tr{self.trend_momentum_bars}"
- f"-tb{self.trend_middle_buffer_pct:g}-tc{self.trend_middle_confirm_bars}"
- f"-nb{self.neutral_middle_buffer_pct:g}-nc{self.neutral_middle_confirm_bars}"
- f"-pt{self.protect_trigger_pct:g}-pl{self.protect_lock_pct:g}"
- f"-pg{self.protect_trail_giveback_pct:g}-pc{self.protect_middle_confirm_bars}"
- f"-fv{self.fast_vol_pct:g}-fr{self.fast_bandwidth_ratio:g}"
- f"-fb{self.fast_middle_buffer_pct:g}-fc{self.fast_middle_confirm_bars}"
- f"-mh{self.max_hold_bars}"
- )
- def _format_ts(ts: int) -> str:
- return pd.to_datetime(ts, unit="ms", utc=True).strftime("%Y-%m-%d %H:%M")
- def _load_candles(symbol: str, bar: str) -> list[Candle]:
- frame = pd.read_csv(DATA_DIR / symbol / f"{bar}.csv")
- return [
- 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),
- )
- for row in frame.itertuples(index=False)
- ]
- def _align_pair(left: list[Candle], right: list[Candle]) -> tuple[list[Candle], list[Candle]]:
- right_by_ts = {candle.ts: candle for candle in right}
- left_out: list[Candle] = []
- right_out: list[Candle] = []
- for candle in left:
- other = right_by_ts.get(candle.ts)
- if other is not None:
- left_out.append(candle)
- right_out.append(other)
- return left_out, right_out
- def close_position(
- *,
- trades: list[dict[str, object]],
- exits: list[dict[str, object]],
- position: dict[str, object],
- candle: Candle,
- exit_price: float,
- reason: str,
- ) -> tuple[float, bool]:
- margin_used = float(position["margin_used"])
- exit_equity = trade_equity(
- side=str(position["side"]),
- margin_used=margin_used,
- entry_price=float(position["entry_price"]),
- exit_price=exit_price,
- leverage=LEVERAGE,
- )
- pnl = exit_equity - margin_used
- trades.append(
- {
- "side": "Long" if position["side"] == "long" else "Short",
- "entry_ts": int(position["entry_time"]),
- "exit_ts": candle.ts,
- "entry_time": _format_ts(int(position["entry_time"])),
- "exit_time": _format_ts(candle.ts),
- "entry_price": round(float(position["entry_price"]), 4),
- "exit_price": round(exit_price, 4),
- "pnl": round(pnl, 4),
- "return_pct": round(pnl / margin_used * 100.0, 4),
- "cost_weight": 1.0,
- "exit_reason": reason,
- "entry_state": str(position["state"]),
- "mfe_pct": round(float(position["mfe_pct"]) * 100.0, 4),
- "hold_bars": int(position["hold_bars"]),
- }
- )
- exits.append({"ts": candle.ts, "price": exit_price, "side": position["side"]})
- return exit_equity, pnl > 0.0
- def favorable_move(side: str, entry_price: float, candle: Candle) -> float:
- if side == "long":
- return candle.high / entry_price - 1.0
- return entry_price / candle.low - 1.0
- def close_profit(side: str, entry_price: float, close: float) -> float:
- if side == "long":
- return close / entry_price - 1.0
- return entry_price / close - 1.0
- def hard_stop_exit(position: dict[str, object], candle: Candle) -> tuple[float, str] | None:
- side = str(position["side"])
- stop = float(position["stop_price"])
- if side == "long":
- if candle.open <= stop:
- return candle.open, "stop_gap"
- if candle.low <= stop:
- return stop, "stop"
- else:
- if candle.open >= stop:
- return candle.open, "stop_gap"
- if candle.high >= stop:
- return stop, "stop"
- return None
- def protection_stop_exit(position: dict[str, object], candle: Candle, variant: Variant) -> tuple[float, str] | None:
- if str(position["state"]) != "protect":
- return None
- side = str(position["side"])
- entry_price = float(position["entry_price"])
- mfe = float(position["mfe_pct"])
- if side == "long":
- lock_stop = entry_price * (1.0 + variant.protect_lock_pct)
- trail_stop = entry_price * (1.0 + mfe - variant.protect_trail_giveback_pct)
- stop = max(float(position["stop_price"]), lock_stop, trail_stop)
- if candle.open <= stop:
- return candle.open, "protect_gap"
- if candle.low <= stop:
- return stop, "protect_trail"
- else:
- lock_stop = entry_price * (1.0 - variant.protect_lock_pct)
- trail_stop = entry_price * (1.0 - mfe + variant.protect_trail_giveback_pct)
- stop = min(float(position["stop_price"]), lock_stop, trail_stop)
- if candle.open >= stop:
- return candle.open, "protect_gap"
- if candle.high >= stop:
- return stop, "protect_trail"
- return None
- def adverse_middle(position: dict[str, object], candle: Candle, middle: float, buffer_pct: float) -> bool:
- if position["side"] == "long":
- return candle.close < middle * (1.0 - buffer_pct)
- return candle.close > middle * (1.0 + buffer_pct)
- def trend_continues(position: dict[str, object], candle: Candle, middle: float, momentum: float, required_bars: int) -> bool:
- if position["side"] == "long":
- above_middle = candle.close > middle
- same_direction = momentum > 0.0
- else:
- above_middle = candle.close < middle
- same_direction = momentum < 0.0
- if above_middle and same_direction:
- position["trend_bars"] = int(position["trend_bars"]) + 1
- else:
- position["trend_bars"] = 0
- return int(position["trend_bars"]) >= required_bars
- def update_state(
- *,
- position: dict[str, object],
- candle: Candle,
- middle: float,
- momentum: float,
- realized_vol: float,
- bandwidth: float,
- threshold: float,
- variant: Variant,
- ) -> None:
- position["hold_bars"] = int(position["hold_bars"]) + 1
- position["mfe_pct"] = max(float(position["mfe_pct"]), favorable_move(str(position["side"]), float(position["entry_price"]), candle))
- if float(position["mfe_pct"]) >= variant.protect_trigger_pct:
- position["state"] = "protect"
- return
- if realized_vol >= variant.fast_vol_pct or bandwidth >= threshold * variant.fast_bandwidth_ratio:
- position["state"] = "fast"
- return
- if trend_continues(position, candle, middle, momentum, variant.trend_momentum_bars):
- position["state"] = "trend"
- else:
- position["state"] = "neutral"
- def state_signal_exit(position: dict[str, object], candle: Candle, middle: float, variant: Variant) -> str | None:
- state = str(position["state"])
- if state == "trend":
- buffer_pct = variant.trend_middle_buffer_pct
- confirm_bars = variant.trend_middle_confirm_bars
- elif state == "protect":
- buffer_pct = 0.0
- confirm_bars = variant.protect_middle_confirm_bars
- elif state == "fast":
- buffer_pct = variant.fast_middle_buffer_pct
- confirm_bars = variant.fast_middle_confirm_bars
- else:
- buffer_pct = variant.neutral_middle_buffer_pct
- confirm_bars = variant.neutral_middle_confirm_bars
- if adverse_middle(position, candle, middle, buffer_pct):
- position["middle_exit_streak"] = int(position["middle_exit_streak"]) + 1
- else:
- position["middle_exit_streak"] = 0
- if int(position["middle_exit_streak"]) >= confirm_bars:
- return f"{state}_middle"
- if int(position["hold_bars"]) >= variant.max_hold_bars:
- return "time_exit"
- return None
- def run_variant(eth: list[Candle], btc: list[Candle], variant: Variant) -> tuple[SegmentResult, dict[str, int]]:
- eth_close = pd.Series([candle.close for candle in eth], dtype=float)
- btc_close = pd.Series([candle.close for candle in btc], dtype=float)
- middle_series = eth_close.rolling(variant.band_length).mean()
- stdev_series = eth_close.rolling(variant.band_length).std(ddof=0)
- upper_values = middle_series + 2.0 * stdev_series
- lower_values = middle_series - 2.0 * stdev_series
- middle = middle_series.tolist()
- upper = upper_values.tolist()
- lower = lower_values.tolist()
- bandwidth = ((upper_values - lower_values) / middle_series).tolist()
- threshold = pd.Series(bandwidth, dtype=float).rolling(variant.bandwidth_lookback).quantile(variant.bandwidth_quantile).tolist()
- btc_sma = btc_close.rolling(480).mean().tolist()
- btc_momentum = (btc_close / btc_close.shift(96) - 1.0).tolist()
- eth_realized_vol = eth_close.pct_change().rolling(96).std(ddof=0).tolist()
- eth_momentum = (eth_close / eth_close.shift(variant.band_length // 2) - 1.0).tolist()
- warmup_bars = max(variant.band_length, variant.bandwidth_lookback, 480, 96)
- equity = INITIAL_EQUITY
- ending_equity = equity
- peak_equity = equity
- max_drawdown = 0.0
- wins = 0
- trades: list[dict[str, object]] = []
- entries: list[dict[str, object]] = []
- exits: list[dict[str, object]] = []
- equity_curve: list[dict[str, float | int]] = []
- position: dict[str, object] | None = None
- pending_entry_side: str | None = None
- pending_exit_reason: str | None = None
- cooldown_until = -1
- exit_counts: Counter[str] = Counter()
- for index in range(warmup_bars, len(eth)):
- candle = eth[index]
- if pending_exit_reason is not None and position is not None:
- equity, won = close_position(
- trades=trades,
- exits=exits,
- position=position,
- candle=candle,
- exit_price=candle.open,
- reason=pending_exit_reason,
- )
- wins += int(won)
- exit_counts[pending_exit_reason] += 1
- position = None
- pending_exit_reason = None
- cooldown_until = index + variant.cooldown_bars
- if pending_entry_side is not None and position is None and equity > 0.0:
- entry_price = candle.open
- position = {
- "side": pending_entry_side,
- "entry_time": candle.ts,
- "entry_price": entry_price,
- "margin_used": equity,
- "stop_price": entry_price * (1.0 - variant.stop_loss_pct if pending_entry_side == "long" else 1.0 + variant.stop_loss_pct),
- "mfe_pct": 0.0,
- "state": "neutral",
- "trend_bars": 0,
- "middle_exit_streak": 0,
- "hold_bars": 0,
- }
- entries.append({"ts": candle.ts, "price": entry_price, "side": pending_entry_side})
- pending_entry_side = None
- current_equity = equity
- if position is not None:
- risk_exit = hard_stop_exit(position, candle)
- if risk_exit is None:
- values = (middle[index], bandwidth[index], threshold[index], eth_realized_vol[index], eth_momentum[index])
- if not any(value != value for value in values):
- update_state(
- position=position,
- candle=candle,
- middle=float(middle[index]),
- momentum=float(eth_momentum[index]),
- realized_vol=float(eth_realized_vol[index]),
- bandwidth=float(bandwidth[index]),
- threshold=float(threshold[index]),
- variant=variant,
- )
- risk_exit = protection_stop_exit(position, candle, variant)
- if risk_exit is None:
- signal_reason = state_signal_exit(position, candle, float(middle[index]), variant)
- if signal_reason is not None:
- pending_exit_reason = signal_reason
- if risk_exit is not None:
- exit_price, reason = risk_exit
- equity, won = close_position(
- trades=trades,
- exits=exits,
- position=position,
- candle=candle,
- exit_price=exit_price,
- reason=reason,
- )
- wins += int(won)
- exit_counts[reason] += 1
- current_equity = equity
- position = None
- pending_exit_reason = None
- cooldown_until = index + variant.cooldown_bars
- if position is not None:
- 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,
- )
- peak_equity = max(peak_equity, current_equity)
- max_drawdown = max(max_drawdown, (peak_equity - current_equity) / peak_equity)
- equity_curve.append({"ts": candle.ts, "equity": current_equity, "close": candle.close})
- ending_equity = current_equity
- if index == len(eth) - 1 or equity <= 0.0:
- continue
- values = (middle[index], upper[index], lower[index], bandwidth[index], threshold[index], btc_sma[index], btc_momentum[index], eth_realized_vol[index])
- if any(value != value for value in values):
- continue
- if position is not None or index < cooldown_until:
- continue
- if variant.eth_vol_cap is not None and float(eth_realized_vol[index]) > variant.eth_vol_cap:
- continue
- if variant.btc_filter == "btc-up" and not (btc_close.iloc[index] > float(btc_sma[index])):
- continue
- if variant.btc_filter == "btc-up-momo" and not (
- btc_close.iloc[index] > float(btc_sma[index]) and float(btc_momentum[index]) > 0.0
- ):
- continue
- if bandwidth[index] <= threshold[index]:
- if candle.close > float(upper[index]):
- pending_entry_side = "long"
- elif variant.side_mode == "both" and candle.close < float(lower[index]):
- pending_entry_side = "short"
- trade_count = len(trades)
- result = SegmentResult(
- trade_count=trade_count,
- total_return=(ending_equity - INITIAL_EQUITY) / INITIAL_EQUITY,
- win_rate=wins / trade_count if trade_count else 0.0,
- max_drawdown=max_drawdown,
- trades=trades,
- open_position=position,
- candles=eth[warmup_bars:],
- equity_curve=equity_curve,
- entries=entries,
- exits=exits,
- )
- return result, dict(exit_counts)
- def cost_equity_frame(result: SegmentResult, cost: float) -> pd.DataFrame:
- rows = [{"ts": pd.to_datetime(result.equity_curve[0]["ts"], unit="ms", utc=True), "equity": INITIAL_EQUITY}]
- equity = INITIAL_EQUITY
- for trade in result.trades:
- equity *= 1.0 + float(trade["return_pct"]) / 100.0 - cost * float(trade.get("cost_weight", 1.0))
- rows.append({"ts": pd.to_datetime(int(trade["exit_ts"]), unit="ms", utc=True), "equity": equity})
- return pd.DataFrame(rows)
- def max_drawdown(values: list[float]) -> float:
- peak = values[0]
- dd = 0.0
- for value in values:
- peak = max(peak, value)
- dd = max(dd, (peak - value) / peak if peak else 0.0)
- return dd
- def equity_metrics(frame: pd.DataFrame, first_ts: int, last_ts: int) -> dict[str, float]:
- years = (last_ts - first_ts) / 86_400_000 / 365
- total_return = float(frame["equity"].iloc[-1] / frame["equity"].iloc[0] - 1.0)
- annualized = (1.0 + total_return) ** (1.0 / years) - 1.0 if total_return > -1.0 and years > 0.0 else 0.0
- dd = max_drawdown([float(value) for value in frame["equity"]])
- return {
- "net_total_return": total_return,
- "net_annualized_return": annualized,
- "net_max_drawdown": dd,
- "net_calmar": annualized / dd if dd else 0.0,
- }
- def trade_stats(trades: list[dict[str, object]]) -> dict[str, float | int]:
- if not trades:
- return {
- "trades": 0,
- "win_rate": 0.0,
- "profit_factor": 0.0,
- "payoff_ratio": 0.0,
- "avg_return_pct": 0.0,
- "avg_mfe_pct": 0.0,
- "avg_hold_bars": 0.0,
- }
- returns = [float(trade["return_pct"]) for trade in trades]
- wins = [value for value in returns if value > 0.0]
- losses = [-value for value in returns if value < 0.0]
- return {
- "trades": len(trades),
- "win_rate": len(wins) / len(trades),
- "profit_factor": sum(wins) / sum(losses) if losses else 0.0,
- "payoff_ratio": (sum(wins) / len(wins)) / (sum(losses) / len(losses)) if wins and losses else 0.0,
- "avg_return_pct": sum(returns) / len(returns),
- "avg_mfe_pct": sum(float(trade["mfe_pct"]) for trade in trades) / len(trades),
- "avg_hold_bars": sum(int(trade["hold_bars"]) for trade in trades) / len(trades),
- }
- def exit_reason_counts(trades: list[dict[str, object]]) -> dict[str, int]:
- counts = Counter(str(trade["exit_reason"]) for trade in trades)
- return {
- "stop_exits": counts["stop"] + counts["stop_gap"],
- "protect_exits": counts["protect_trail"] + counts["protect_gap"],
- "trend_middle_exits": counts["trend_middle"],
- "protect_middle_exits": counts["protect_middle"],
- "fast_middle_exits": counts["fast_middle"],
- "neutral_middle_exits": counts["neutral_middle"],
- "time_exits": counts["time_exit"],
- }
- def horizon_frame(frame: pd.DataFrame, first_ts: int, last_ts: int, offset: pd.DateOffset | None) -> tuple[pd.DataFrame, int, str, str]:
- end_time = pd.to_datetime(last_ts, unit="ms", utc=True)
- if offset is None:
- start_time = pd.to_datetime(first_ts, unit="ms", utc=True)
- return frame[["ts", "equity"]].copy(), first_ts, start_time.strftime("%Y-%m-%d %H:%M"), end_time.strftime("%Y-%m-%d %H:%M")
- cutoff = end_time - offset
- before = frame[frame["ts"] <= cutoff]
- if len(before):
- start_equity = float(before["equity"].iloc[-1])
- after = frame[frame["ts"] > cutoff]
- out = pd.concat([pd.DataFrame([{"ts": cutoff, "equity": start_equity}]), after[["ts", "equity"]]], ignore_index=True)
- else:
- out = frame[["ts", "equity"]].copy()
- cutoff = pd.Timestamp(out["ts"].iloc[0])
- return out, int(cutoff.timestamp() * 1000), cutoff.strftime("%Y-%m-%d %H:%M"), end_time.strftime("%Y-%m-%d %H:%M")
- def horizon_rows(result: SegmentResult, frame: pd.DataFrame, first_ts: int, last_ts: int) -> list[dict[str, object]]:
- rows: list[dict[str, object]] = []
- for label, offset in HORIZONS:
- sliced_frame, start_ts, start_text, end_text = horizon_frame(frame, first_ts, last_ts, offset)
- trades = [trade for trade in result.trades if int(trade["exit_ts"]) >= start_ts]
- rows.append(
- {
- "horizon": label,
- "horizon_start": start_text,
- "horizon_end": end_text,
- **equity_metrics(sliced_frame, start_ts, last_ts),
- **trade_stats(trades),
- **exit_reason_counts(trades),
- }
- )
- return rows
- def worst_month(frame: pd.DataFrame) -> tuple[str, float]:
- monthly = frame.set_index("ts")["equity"].resample("ME").last().ffill().pct_change().dropna()
- if not len(monthly):
- return "", 0.0
- idx = monthly.idxmin()
- return idx.strftime("%Y-%m"), float(monthly.loc[idx])
- def build_variants() -> list[Variant]:
- bases = (
- (48, 960, 0.25, "both", "none", 0.006, 0.010),
- (48, 960, 0.25, "both", "none", 0.006, 0.012),
- (96, 960, 0.25, "both", "btc-up", 0.006, 0.012),
- (96, 960, 0.25, "both", "btc-up-momo", 0.006, 0.012),
- (96, 480, 0.15, "both", "none", 0.006, 0.010),
- (48, 960, 0.25, "long", "btc-up", 0.006, 0.010),
- )
- exits = (
- (2, 0.0015, 2, 0.0005, 1, 0.006, 0.0000, 0.006, 1, 0.0070, 1.40, 0.0, 1, 192),
- (2, 0.0025, 3, 0.0010, 1, 0.008, 0.0005, 0.007, 1, 0.0065, 1.30, 0.0, 1, 288),
- (3, 0.0035, 3, 0.0010, 2, 0.010, 0.0010, 0.008, 2, 0.0060, 1.25, 0.0, 1, 384),
- (3, 0.0045, 4, 0.0015, 2, 0.012, 0.0010, 0.010, 2, 0.0060, 1.20, 0.0, 1, 480),
- (2, 0.0020, 2, 0.0000, 1, 0.006, 0.0005, 0.005, 1, 0.0055, 1.15, 0.0, 1, 192),
- (4, 0.0050, 4, 0.0015, 2, 0.015, 0.0015, 0.012, 2, 0.0065, 1.35, 0.0, 1, 576),
- )
- variants: list[Variant] = []
- for band_length, lookback, quantile, side_mode, btc_filter, vol_cap, stop_loss in bases:
- for exit_spec in exits:
- variants.append(
- Variant(
- band_length=band_length,
- bandwidth_lookback=lookback,
- bandwidth_quantile=quantile,
- side_mode=side_mode,
- btc_filter=btc_filter,
- eth_vol_cap=vol_cap,
- cooldown_bars=24,
- stop_loss_pct=stop_loss,
- trend_momentum_bars=exit_spec[0],
- trend_middle_buffer_pct=exit_spec[1],
- trend_middle_confirm_bars=exit_spec[2],
- neutral_middle_buffer_pct=exit_spec[3],
- neutral_middle_confirm_bars=exit_spec[4],
- protect_trigger_pct=exit_spec[5],
- protect_lock_pct=exit_spec[6],
- protect_trail_giveback_pct=exit_spec[7],
- protect_middle_confirm_bars=exit_spec[8],
- fast_vol_pct=exit_spec[9],
- fast_bandwidth_ratio=exit_spec[10],
- fast_middle_buffer_pct=exit_spec[11],
- fast_middle_confirm_bars=exit_spec[12],
- max_hold_bars=exit_spec[13],
- )
- )
- return variants
- def format_cell(value: object) -> str:
- if isinstance(value, float):
- return f"{value:.6g}"
- return str(value).replace("|", "\\|")
- def markdown_table(frame: pd.DataFrame) -> str:
- columns = list(frame.columns)
- rows = [columns, ["---" for _ in columns]]
- for record in frame.to_dict("records"):
- rows.append([record[column] for column in columns])
- return "\n".join("| " + " | ".join(format_cell(value) for value in row) + " |" for row in rows)
- def write_report(*, summary: pd.DataFrame, horizon: pd.DataFrame, first_ts: int, last_ts: int, requested_years: float, command: str) -> str:
- primary = summary[summary["cost"] == PRIMARY_COST]
- top = primary.head(10)
- horizon_top = (
- horizon[horizon["cost"] == PRIMARY_COST]
- .sort_values(["horizon", "net_calmar", "net_annualized_return"], ascending=[True, False, False])
- .groupby("horizon", observed=True)
- .head(3)
- )
- lines = [
- "# ETH BB squeeze adaptive state-exit exploration",
- "",
- f"Run command: `{command}`",
- f"Requested years: {requested_years:g}",
- f"Actual continuous local history: `{_format_ts(first_ts)}` to `{_format_ts(last_ts)}`.",
- "",
- "State machine:",
- "- `trend`: ETH move remains aligned with the breakout and close stays on the favorable side of the BB middle; middle exit uses a wider buffer and more confirmations.",
- "- `protect`: trade reaches floating-profit trigger; a lock/trailing stop and faster middle exit protect profit.",
- "- `fast`: realized volatility or bandwidth expansion crosses the variant threshold; middle exit is immediate.",
- "- `neutral`: default state, between trend continuation and protection.",
- "",
- "Top 10 by maker_taker full-period Calmar:",
- markdown_table(
- top[
- [
- "name",
- "trades",
- "win_rate",
- "net_total_return",
- "net_annualized_return",
- "net_max_drawdown",
- "net_calmar",
- "profit_factor",
- "payoff_ratio",
- "avg_return_pct",
- "avg_mfe_pct",
- "protect_exits",
- "trend_middle_exits",
- "fast_middle_exits",
- "neutral_middle_exits",
- ]
- ]
- ),
- "",
- "Horizon leaders:",
- markdown_table(
- horizon_top[
- [
- "horizon",
- "name",
- "trades",
- "win_rate",
- "net_total_return",
- "net_annualized_return",
- "net_max_drawdown",
- "net_calmar",
- "profit_factor",
- "payoff_ratio",
- "protect_exits",
- "fast_middle_exits",
- ]
- ]
- ),
- ]
- return "\n".join(lines) + "\n"
- def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--bar", default=BAR)
- parser.add_argument("--years", type=float, default=YEARS)
- parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
- args = parser.parse_args()
- eth = _load_candles(ETH_SYMBOL, args.bar)
- btc = _load_candles(BTC_SYMBOL, args.bar)
- eth, btc = _align_pair(eth, btc)
- requested_bars = int(args.years * 365 * 24 * 60 / 15)
- eth = eth[-requested_bars:]
- btc = btc[-requested_bars:]
- summary_rows: list[dict[str, object]] = []
- horizon_rows_out: list[dict[str, object]] = []
- variants = build_variants()
- for index, variant in enumerate(variants, start=1):
- result, exit_counts = run_variant(eth, btc, variant)
- if not result.equity_curve:
- print(f"skip {index}/{len(variants)} {variant.name}", flush=True)
- continue
- stats = trade_stats(result.trades)
- reason_counts = exit_reason_counts(result.trades)
- for cost_name, cost in COSTS:
- frame = cost_equity_frame(result, cost)
- metrics = equity_metrics(frame, eth[0].ts, eth[-1].ts)
- month, month_return = worst_month(frame)
- row = {
- "family": "eth_adaptive_state_exit",
- "cost": cost_name,
- "symbol": ETH_SYMBOL,
- "signal_symbol": BTC_SYMBOL if variant.btc_filter != "none" else "",
- "bar": args.bar,
- "name": variant.name,
- "band_length": variant.band_length,
- "bandwidth_lookback": variant.bandwidth_lookback,
- "bandwidth_quantile": variant.bandwidth_quantile,
- "side_mode": variant.side_mode,
- "btc_filter": variant.btc_filter,
- "eth_vol_cap": variant.eth_vol_cap,
- "cooldown_bars": variant.cooldown_bars,
- "stop_loss_pct": variant.stop_loss_pct,
- "trend_momentum_bars": variant.trend_momentum_bars,
- "trend_middle_buffer_pct": variant.trend_middle_buffer_pct,
- "trend_middle_confirm_bars": variant.trend_middle_confirm_bars,
- "neutral_middle_buffer_pct": variant.neutral_middle_buffer_pct,
- "neutral_middle_confirm_bars": variant.neutral_middle_confirm_bars,
- "protect_trigger_pct": variant.protect_trigger_pct,
- "protect_lock_pct": variant.protect_lock_pct,
- "protect_trail_giveback_pct": variant.protect_trail_giveback_pct,
- "protect_middle_confirm_bars": variant.protect_middle_confirm_bars,
- "fast_vol_pct": variant.fast_vol_pct,
- "fast_bandwidth_ratio": variant.fast_bandwidth_ratio,
- "fast_middle_buffer_pct": variant.fast_middle_buffer_pct,
- "fast_middle_confirm_bars": variant.fast_middle_confirm_bars,
- "max_hold_bars": variant.max_hold_bars,
- "first_candle": _format_ts(eth[0].ts),
- "last_candle": _format_ts(eth[-1].ts),
- "years": (eth[-1].ts - eth[0].ts) / 86_400_000 / 365,
- "gross_total_return": result.total_return,
- "gross_max_drawdown_mark_to_market": result.max_drawdown,
- "worst_month": month,
- "worst_month_return": month_return,
- **stats,
- **reason_counts,
- **metrics,
- }
- summary_rows.append(row)
- for horizon_row in horizon_rows(result, frame, eth[0].ts, eth[-1].ts):
- horizon_rows_out.append(
- {
- "family": "eth_adaptive_state_exit",
- "cost": cost_name,
- "symbol": ETH_SYMBOL,
- "signal_symbol": BTC_SYMBOL if variant.btc_filter != "none" else "",
- "bar": args.bar,
- "name": variant.name,
- **horizon_row,
- }
- )
- print(f"done {index}/{len(variants)} {variant.name} exits={exit_counts}", flush=True)
- summary = pd.DataFrame(summary_rows).sort_values(
- ["cost", "net_calmar", "net_annualized_return", "profit_factor"],
- ascending=[True, False, False, False],
- )
- primary = summary[summary["cost"] == PRIMARY_COST]
- summary = pd.concat([primary, summary[summary["cost"] != PRIMARY_COST]], ignore_index=True)
- horizon = pd.DataFrame(horizon_rows_out)
- horizon["horizon"] = pd.Categorical(horizon["horizon"], categories=[label for label, _ in HORIZONS], ordered=True)
- horizon = horizon.sort_values(["cost", "horizon", "net_calmar", "net_annualized_return"], ascending=[True, True, False, False])
- args.output_dir.mkdir(parents=True, exist_ok=True)
- summary_path = args.output_dir / "eth-adaptive-state-exit-summary.csv"
- horizon_path = args.output_dir / "eth-adaptive-state-exit-horizon.csv"
- report_path = args.output_dir / "eth-adaptive-state-exit-report.md"
- summary.to_csv(summary_path, index=False)
- horizon.to_csv(horizon_path, index=False)
- command = f"rtk .venv/bin/python {Path(__file__).as_posix()} --bar {args.bar} --years {args.years}"
- report_path.write_text(
- write_report(summary=summary, horizon=horizon, first_ts=eth[0].ts, last_ts=eth[-1].ts, requested_years=args.years, command=command),
- encoding="utf-8",
- )
- print(primary.head(10).to_string(index=False))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|