feat: exp14 portfolio sim + exp15 grid search (ws×leverage)
exp14: full portfolio simulation with $114, equal vs optimized allocation exp15: grid search ws=[32,48,64,96,128] × leverage=[1,2] per asset → Sharpe-optimal params found and deployed in config Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
"""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:
|
||||
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}")
|
||||
Reference in New Issue
Block a user