Files
remizov-trader/experiments/common/metrics.py
T
anorandClaude Opus 4.6 2601152afe fix: Sharpe ratio — daily returns вместо trade count + memory leak fix
Sharpe считался через sqrt(trades_per_year), что завышало метрику в ~2x.
Исправлено на daily returns + sqrt(252) во всех бэктест скриптах.
Утечка памяти: добавлен del tensors в model.train() и evaluate.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 13:39:50 +10:00

110 lines
4.1 KiB
Python

"""Shared metrics and comparison utilities for experiments."""
import json
from datetime import datetime
from pathlib import Path
import numpy as np
def compute_metrics(trades: list[dict], initial_capital: float,
years: float) -> dict:
"""Compute standard trading metrics from trade list.
Each trade must have: pnl_net, equity_at_entry.
"""
if not trades:
return {"trades": 0}
pnls = [t["pnl_net"] for t in trades]
wins = [t for t in trades if t["pnl_net"] > 0]
losses = [t for t in trades if t["pnl_net"] <= 0]
total_pnl = sum(pnls)
wr = len(wins) / len(trades) * 100
if len(trades) > 1 and years > 0:
# Daily returns method (proper annualization)
if trades[0].get("entry_idx") is not None:
first_idx = min(t["entry_idx"] for t in trades)
last_idx = max(t["entry_idx"] for t in trades)
bars_per_day = 6 # 4h bars
n_days = max((last_idx - first_idx) // bars_per_day, 1)
daily_pnl = np.zeros(n_days)
for t in trades:
day = min((t["entry_idx"] - first_idx) // bars_per_day, n_days - 1)
daily_pnl[day] += t["pnl_net"]
daily_ret = daily_pnl / initial_capital
sharpe = float(
np.mean(daily_ret) / np.std(daily_ret) * np.sqrt(252)
) if np.std(daily_ret) > 0 else 0.0
else:
# Fallback: per-trade returns (less accurate)
returns = np.array([t["pnl_net"] / t["equity_at_entry"] for t in trades])
tpy = len(trades) / years
sharpe = float(
np.mean(returns) / np.std(returns) * np.sqrt(tpy)
) if np.std(returns) > 0 else 0.0
else:
sharpe = 0.0
return {
"trades": len(trades),
"wins": len(wins),
"losses": len(losses),
"wr": round(wr, 1),
"total_pnl": round(total_pnl, 2),
"total_ret": round(total_pnl / initial_capital * 100, 1),
"sharpe": round(sharpe, 2),
"avg_win": round(np.mean([t["pnl_net"] for t in wins]), 2) if wins else 0,
"avg_loss": round(np.mean([t["pnl_net"] for t in losses]), 2) if losses else 0,
}
def save_results(results: dict, results_dir: str | Path, name: str = "") -> Path:
"""Save experiment results to JSON."""
results_dir = Path(results_dir)
results_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
label = f"_{name}" if name else ""
path = results_dir / f"results{label}_{ts}.json"
path.write_text(json.dumps(results, indent=2, default=str))
return path
def compare_results(baseline: dict, experiment: dict, name: str = "") -> str:
"""Format comparison table between baseline and experiment."""
lines = []
header = f" {'Metric':<14s} {'Baseline':>10s} {'Experiment':>10s} {'Delta':>10s}"
lines.append(f"\n{'='*50}")
if name:
lines.append(f" {name}")
lines.append(header)
lines.append(f" {'-'*44}")
for key in ["trades", "wr", "sharpe", "total_pnl", "total_ret", "avg_win", "avg_loss"]:
bv = baseline.get(key, 0)
ev = experiment.get(key, 0)
delta = ev - bv
sign = "+" if delta > 0 else ""
if key in ("wr", "total_ret"):
lines.append(f" {key:<14s} {bv:>9.1f}% {ev:>9.1f}% {sign}{delta:>8.1f}%")
elif key in ("total_pnl", "avg_win", "avg_loss"):
lines.append(f" {key:<14s} ${bv:>9.2f} ${ev:>9.2f} {sign}${delta:>7.2f}")
elif key == "sharpe":
lines.append(f" {key:<14s} {bv:>10.2f} {ev:>10.2f} {sign}{delta:>9.2f}")
else:
lines.append(f" {key:<14s} {bv:>10d} {ev:>10d} {sign}{delta:>9d}")
lines.append(f"{'='*50}")
return "\n".join(lines)
def print_metrics(m: dict, title: str = ""):
"""Print metrics in a formatted block."""
if title:
print(f"\n {title}")
print(f" Trades: {m['trades']} | WR: {m['wr']}% | Sharpe: {m['sharpe']}")
print(f" PnL: ${m['total_pnl']:+,.2f} ({m['total_ret']:+.1f}%)")
print(f" Avg win: ${m['avg_win']:+,.2f} | Avg loss: ${m['avg_loss']:+,.2f}")