| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657 |
- from __future__ import annotations
- import argparse
- import sys
- 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 = (
- ("3y", pd.DateOffset(years=3)),
- ("1y", pd.DateOffset(years=1)),
- ("6m", pd.DateOffset(months=6)),
- ("3m", pd.DateOffset(months=3)),
- )
- @dataclass(frozen=True)
- class Variant:
- band_length: int
- bandwidth_lookback: int
- bandwidth_quantile: float
- stop_loss_pct: float
- take_profit_pct: float | None
- extreme_take_profit_pct: float | None
- extreme_band_extension: float | None
- extreme_reentry_bars: int | None
- side_mode: str
- btc_filter: str
- eth_vol_cap: float | None
- dd_overlay: float | None
- cooldown_bars: int
- @property
- def name(self) -> str:
- tp = "none" if self.take_profit_pct is None else f"{self.take_profit_pct:g}"
- xtp = "none" if self.extreme_take_profit_pct is None else f"{self.extreme_take_profit_pct:g}"
- xband = "none" if self.extreme_band_extension is None else f"{self.extreme_band_extension:g}"
- tre = "none" if self.extreme_reentry_bars is None else str(self.extreme_reentry_bars)
- vol = "none" if self.eth_vol_cap is None else f"{self.eth_vol_cap:g}"
- dd = "none" if self.dd_overlay is None else f"{self.dd_overlay:g}"
- return (
- f"bb-squeeze-l{self.band_length}-bw{self.bandwidth_lookback}"
- f"-q{self.bandwidth_quantile:g}-sl{self.stop_loss_pct:g}-tp{tp}"
- f"-xtp{xtp}-xb{xband}-tre{tre}"
- f"-{self.side_mode}-{self.btc_filter}-vc{vol}-dd{dd}-cd{self.cooldown_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,
- ) -> 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_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,
- }
- )
- exits.append({"ts": candle.ts, "price": exit_price, "side": position["side"]})
- return exit_equity, pnl > 0.0
- def run_variant(eth: list[Candle], btc: list[Candle], variant: Variant) -> SegmentResult:
- 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 = (middle_series + 2.0 * stdev_series).tolist()
- lower = (middle_series - 2.0 * stdev_series).tolist()
- middle = middle_series.tolist()
- bandwidth = ((pd.Series(upper) - pd.Series(lower)) / 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()
- 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 = False
- reentry_side: str | None = None
- reentry_until = -1
- cooldown_until = -1
- for index in range(warmup_bars, len(eth)):
- candle = eth[index]
- if pending_exit and position is not None:
- equity, won = _close_position(trades=trades, exits=exits, position=position, candle=candle, exit_price=candle.open)
- wins += int(won)
- position = None
- pending_exit = False
- cooldown_until = index + variant.cooldown_bars
- if pending_entry_side is not None and position is None and equity > 0.0:
- position = {
- "side": pending_entry_side,
- "entry_time": candle.ts,
- "entry_price": candle.open,
- "margin_used": equity,
- "stop_price": candle.open * (1.0 - variant.stop_loss_pct if pending_entry_side == "long" else 1.0 + variant.stop_loss_pct),
- "take_price": None
- if variant.take_profit_pct is None
- else candle.open * (1.0 + variant.take_profit_pct if pending_entry_side == "long" else 1.0 - variant.take_profit_pct),
- "extreme_take_price": None
- if variant.extreme_take_profit_pct is None
- else candle.open * (1.0 + variant.extreme_take_profit_pct if pending_entry_side == "long" else 1.0 - variant.extreme_take_profit_pct),
- }
- entries.append({"ts": candle.ts, "price": candle.open, "side": pending_entry_side})
- pending_entry_side = None
- current_equity = equity
- if position is not None:
- side = str(position["side"])
- stop_hit = (side == "long" and candle.low <= float(position["stop_price"])) or (
- side == "short" and candle.high >= float(position["stop_price"])
- )
- take_price = position["take_price"]
- take_hit = take_price is not None and (
- (side == "long" and candle.high >= float(take_price)) or (side == "short" and candle.low <= float(take_price))
- )
- extreme_take_price = position["extreme_take_price"]
- extreme_take_hit = extreme_take_price is not None and (
- (side == "long" and candle.high >= float(extreme_take_price)) or (
- side == "short" and candle.low <= float(extreme_take_price)
- )
- )
- if stop_hit or take_hit or extreme_take_hit:
- exit_side = side
- if stop_hit:
- exit_price = float(position["stop_price"])
- elif take_hit:
- exit_price = float(take_price)
- else:
- exit_price = float(extreme_take_price)
- equity, won = _close_position(trades=trades, exits=exits, position=position, candle=candle, exit_price=exit_price)
- wins += int(won)
- current_equity = equity
- position = None
- if extreme_take_hit and not stop_hit and not take_hit and variant.extreme_reentry_bars is not None:
- reentry_side = exit_side
- reentry_until = index + variant.extreme_reentry_bars
- else:
- 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])
- if any(value != value for value in values):
- continue
- if position is None and reentry_side is not None:
- if index > reentry_until:
- reentry_side = None
- elif (reentry_side == "long" and float(middle[index]) < candle.close <= float(upper[index])) or (
- reentry_side == "short" and float(lower[index]) <= candle.close < float(middle[index])
- ):
- pending_entry_side = reentry_side
- reentry_side = None
- continue
- if position is not None:
- middle_exit = (position["side"] == "long" and candle.close < float(middle[index])) or (
- position["side"] == "short" and candle.close > float(middle[index])
- )
- extreme_band_exit = False
- if variant.extreme_band_extension is not None:
- band_half_width = float(upper[index]) - float(middle[index])
- long_extreme = float(upper[index]) + band_half_width * variant.extreme_band_extension
- short_extreme = float(lower[index]) - band_half_width * variant.extreme_band_extension
- extreme_band_exit = (position["side"] == "long" and candle.close >= long_extreme) or (
- position["side"] == "short" and candle.close <= short_extreme
- )
- if middle_exit or extreme_band_exit:
- pending_exit = True
- continue
- if 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.dd_overlay is not None and (peak_equity - current_equity) / peak_equity > variant.dd_overlay:
- 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)
- return 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,
- )
- 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(str(trade["exit_time"]), 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 horizon_rows(frame: pd.DataFrame, last_ts: int) -> list[dict[str, object]]:
- rows: list[dict[str, object]] = []
- end_time = pd.to_datetime(last_ts, unit="ms", utc=True)
- for label, offset in HORIZONS:
- cutoff = end_time - offset
- before = frame[frame["ts"] <= cutoff]
- if len(before):
- start_equity = float(before["equity"].iloc[-1])
- start_time = cutoff
- after = frame[frame["ts"] > cutoff]
- horizon_frame = pd.concat([pd.DataFrame([{"ts": cutoff, "equity": start_equity}]), after[["ts", "equity"]]], ignore_index=True)
- else:
- horizon_frame = frame[["ts", "equity"]].copy()
- start_time = pd.Timestamp(horizon_frame["ts"].iloc[0])
- rows.append(
- {
- "horizon": label,
- "horizon_start": start_time.strftime("%Y-%m-%d %H:%M"),
- "horizon_end": end_time.strftime("%Y-%m-%d %H:%M"),
- **equity_metrics(horizon_frame, int(start_time.timestamp() * 1000), last_ts),
- }
- )
- 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 = (
- (96, 480, 0.15),
- (96, 960, 0.25),
- (48, 960, 0.25),
- (48, 480, 0.15),
- )
- variants: list[Variant] = []
- for length, bandwidth_lookback, quantile in bases:
- for side_mode in ("long", "both"):
- for btc_filter in ("none", "btc-up", "btc-up-momo"):
- for eth_vol_cap in (None, 0.006):
- for dd_overlay in (None, 0.25):
- for stop_loss_pct, take_profit_pct in (
- (0.006, 0.012),
- (0.008, 0.018),
- (0.010, None),
- ):
- for extreme_take_profit_pct, extreme_band_extension, extreme_reentry_bars in (
- (None, None, None),
- (0.025, None, None),
- (0.035, None, None),
- (0.025, None, 96),
- (0.035, None, 96),
- (None, 0.75, None),
- (0.025, 0.75, None),
- ):
- variants.append(
- Variant(
- band_length=length,
- bandwidth_lookback=bandwidth_lookback,
- bandwidth_quantile=quantile,
- stop_loss_pct=stop_loss_pct,
- take_profit_pct=take_profit_pct,
- extreme_take_profit_pct=extreme_take_profit_pct,
- extreme_band_extension=extreme_band_extension,
- extreme_reentry_bars=extreme_reentry_bars,
- side_mode=side_mode,
- btc_filter=btc_filter,
- eth_vol_cap=eth_vol_cap,
- dd_overlay=dd_overlay,
- cooldown_bars=24,
- )
- )
- 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,
- output_files: list[Path],
- command: str,
- first_ts: int,
- last_ts: int,
- requested_years: float,
- ) -> str:
- primary = summary[summary["cost"] == PRIMARY_COST]
- top_calmar = primary.head(10)
- top_worst_month = primary.sort_values(
- ["worst_month_return", "net_calmar", "net_annualized_return"],
- ascending=[False, False, False],
- ).head(10)
- acceptable = primary[(primary["net_max_drawdown"] <= 0.45) & (primary["worst_month_return"] >= -0.25) & (primary["net_calmar"] > 1.0)]
- best = primary.iloc[0] if len(primary) else None
- 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)
- )
- verdict = (
- "Yes: at least one variant met MDD <= 45%, worst month >= -25%, and Calmar > 1.0."
- if len(acceptable)
- else "No: this run did not find a BB squeeze variant with acceptable drawdown under MDD <= 45% and worst month >= -25%."
- )
- lines = [
- "# ETH BB squeeze breakout risk 10y 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)}`.",
- "",
- "Output files:",
- *[f"- `{path}`" for path in output_files],
- "",
- "Cost model: maker_taker is the primary ranking cost; maker_maker and taker_taker are included for sensitivity.",
- "Objective: reduce drawdown, not maximize total return.",
- "",
- "Top 10 by Calmar:",
- markdown_table(
- top_calmar[
- [
- "name",
- "trades",
- "net_total_return",
- "net_annualized_return",
- "net_max_drawdown",
- "net_calmar",
- "worst_month",
- "worst_month_return",
- ]
- ]
- ),
- "",
- "Top 10 by worst month:",
- markdown_table(
- top_worst_month[
- [
- "name",
- "trades",
- "net_total_return",
- "net_annualized_return",
- "net_max_drawdown",
- "net_calmar",
- "worst_month",
- "worst_month_return",
- ]
- ]
- ),
- "",
- "Recent horizon leaders:",
- markdown_table(
- horizon_top[
- [
- "horizon",
- "name",
- "trades",
- "net_total_return",
- "net_annualized_return",
- "net_max_drawdown",
- "net_calmar",
- ]
- ]
- ),
- "",
- "Verdict:",
- f"- {verdict}",
- ]
- if best is not None:
- lines.append(
- 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']}."
- )
- if len(acceptable):
- lines.extend(
- [
- "",
- "Acceptable drawdown candidates:",
- markdown_table(
- acceptable.head(10)[
- [
- "name",
- "trades",
- "net_annualized_return",
- "net_max_drawdown",
- "net_calmar",
- "worst_month_return",
- ]
- ]
- ),
- ]
- )
- 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_output_rows: list[dict[str, object]] = []
- variants = build_variants()
- for index, variant in enumerate(variants, start=1):
- result = run_variant(eth, btc, variant)
- if not result.equity_curve:
- print(f"skip {index}/{len(variants)} {variant.name}")
- continue
- 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": "bb_squeeze_breakout_risk",
- "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,
- "stop_loss_pct": variant.stop_loss_pct,
- "take_profit_pct": variant.take_profit_pct,
- "extreme_take_profit_pct": variant.extreme_take_profit_pct,
- "extreme_band_extension": variant.extreme_band_extension,
- "extreme_reentry_bars": variant.extreme_reentry_bars,
- "side_mode": variant.side_mode,
- "btc_filter": variant.btc_filter,
- "eth_vol_cap": variant.eth_vol_cap,
- "dd_overlay": variant.dd_overlay,
- "cooldown_bars": variant.cooldown_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,
- "trades": result.trade_count,
- "gross_total_return": result.total_return,
- "gross_max_drawdown_mark_to_market": result.max_drawdown,
- "worst_month": month,
- "worst_month_return": month_return,
- **metrics,
- }
- summary_rows.append(row)
- for horizon_row in horizon_rows(frame, eth[-1].ts):
- horizon_output_rows.append(
- {
- "family": "bb_squeeze_breakout_risk",
- "cost": cost_name,
- "symbol": ETH_SYMBOL,
- "signal_symbol": BTC_SYMBOL if variant.btc_filter != "none" else "",
- "bar": args.bar,
- "name": variant.name,
- "trades": result.trade_count,
- **horizon_row,
- }
- )
- print(f"done {index}/{len(variants)} {variant.name}")
- summary = pd.DataFrame(summary_rows).sort_values(
- ["cost", "net_calmar", "worst_month_return", "net_annualized_return"],
- 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_output_rows)
- 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)
- prefix = "eth-bb-squeeze-risk-10y"
- summary_path = args.output_dir / f"{prefix}-summary.csv"
- horizon_path = args.output_dir / f"{prefix}-horizon.csv"
- top_calmar_path = args.output_dir / f"{prefix}-top10-calmar.csv"
- top_worst_month_path = args.output_dir / f"{prefix}-top10-worst-month.csv"
- report_path = args.output_dir / f"{prefix}-report.md"
- output_files = [summary_path, horizon_path, top_calmar_path, top_worst_month_path, report_path]
- summary.to_csv(summary_path, index=False)
- horizon.to_csv(horizon_path, index=False)
- primary.head(10).to_csv(top_calmar_path, index=False)
- primary.sort_values(["worst_month_return", "net_calmar", "net_annualized_return"], ascending=[False, False, False]).head(10).to_csv(
- top_worst_month_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,
- output_files=output_files,
- command=command,
- first_ts=eth[0].ts,
- last_ts=eth[-1].ts,
- requested_years=args.years,
- ),
- encoding="utf-8",
- )
- print(primary.head(10).to_string(index=False))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|