From ff51c5e5cfa635ff900a21bb7cfc323f67e0f671 Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 9 Mar 2026 23:38:49 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20exp14=20portfolio=20sim=20+=20exp15=20g?= =?UTF-8?q?rid=20search=20(ws=C3=97leverage)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- experiments/common/__init__.py | 0 experiments/common/metrics.py | 93 ++ ...s_exp14_portfolio_sim_20260309_225311.json | 218 ++++ experiments/exp14_portfolio_sim/run.py | 373 ++++++ ...lts_exp15_grid_search_20260309_231355.json | 1150 +++++++++++++++++ ...exp15b_sharpe_optimal_20260309_232545.json | 323 +++++ experiments/exp15_grid_search/run.py | 549 ++++++++ .../exp15_grid_search/run_sharpe_optimal.py | 150 +++ 8 files changed, 2856 insertions(+) create mode 100644 experiments/common/__init__.py create mode 100644 experiments/common/metrics.py create mode 100644 experiments/exp14_portfolio_sim/results/results_exp14_portfolio_sim_20260309_225311.json create mode 100644 experiments/exp14_portfolio_sim/run.py create mode 100644 experiments/exp15_grid_search/results/results_exp15_grid_search_20260309_231355.json create mode 100644 experiments/exp15_grid_search/results/results_exp15b_sharpe_optimal_20260309_232545.json create mode 100644 experiments/exp15_grid_search/run.py create mode 100644 experiments/exp15_grid_search/run_sharpe_optimal.py diff --git a/experiments/common/__init__.py b/experiments/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/experiments/common/metrics.py b/experiments/common/metrics.py new file mode 100644 index 0000000..7aa94df --- /dev/null +++ b/experiments/common/metrics.py @@ -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}") diff --git a/experiments/exp14_portfolio_sim/results/results_exp14_portfolio_sim_20260309_225311.json b/experiments/exp14_portfolio_sim/results/results_exp14_portfolio_sim_20260309_225311.json new file mode 100644 index 0000000..04b668c --- /dev/null +++ b/experiments/exp14_portfolio_sim/results/results_exp14_portfolio_sim_20260309_225311.json @@ -0,0 +1,218 @@ +{ + "CURRENT (equal, ws=64, 2x)": { + "config_name": "CURRENT (equal, ws=64, 2x)", + "total_capital": 114.0, + "final_equity": 3587.14, + "total_pnl": 3473.14, + "total_ret": 3046.6, + "total_trades": 2605, + "asset_stats": { + "ETH-USD": { + "trades": 572, + "wins": 281, + "wr": 49.1, + "pnl": 507.92, + "sharpe": 3.02, + "weight": 0.14285714285714285, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 524.2, + "monthly_pnl": 22.21, + "years": 1.91 + }, + "SOL-USD": { + "trades": 583, + "wins": 267, + "wr": 45.8, + "pnl": 274.75, + "sharpe": 2.17, + "weight": 0.14285714285714285, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 291.04, + "monthly_pnl": 12.02, + "years": 1.91 + }, + "BTC-USD": { + "trades": 310, + "wins": 144, + "wr": 46.5, + "pnl": 102.29, + "sharpe": 2.36, + "weight": 0.14285714285714285, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 118.58, + "monthly_pnl": 4.51, + "years": 1.89 + }, + "DOGE-USD": { + "trades": 281, + "wins": 146, + "wr": 52.0, + "pnl": 1208.26, + "sharpe": 2.89, + "weight": 0.14285714285714285, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 1224.55, + "monthly_pnl": 53.25, + "years": 1.89 + }, + "ADA-USD": { + "trades": 285, + "wins": 143, + "wr": 50.2, + "pnl": 785.9, + "sharpe": 2.78, + "weight": 0.14285714285714285, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 802.19, + "monthly_pnl": 34.63, + "years": 1.89 + }, + "XRP-USD": { + "trades": 296, + "wins": 148, + "wr": 50.0, + "pnl": 385.59, + "sharpe": 2.49, + "weight": 0.14285714285714285, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 401.88, + "monthly_pnl": 16.99, + "years": 1.89 + }, + "DOT-USD": { + "trades": 278, + "wins": 133, + "wr": 47.8, + "pnl": 208.43, + "sharpe": 1.93, + "weight": 0.14285714285714285, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 224.71, + "monthly_pnl": 9.19, + "years": 1.89 + } + } + }, + "OPTIMIZED (Sharpe/DD weights, optimal ws, per-asset lev)": { + "config_name": "OPTIMIZED (Sharpe/DD weights, optimal ws, per-asset lev)", + "total_capital": 114.0, + "final_equity": 4634.99, + "total_pnl": 4520.99, + "total_ret": 3965.8, + "total_trades": 2629, + "asset_stats": { + "ETH-USD": { + "trades": 604, + "wins": 290, + "wr": 48.0, + "pnl": 793.42, + "sharpe": 2.65, + "weight": 0.275, + "ws": 128, + "leverage": 2, + "initial": 31.35, + "final": 824.77, + "monthly_pnl": 34.91, + "years": 1.89 + }, + "SOL-USD": { + "trades": 595, + "wins": 281, + "wr": 47.2, + "pnl": 1451.71, + "sharpe": 3.11, + "weight": 0.101, + "ws": 128, + "leverage": 2, + "initial": 11.51, + "final": 1463.22, + "monthly_pnl": 63.87, + "years": 1.89 + }, + "BTC-USD": { + "trades": 290, + "wins": 135, + "wr": 46.6, + "pnl": 34.03, + "sharpe": 1.49, + "weight": 0.151, + "ws": 48, + "leverage": 2, + "initial": 17.21, + "final": 51.24, + "monthly_pnl": 1.49, + "years": 1.9 + }, + "DOGE-USD": { + "trades": 281, + "wins": 146, + "wr": 52.0, + "pnl": 1361.71, + "sharpe": 2.89, + "weight": 0.161, + "ws": 64, + "leverage": 2, + "initial": 18.35, + "final": 1380.06, + "monthly_pnl": 60.01, + "years": 1.89 + }, + "ADA-USD": { + "trades": 285, + "wins": 143, + "wr": 50.2, + "pnl": 682.16, + "sharpe": 2.78, + "weight": 0.124, + "ws": 64, + "leverage": 2, + "initial": 14.14, + "final": 696.3, + "monthly_pnl": 30.06, + "years": 1.89 + }, + "XRP-USD": { + "trades": 296, + "wins": 148, + "wr": 50.0, + "pnl": 44.76, + "sharpe": 2.49, + "weight": 0.083, + "ws": 64, + "leverage": 1, + "initial": 9.46, + "final": 54.22, + "monthly_pnl": 1.97, + "years": 1.89 + }, + "DOT-USD": { + "trades": 278, + "wins": 133, + "wr": 47.8, + "pnl": 153.19, + "sharpe": 1.93, + "weight": 0.105, + "ws": 64, + "leverage": 2, + "initial": 11.97, + "final": 165.16, + "monthly_pnl": 6.75, + "years": 1.89 + } + } + } +} \ No newline at end of file diff --git a/experiments/exp14_portfolio_sim/run.py b/experiments/exp14_portfolio_sim/run.py new file mode 100644 index 0000000..c896425 --- /dev/null +++ b/experiments/exp14_portfolio_sim/run.py @@ -0,0 +1,373 @@ +"""Exp14: Full portfolio simulation with $114 capital. + +Tests risk-adjusted allocation (Sharpe/DD weights), optimal window sizes, +per-asset leverage. Position value = total_equity × weight (no cap). +Compares vs equal allocation baseline. +""" +import json +import sys +import traceback +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) +sys.path.insert(0, str(Path(__file__).parent.parent)) + +import numpy as np +import torch + +from remizov_trader.core import model as model_mod, signals, risk +from remizov_trader.config import ModelConfig, RiskConfig +from common.metrics import compute_metrics, save_results + +TOTAL_CAPITAL = 114.0 +K = 2 +CORR_THRESH = 0.5 +TRAILING_STOP = True +TRAIN_RATIO = 0.3 + +# Correlation groups — prevent same-direction positions in correlated assets +CORRELATED_GROUPS = [ + {"BTC-USD", "ETH-USD"}, + {"ADA-USD", "DOT-USD", "XRP-USD"}, +] + +# Config A: CURRENT (equal allocation, ws=64, leverage=2x) +CONFIG_CURRENT = { + "name": "CURRENT (equal, ws=64, 2x)", + "assets": [ + {"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "weight": 1/7, "leverage": 2}, + {"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 64, "weight": 1/7, "leverage": 2}, + {"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 64, "weight": 1/7, "leverage": 2}, + {"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 64, "weight": 1/7, "leverage": 2}, + {"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "weight": 1/7, "leverage": 2}, + {"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "weight": 1/7, "leverage": 2}, + {"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 64, "weight": 1/7, "leverage": 2}, + ], +} + +# Config B: OPTIMIZED (risk-adjusted weights, optimal ws, per-asset leverage) +CONFIG_OPTIMIZED = { + "name": "OPTIMIZED (Sharpe/DD weights, optimal ws, per-asset lev)", + "assets": [ + {"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 128, "weight": 0.275, "leverage": 2}, + {"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "weight": 0.101, "leverage": 2}, + {"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 48, "weight": 0.151, "leverage": 2}, + {"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 64, "weight": 0.161, "leverage": 2}, + {"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "weight": 0.124, "leverage": 2}, + {"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "weight": 0.083, "leverage": 1}, + {"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 64, "weight": 0.105, "leverage": 2}, + ], +} + + +def train_model(prices, ws): + """Train model and return (model, test_data).""" + model_cfg = ModelConfig( + window_size=ws, n_steps=20, total_time=0.5, + shift=7, epochs=200, finetune_epochs=50, lr=0.003, + ) + data = signals.prepare_windows(prices, ws, model_cfg.shift) + if len(data) < 30: + return None, None, None + + n_train = max(int(len(data) * TRAIN_RATIO), 20) + train_data = data[:n_train] + test_data = data[n_train:] + + torch.manual_seed(42) + np.random.seed(42) + mdl = model_mod.create_model(model_cfg) + windows = np.array([d["norm_input"] for d in train_data]) + targets = np.array([d["norm_target"] for d in train_data]) + model_mod.train(mdl, windows, targets, 200, 0.003) + + return mdl, test_data, model_cfg + + +def run_portfolio(config, price_cache): + """Simulate full portfolio with shared equity and correlation groups.""" + assets = config["assets"] + shift = 7 + + # Train all models + models = {} + test_data_map = {} + model_cfgs = {} + for a in assets: + ticker = a["ticker"] + if ticker not in price_cache: + continue + prices, dates, tf = price_cache[ticker] + mdl, td, mcfg = train_model(prices, a["ws"]) + if mdl is None: + continue + models[ticker] = mdl + test_data_map[ticker] = td + model_cfgs[ticker] = mcfg + + # Find common test period (bar indices overlap) + # For simplicity: simulate each asset independently but with shared equity + total_equity = TOTAL_CAPITAL + peak_equity = TOTAL_CAPITAL + max_drawdown = 0.0 + all_trades = [] + positions = {} # ticker -> position dict + equity_curve = [TOTAL_CAPITAL] + + # Build unified timeline: collect all test bar events sorted by price_idx + # Since assets have different TFs, we process each asset's test data independently + # but position sizing uses shared total_equity × weight + + per_asset_trades = {a["ticker"]: [] for a in assets} + per_asset_equity = {a["ticker"]: TOTAL_CAPITAL * a["weight"] for a in assets} + + for a in assets: + ticker = a["ticker"] + if ticker not in models: + continue + + prices, dates, tf = price_cache[ticker] + mdl = models[ticker] + td = test_data_map[ticker] + ws = a["ws"] + weight = a["weight"] + leverage = a["leverage"] + position = None + + for d in td: + price_idx = d["price_idx"] + current_price = float(prices[price_idx]) + + # Check open position + if position is not None: + p = position + if TRAILING_STOP: + p["best_price"], p["stop_price"] = risk.update_trailing_stop( + current_price, p["best_price"], p["stop_price"], + p["stop_dist"], p["direction"]) + stopped = risk.is_stopped(current_price, p["stop_price"], p["direction"]) + bars_held = price_idx - p["entry_bar"] + if stopped or bars_held >= (shift - p["k_used"]): + exit_price = p["stop_price"] if stopped else current_price + pnl_net, _ = risk.calculate_pnl( + p["entry_price"], exit_price, p["direction"], + p["pos_size"], p["pos_value"]) + per_asset_equity[ticker] += pnl_net + per_asset_trades[ticker].append({ + "pnl_net": pnl_net, + "equity_at_entry": p["equity_at_entry"], + }) + all_trades.append({ + "ticker": ticker, + "pnl_net": pnl_net, + "equity_at_entry": p["equity_at_entry"], + }) + position = None + + if position is None and price_idx >= ws + K: + w = prices[price_idx - ws - K:price_idx - K].copy() + confirm = prices[price_idx - K:price_idx].copy() + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + norm_input = (w - mu) / std + pred = model_mod.predict(mdl, norm_input) + pred_new = pred[-shift:] + corr, confirmed = signals.check_shape_confirmation( + pred_new, confirm, mu, std, K, CORR_THRESH) + + if confirmed: + direction = signals.get_direction(pred_new, K) + if direction is not None: + # Position value = asset equity × leverage (no cap) + asset_eq = per_asset_equity[ticker] + pos_value = asset_eq * leverage + if pos_value < 1.0: + continue + pos_size = pos_value / current_price + k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K) + atr = risk.compute_atr(prices, price_idx) + stop_dist = max(atr * stop_mult, current_price * 0.005) + position = { + "direction": direction, + "entry_price": current_price, + "stop_price": current_price - direction * stop_dist, + "stop_dist": stop_dist, + "best_price": current_price, + "pos_size": pos_size, + "pos_value": pos_value, + "entry_bar": price_idx, + "k_used": k_adj, + "equity_at_entry": asset_eq, + } + + # Close remaining position + if position is not None: + last_price = float(prices[-1]) + pnl_net, _ = risk.calculate_pnl( + position["entry_price"], last_price, position["direction"], + position["pos_size"], position["pos_value"]) + per_asset_equity[ticker] += pnl_net + per_asset_trades[ticker].append({ + "pnl_net": pnl_net, + "equity_at_entry": position["equity_at_entry"], + }) + all_trades.append({ + "ticker": ticker, + "pnl_net": pnl_net, + "equity_at_entry": position["equity_at_entry"], + }) + + # Final equity + final_equity = sum(per_asset_equity.values()) + total_pnl = final_equity - TOTAL_CAPITAL + + # Per-asset stats + asset_stats = {} + for a in assets: + ticker = a["ticker"] + trades = per_asset_trades[ticker] + if not trades: + continue + wins = [t for t in trades if t["pnl_net"] > 0] + pnl = sum(t["pnl_net"] for t in trades) + # Estimate years from test data + if ticker in test_data_map and test_data_map[ticker]: + td = test_data_map[ticker] + fb, lb = td[0]["price_idx"], td[-1]["price_idx"] + tf_hours = {"2h": 2, "4h": 4} + bpd = 24 / tf_hours.get(a["tf"], 4) + years = (lb - fb) / (365.25 * bpd) + else: + years = 1.0 + + 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 + else: + sharpe = 0 + + months = years * 12 + asset_stats[ticker] = { + "trades": len(trades), + "wins": len(wins), + "wr": round(len(wins) / len(trades) * 100, 1) if trades else 0, + "pnl": round(pnl, 2), + "sharpe": round(sharpe, 2), + "weight": a["weight"], + "ws": a["ws"], + "leverage": a["leverage"], + "initial": round(TOTAL_CAPITAL * a["weight"], 2), + "final": round(per_asset_equity[ticker], 2), + "monthly_pnl": round(pnl / months, 2) if months > 0 else 0, + "years": round(years, 2), + } + + return { + "config_name": config["name"], + "total_capital": TOTAL_CAPITAL, + "final_equity": round(final_equity, 2), + "total_pnl": round(total_pnl, 2), + "total_ret": round(total_pnl / TOTAL_CAPITAL * 100, 1), + "total_trades": len(all_trades), + "asset_stats": asset_stats, + } + + +def print_result(result): + """Print portfolio simulation results.""" + print(f"\n{'='*80}") + print(f" {result['config_name']}") + print(f"{'='*80}") + print(f" Capital: ${result['total_capital']:.0f} → ${result['final_equity']:.2f} " + f"(PnL: ${result['total_pnl']:+.2f}, {result['total_ret']:+.1f}%)") + print(f" Total trades: {result['total_trades']}") + + stats = result["asset_stats"] + if not stats: + print(" No trades!") + return + + print(f"\n {'Asset':<10s} {'WS':>4s} {'Lev':>4s} {'Wt%':>5s} " + f"{'Init$':>7s} {'Final$':>8s} {'PnL$':>9s} " + f"{'Sharpe':>7s} {'WR%':>5s} {'Trds':>5s} {'$/mo':>8s}") + print(f" {'-'*78}") + + sorted_stats = sorted(stats.items(), key=lambda x: x[1]["sharpe"], reverse=True) + for ticker, s in sorted_stats: + print(f" {ticker:<10s} {s['ws']:>4d} {s['leverage']:>3d}x {s['weight']*100:>4.1f}% " + f"${s['initial']:>6.2f} ${s['final']:>7.2f} ${s['pnl']:>+8.2f} " + f"{s['sharpe']:>7.2f} {s['wr']:>4.1f}% {s['trades']:>5d} ${s['monthly_pnl']:>+7.2f}") + + total_monthly = sum(s["monthly_pnl"] for s in stats.values()) + print(f" {'-'*78}") + print(f" {'TOTAL':<10s} {'':>4s} {'':>4s} {'100%':>5s} " + f"${result['total_capital']:>6.0f} ${result['final_equity']:>7.2f} " + f"${result['total_pnl']:>+8.2f} " + f"{'':>7s} {'':>5s} {result['total_trades']:>5d} ${total_monthly:>+7.2f}") + + +def main(): + results_dir = Path(__file__).parent / "results" + + # Fetch all data + all_tickers = set() + for cfg in [CONFIG_CURRENT, CONFIG_OPTIMIZED]: + for a in cfg["assets"]: + all_tickers.add((a["symbol"], a["ticker"], a["tf"])) + + price_cache = {} + for symbol, ticker, tf in sorted(all_tickers): + if ticker in price_cache: + continue + print(f"Fetching {ticker} ({tf})...", end=" ", flush=True) + try: + prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max") + if prices is not None: + price_cache[ticker] = (prices, dates, tf) + print(f"{len(prices)} bars") + else: + print("SKIP") + except Exception as e: + print(f"ERROR: {e}") + + # Run both configs + results = {} + for cfg in [CONFIG_CURRENT, CONFIG_OPTIMIZED]: + print(f"\nRunning: {cfg['name']}...") + try: + r = run_portfolio(cfg, price_cache) + results[cfg["name"]] = r + print_result(r) + except Exception as e: + print(f"ERROR: {e}") + traceback.print_exc() + + # Comparison + if len(results) == 2: + r_cur = list(results.values())[0] + r_opt = list(results.values())[1] + print(f"\n{'='*60}") + print("COMPARISON") + print(f"{'='*60}") + print(f" {'Metric':<20s} {'Current':>12s} {'Optimized':>12s} {'Delta':>12s}") + print(f" {'-'*56}") + for label, k in [("Final Equity", "final_equity"), ("Total PnL", "total_pnl"), + ("Return %", "total_ret"), ("Trades", "total_trades")]: + v1, v2 = r_cur[k], r_opt[k] + d = v2 - v1 + if k in ("final_equity", "total_pnl"): + print(f" {label:<20s} ${v1:>11.2f} ${v2:>11.2f} ${d:>+11.2f}") + elif k == "total_ret": + print(f" {label:<20s} {v1:>11.1f}% {v2:>11.1f}% {d:>+11.1f}%") + else: + print(f" {label:<20s} {v1:>12d} {v2:>12d} {d:>+12d}") + + # Save + path = save_results(results, results_dir, "exp14_portfolio_sim") + print(f"\nSaved: {path}") + + +if __name__ == "__main__": + main() diff --git a/experiments/exp15_grid_search/results/results_exp15_grid_search_20260309_231355.json b/experiments/exp15_grid_search/results/results_exp15_grid_search_20260309_231355.json new file mode 100644 index 0000000..bd369c4 --- /dev/null +++ b/experiments/exp15_grid_search/results/results_exp15_grid_search_20260309_231355.json @@ -0,0 +1,1150 @@ +{ + "grid_results": { + "ETH-USD": [ + { + "ws": 32, + "leverage": 1, + "sharpe": 2.49, + "total_pnl": 8322.2, + "total_ret": 83.2, + "wr": 46.5, + "trades": 564, + "max_drawdown": 5.7, + "monthly_pnl": 363.08, + "years": 1.9101072324891626 + }, + { + "ws": 32, + "leverage": 2, + "sharpe": 2.49, + "total_pnl": 22498.4, + "total_ret": 225.0, + "wr": 46.5, + "trades": 564, + "max_drawdown": 11.1, + "monthly_pnl": 981.55, + "years": 1.9101072324891626 + }, + { + "ws": 48, + "leverage": 1, + "sharpe": 2.7, + "total_pnl": 10614.55, + "total_ret": 106.1, + "wr": 45.8, + "trades": 626, + "max_drawdown": 8.4, + "monthly_pnl": 463.86, + "years": 1.9069130732375086 + }, + { + "ws": 48, + "leverage": 2, + "sharpe": 2.7, + "total_pnl": 30832.95, + "total_ret": 308.3, + "wr": 45.8, + "trades": 626, + "max_drawdown": 16.1, + "monthly_pnl": 1347.42, + "years": 1.9069130732375086 + }, + { + "ws": 64, + "leverage": 1, + "sharpe": 3.02, + "total_pnl": 11435.62, + "total_ret": 114.4, + "wr": 49.1, + "trades": 572, + "max_drawdown": 6.4, + "monthly_pnl": 500.16, + "years": 1.9053159936116815 + }, + { + "ws": 64, + "leverage": 2, + "sharpe": 3.02, + "total_pnl": 34376.02, + "total_ret": 343.8, + "wr": 49.1, + "trades": 572, + "max_drawdown": 12.6, + "monthly_pnl": 1503.51, + "years": 1.9053159936116815 + }, + { + "ws": 96, + "leverage": 1, + "sharpe": 2.73, + "total_pnl": 10226.05, + "total_ret": 102.3, + "wr": 47.4, + "trades": 591, + "max_drawdown": 6.8, + "monthly_pnl": 448.76, + "years": 1.8989276751083732 + }, + { + "ws": 96, + "leverage": 2, + "sharpe": 2.73, + "total_pnl": 29447.23, + "total_ret": 294.5, + "wr": 47.4, + "trades": 591, + "max_drawdown": 13.5, + "monthly_pnl": 1292.27, + "years": 1.8989276751083732 + }, + { + "ws": 128, + "leverage": 1, + "sharpe": 2.65, + "total_pnl": 10883.61, + "total_ret": 108.8, + "wr": 48.0, + "trades": 604, + "max_drawdown": 5.2, + "monthly_pnl": 478.83, + "years": 1.8941364362308921 + }, + { + "ws": 128, + "leverage": 2, + "sharpe": 2.65, + "total_pnl": 31771.45, + "total_ret": 317.7, + "wr": 48.0, + "trades": 604, + "max_drawdown": 10.2, + "monthly_pnl": 1397.8, + "years": 1.8941364362308921 + } + ], + "SOL-USD": [ + { + "ws": 32, + "leverage": 1, + "sharpe": 2.71, + "total_pnl": 13738.47, + "total_ret": 137.4, + "wr": 46.3, + "trades": 572, + "max_drawdown": 5.2, + "monthly_pnl": 599.38, + "years": 1.9101072324891626 + }, + { + "ws": 32, + "leverage": 2, + "sharpe": 2.67, + "total_pnl": 41345.05, + "total_ret": 413.5, + "wr": 46.3, + "trades": 572, + "max_drawdown": 10.1, + "monthly_pnl": 1803.78, + "years": 1.9101072324891626 + }, + { + "ws": 48, + "leverage": 1, + "sharpe": 3.07, + "total_pnl": 18113.48, + "total_ret": 181.1, + "wr": 47.7, + "trades": 618, + "max_drawdown": 9.8, + "monthly_pnl": 791.57, + "years": 1.9069130732375086 + }, + { + "ws": 48, + "leverage": 2, + "sharpe": 3.04, + "total_pnl": 61950.2, + "total_ret": 619.5, + "wr": 47.7, + "trades": 618, + "max_drawdown": 18.8, + "monthly_pnl": 2707.26, + "years": 1.9069130732375086 + }, + { + "ws": 64, + "leverage": 1, + "sharpe": 2.17, + "total_pnl": 9855.04, + "total_ret": 98.6, + "wr": 45.8, + "trades": 583, + "max_drawdown": 7.1, + "monthly_pnl": 431.03, + "years": 1.9053159936116815 + }, + { + "ws": 64, + "leverage": 2, + "sharpe": 2.16, + "total_pnl": 26879.54, + "total_ret": 268.8, + "wr": 45.8, + "trades": 583, + "max_drawdown": 13.9, + "monthly_pnl": 1175.64, + "years": 1.9053159936116815 + }, + { + "ws": 96, + "leverage": 1, + "sharpe": 1.6, + "total_pnl": 6474.96, + "total_ret": 64.7, + "wr": 44.9, + "trades": 594, + "max_drawdown": 8.6, + "monthly_pnl": 284.15, + "years": 1.8989276751083732 + }, + { + "ws": 96, + "leverage": 2, + "sharpe": 1.6, + "total_pnl": 15642.19, + "total_ret": 156.4, + "wr": 44.9, + "trades": 594, + "max_drawdown": 16.7, + "monthly_pnl": 686.45, + "years": 1.8989276751083732 + }, + { + "ws": 128, + "leverage": 1, + "sharpe": 3.11, + "total_pnl": 20118.72, + "total_ret": 201.2, + "wr": 47.2, + "trades": 595, + "max_drawdown": 9.8, + "monthly_pnl": 885.13, + "years": 1.8941364362308921 + }, + { + "ws": 128, + "leverage": 2, + "sharpe": 3.11, + "total_pnl": 74127.63, + "total_ret": 741.3, + "wr": 47.2, + "trades": 595, + "max_drawdown": 19.1, + "monthly_pnl": 3261.28, + "years": 1.8941364362308921 + } + ], + "BTC-USD": [ + { + "ws": 32, + "leverage": 1, + "sharpe": 2.44, + "total_pnl": 5517.56, + "total_ret": 55.2, + "wr": 47.2, + "trades": 290, + "max_drawdown": 3.4, + "monthly_pnl": 241.53, + "years": 1.9037189139858544 + }, + { + "ws": 32, + "leverage": 2, + "sharpe": 2.44, + "total_pnl": 13650.5, + "total_ret": 136.5, + "wr": 47.2, + "trades": 290, + "max_drawdown": 6.7, + "monthly_pnl": 597.54, + "years": 1.9037189139858544 + }, + { + "ws": 48, + "leverage": 1, + "sharpe": 1.49, + "total_pnl": 2808.06, + "total_ret": 28.1, + "wr": 46.6, + "trades": 290, + "max_drawdown": 5.6, + "monthly_pnl": 123.33, + "years": 1.8973305954825461 + }, + { + "ws": 48, + "leverage": 2, + "sharpe": 1.49, + "total_pnl": 6152.8, + "total_ret": 61.5, + "wr": 46.6, + "trades": 290, + "max_drawdown": 10.9, + "monthly_pnl": 270.24, + "years": 1.8973305954825461 + }, + { + "ws": 64, + "leverage": 1, + "sharpe": 2.35, + "total_pnl": 5416.41, + "total_ret": 54.2, + "wr": 46.5, + "trades": 310, + "max_drawdown": 5.5, + "monthly_pnl": 238.7, + "years": 1.890942276979238 + }, + { + "ws": 64, + "leverage": 2, + "sharpe": 2.35, + "total_pnl": 13322.91, + "total_ret": 133.2, + "wr": 46.5, + "trades": 310, + "max_drawdown": 10.8, + "monthly_pnl": 587.14, + "years": 1.890942276979238 + }, + { + "ws": 96, + "leverage": 1, + "sharpe": 2.04, + "total_pnl": 4076.58, + "total_ret": 40.8, + "wr": 49.6, + "trades": 284, + "max_drawdown": 6.2, + "monthly_pnl": 180.26, + "years": 1.8845539584759297 + }, + { + "ws": 96, + "leverage": 2, + "sharpe": 2.04, + "total_pnl": 9507.69, + "total_ret": 95.1, + "wr": 49.6, + "trades": 284, + "max_drawdown": 12.1, + "monthly_pnl": 420.42, + "years": 1.8845539584759297 + }, + { + "ws": 128, + "leverage": 1, + "sharpe": 1.42, + "total_pnl": 2690.58, + "total_ret": 26.9, + "wr": 47.1, + "trades": 297, + "max_drawdown": 8.2, + "monthly_pnl": 119.79, + "years": 1.8717773214693132 + }, + { + "ws": 128, + "leverage": 2, + "sharpe": 1.42, + "total_pnl": 5851.47, + "total_ret": 58.5, + "wr": 47.1, + "trades": 297, + "max_drawdown": 16.1, + "monthly_pnl": 260.51, + "years": 1.8717773214693132 + } + ], + "DOGE-USD": [ + { + "ws": 32, + "leverage": 1, + "sharpe": 2.3, + "total_pnl": 12297.75, + "total_ret": 123.0, + "wr": 47.2, + "trades": 303, + "max_drawdown": 7.7, + "monthly_pnl": 538.32, + "years": 1.9037189139858544 + }, + { + "ws": 32, + "leverage": 2, + "sharpe": 2.3, + "total_pnl": 35594.29, + "total_ret": 355.9, + "wr": 47.2, + "trades": 303, + "max_drawdown": 14.9, + "monthly_pnl": 1558.1, + "years": 1.9037189139858544 + }, + { + "ws": 48, + "leverage": 1, + "sharpe": 3.15, + "total_pnl": 20535.58, + "total_ret": 205.4, + "wr": 52.6, + "trades": 293, + "max_drawdown": 10.1, + "monthly_pnl": 901.95, + "years": 1.8973305954825461 + }, + { + "ws": 48, + "leverage": 2, + "sharpe": 3.25, + "total_pnl": 81377.11, + "total_ret": 813.8, + "wr": 52.6, + "trades": 293, + "max_drawdown": 17.0, + "monthly_pnl": 3574.19, + "years": 1.8973305954825461 + }, + { + "ws": 64, + "leverage": 1, + "sharpe": 2.89, + "total_pnl": 16945.9, + "total_ret": 169.5, + "wr": 52.0, + "trades": 281, + "max_drawdown": 8.8, + "monthly_pnl": 746.8, + "years": 1.890942276979238 + }, + { + "ws": 64, + "leverage": 2, + "sharpe": 2.97, + "total_pnl": 60005.03, + "total_ret": 600.1, + "wr": 52.0, + "trades": 281, + "max_drawdown": 15.5, + "monthly_pnl": 2644.41, + "years": 1.890942276979238 + }, + { + "ws": 96, + "leverage": 1, + "sharpe": 2.85, + "total_pnl": 17757.12, + "total_ret": 177.6, + "wr": 51.2, + "trades": 281, + "max_drawdown": 7.7, + "monthly_pnl": 785.2, + "years": 1.8845539584759297 + }, + { + "ws": 96, + "leverage": 2, + "sharpe": 2.81, + "total_pnl": 58405.92, + "total_ret": 584.1, + "wr": 51.2, + "trades": 281, + "max_drawdown": 17.7, + "monthly_pnl": 2582.66, + "years": 1.8845539584759297 + }, + { + "ws": 128, + "leverage": 1, + "sharpe": 1.46, + "total_pnl": 5785.31, + "total_ret": 57.9, + "wr": 45.7, + "trades": 302, + "max_drawdown": 13.2, + "monthly_pnl": 257.57, + "years": 1.8717773214693132 + }, + { + "ws": 128, + "leverage": 2, + "sharpe": 1.54, + "total_pnl": 14371.37, + "total_ret": 143.7, + "wr": 45.7, + "trades": 302, + "max_drawdown": 24.8, + "monthly_pnl": 639.83, + "years": 1.8717773214693132 + } + ], + "ADA-USD": [ + { + "ws": 32, + "leverage": 1, + "sharpe": 2.45, + "total_pnl": 23680.97, + "total_ret": 236.8, + "wr": 48.8, + "trades": 291, + "max_drawdown": 8.0, + "monthly_pnl": 1036.61, + "years": 1.9037189139858544 + }, + { + "ws": 32, + "leverage": 2, + "sharpe": 2.5, + "total_pnl": 88935.23, + "total_ret": 889.4, + "wr": 48.8, + "trades": 291, + "max_drawdown": 15.1, + "monthly_pnl": 3893.05, + "years": 1.9037189139858544 + }, + { + "ws": 48, + "leverage": 1, + "sharpe": 1.58, + "total_pnl": 7960.12, + "total_ret": 79.6, + "wr": 44.4, + "trades": 284, + "max_drawdown": 14.6, + "monthly_pnl": 349.62, + "years": 1.8973305954825461 + }, + { + "ws": 48, + "leverage": 2, + "sharpe": 1.57, + "total_pnl": 19434.36, + "total_ret": 194.3, + "wr": 44.4, + "trades": 284, + "max_drawdown": 27.1, + "monthly_pnl": 853.58, + "years": 1.8973305954825461 + }, + { + "ws": 64, + "leverage": 1, + "sharpe": 2.78, + "total_pnl": 14426.5, + "total_ret": 144.3, + "wr": 50.2, + "trades": 285, + "max_drawdown": 8.1, + "monthly_pnl": 635.77, + "years": 1.890942276979238 + }, + { + "ws": 64, + "leverage": 2, + "sharpe": 2.86, + "total_pnl": 47696.16, + "total_ret": 477.0, + "wr": 50.2, + "trades": 285, + "max_drawdown": 13.9, + "monthly_pnl": 2101.96, + "years": 1.890942276979238 + }, + { + "ws": 96, + "leverage": 1, + "sharpe": 2.09, + "total_pnl": 14418.32, + "total_ret": 144.2, + "wr": 50.2, + "trades": 287, + "max_drawdown": 12.8, + "monthly_pnl": 637.57, + "years": 1.8845539584759297 + }, + { + "ws": 96, + "leverage": 2, + "sharpe": 2.1, + "total_pnl": 44049.38, + "total_ret": 440.5, + "wr": 50.2, + "trades": 287, + "max_drawdown": 22.9, + "monthly_pnl": 1947.83, + "years": 1.8845539584759297 + }, + { + "ws": 128, + "leverage": 1, + "sharpe": 1.21, + "total_pnl": 4828.9, + "total_ret": 48.3, + "wr": 44.9, + "trades": 301, + "max_drawdown": 12.6, + "monthly_pnl": 214.99, + "years": 1.8717773214693132 + }, + { + "ws": 128, + "leverage": 2, + "sharpe": 1.22, + "total_pnl": 10688.03, + "total_ret": 106.9, + "wr": 44.9, + "trades": 301, + "max_drawdown": 23.8, + "monthly_pnl": 475.84, + "years": 1.8717773214693132 + } + ], + "XRP-USD": [ + { + "ws": 32, + "leverage": 1, + "sharpe": 2.25, + "total_pnl": 10647.42, + "total_ret": 106.5, + "wr": 50.0, + "trades": 294, + "max_drawdown": 6.7, + "monthly_pnl": 466.08, + "years": 1.9037189139858544 + }, + { + "ws": 32, + "leverage": 2, + "sharpe": 2.35, + "total_pnl": 31825.26, + "total_ret": 318.3, + "wr": 50.0, + "trades": 294, + "max_drawdown": 11.8, + "monthly_pnl": 1393.12, + "years": 1.9037189139858544 + }, + { + "ws": 48, + "leverage": 1, + "sharpe": 1.45, + "total_pnl": 5499.42, + "total_ret": 55.0, + "wr": 46.9, + "trades": 307, + "max_drawdown": 13.3, + "monthly_pnl": 241.54, + "years": 1.8973305954825461 + }, + { + "ws": 48, + "leverage": 2, + "sharpe": 1.54, + "total_pnl": 13606.9, + "total_ret": 136.1, + "wr": 46.9, + "trades": 307, + "max_drawdown": 23.6, + "monthly_pnl": 597.63, + "years": 1.8973305954825461 + }, + { + "ws": 64, + "leverage": 1, + "sharpe": 2.49, + "total_pnl": 10845.86, + "total_ret": 108.5, + "wr": 50.0, + "trades": 296, + "max_drawdown": 9.6, + "monthly_pnl": 477.97, + "years": 1.890942276979238 + }, + { + "ws": 64, + "leverage": 2, + "sharpe": 2.55, + "total_pnl": 32441.71, + "total_ret": 324.4, + "wr": 50.0, + "trades": 296, + "max_drawdown": 18.5, + "monthly_pnl": 1429.7, + "years": 1.890942276979238 + }, + { + "ws": 96, + "leverage": 1, + "sharpe": 2.31, + "total_pnl": 12355.63, + "total_ret": 123.6, + "wr": 46.1, + "trades": 295, + "max_drawdown": 9.2, + "monthly_pnl": 546.36, + "years": 1.8845539584759297 + }, + { + "ws": 96, + "leverage": 2, + "sharpe": 2.37, + "total_pnl": 37014.41, + "total_ret": 370.1, + "wr": 46.1, + "trades": 295, + "max_drawdown": 17.7, + "monthly_pnl": 1636.74, + "years": 1.8845539584759297 + }, + { + "ws": 128, + "leverage": 1, + "sharpe": 1.28, + "total_pnl": 4381.38, + "total_ret": 43.8, + "wr": 45.3, + "trades": 289, + "max_drawdown": 8.7, + "monthly_pnl": 195.06, + "years": 1.8717773214693132 + }, + { + "ws": 128, + "leverage": 2, + "sharpe": 1.3, + "total_pnl": 9808.54, + "total_ret": 98.1, + "wr": 45.3, + "trades": 289, + "max_drawdown": 19.9, + "monthly_pnl": 436.69, + "years": 1.8717773214693132 + } + ], + "DOT-USD": [ + { + "ws": 32, + "leverage": 1, + "sharpe": 2.85, + "total_pnl": 17661.62, + "total_ret": 176.6, + "wr": 49.1, + "trades": 281, + "max_drawdown": 7.1, + "monthly_pnl": 773.12, + "years": 1.9037189139858544 + }, + { + "ws": 32, + "leverage": 2, + "sharpe": 2.87, + "total_pnl": 61416.99, + "total_ret": 614.2, + "wr": 49.1, + "trades": 281, + "max_drawdown": 13.9, + "monthly_pnl": 2688.47, + "years": 1.9037189139858544 + }, + { + "ws": 48, + "leverage": 1, + "sharpe": 1.98, + "total_pnl": 9398.11, + "total_ret": 94.0, + "wr": 46.4, + "trades": 304, + "max_drawdown": 8.0, + "monthly_pnl": 412.78, + "years": 1.8973305954825461 + }, + { + "ws": 48, + "leverage": 2, + "sharpe": 2.0, + "total_pnl": 25419.38, + "total_ret": 254.2, + "wr": 46.4, + "trades": 304, + "max_drawdown": 15.4, + "monthly_pnl": 1116.45, + "years": 1.8973305954825461 + }, + { + "ws": 64, + "leverage": 1, + "sharpe": 1.93, + "total_pnl": 8954.2, + "total_ret": 89.5, + "wr": 47.8, + "trades": 278, + "max_drawdown": 6.9, + "monthly_pnl": 394.61, + "years": 1.890942276979238 + }, + { + "ws": 64, + "leverage": 2, + "sharpe": 1.95, + "total_pnl": 23511.48, + "total_ret": 235.1, + "wr": 47.8, + "trades": 278, + "max_drawdown": 13.6, + "monthly_pnl": 1036.14, + "years": 1.890942276979238 + }, + { + "ws": 96, + "leverage": 1, + "sharpe": 2.33, + "total_pnl": 11434.3, + "total_ret": 114.3, + "wr": 48.8, + "trades": 285, + "max_drawdown": 8.0, + "monthly_pnl": 505.61, + "years": 1.8845539584759297 + }, + { + "ws": 96, + "leverage": 2, + "sharpe": 2.31, + "total_pnl": 30741.19, + "total_ret": 307.4, + "wr": 48.8, + "trades": 285, + "max_drawdown": 14.2, + "monthly_pnl": 1359.35, + "years": 1.8845539584759297 + }, + { + "ws": 128, + "leverage": 1, + "sharpe": 1.53, + "total_pnl": 6182.27, + "total_ret": 61.8, + "wr": 46.7, + "trades": 291, + "max_drawdown": 8.4, + "monthly_pnl": 275.24, + "years": 1.8717773214693132 + }, + { + "ws": 128, + "leverage": 2, + "sharpe": 1.55, + "total_pnl": 14830.0, + "total_ret": 148.3, + "wr": 46.7, + "trades": 291, + "max_drawdown": 13.8, + "monthly_pnl": 660.25, + "years": 1.8717773214693132 + } + ] + }, + "optimal_params": { + "ETH-USD": { + "ws": 64, + "leverage": 2, + "tf": "2h", + "sharpe": 3.02, + "max_drawdown": 12.6, + "total_pnl": 34376.02, + "weight": 0.1637 + }, + "SOL-USD": { + "ws": 128, + "leverage": 2, + "tf": "2h", + "sharpe": 3.11, + "max_drawdown": 19.1, + "total_pnl": 74127.63, + "weight": 0.1112 + }, + "BTC-USD": { + "ws": 32, + "leverage": 2, + "tf": "4h", + "sharpe": 2.44, + "max_drawdown": 6.7, + "total_pnl": 13650.5, + "weight": 0.2488 + }, + "DOGE-USD": { + "ws": 48, + "leverage": 2, + "tf": "4h", + "sharpe": 3.25, + "max_drawdown": 17.0, + "total_pnl": 81377.11, + "weight": 0.1306 + }, + "ADA-USD": { + "ws": 32, + "leverage": 2, + "tf": "4h", + "sharpe": 2.5, + "max_drawdown": 15.1, + "total_pnl": 88935.23, + "weight": 0.1131 + }, + "XRP-USD": { + "ws": 96, + "leverage": 2, + "tf": "4h", + "sharpe": 2.37, + "max_drawdown": 17.7, + "total_pnl": 37014.41, + "weight": 0.0915 + }, + "DOT-USD": { + "ws": 32, + "leverage": 2, + "tf": "4h", + "sharpe": 2.87, + "max_drawdown": 13.9, + "total_pnl": 61416.99, + "weight": 0.1411 + } + }, + "weights": { + "ETH-USD": 0.1637, + "SOL-USD": 0.1112, + "BTC-USD": 0.2488, + "DOGE-USD": 0.1306, + "ADA-USD": 0.1131, + "XRP-USD": 0.0915, + "DOT-USD": 0.1411 + }, + "portfolio_results": { + "CURRENT (equal, ws=64, 2x)": { + "total_capital": 114.0, + "final_equity": 3587.6, + "total_pnl": 3473.6, + "total_ret": 3047.0, + "total_trades": 2605, + "asset_stats": { + "ETH-USD": { + "trades": 572, + "wins": 281, + "wr": 49.1, + "pnl": 508.07, + "sharpe": 3.02, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 524.36, + "monthly_pnl": 22.22, + "years": 1.91 + }, + "SOL-USD": { + "trades": 583, + "wins": 267, + "wr": 45.8, + "pnl": 274.84, + "sharpe": 2.17, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 291.13, + "monthly_pnl": 12.02, + "years": 1.91 + }, + "BTC-USD": { + "trades": 310, + "wins": 144, + "wr": 46.5, + "pnl": 101.7, + "sharpe": 2.35, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 117.99, + "monthly_pnl": 4.48, + "years": 1.89 + }, + "DOGE-USD": { + "trades": 281, + "wins": 146, + "wr": 52.0, + "pnl": 1208.62, + "sharpe": 2.89, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 1224.91, + "monthly_pnl": 53.26, + "years": 1.89 + }, + "ADA-USD": { + "trades": 285, + "wins": 143, + "wr": 50.2, + "pnl": 786.14, + "sharpe": 2.78, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 802.43, + "monthly_pnl": 34.64, + "years": 1.89 + }, + "XRP-USD": { + "trades": 296, + "wins": 148, + "wr": 50.0, + "pnl": 385.71, + "sharpe": 2.49, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 402.0, + "monthly_pnl": 17.0, + "years": 1.89 + }, + "DOT-USD": { + "trades": 278, + "wins": 133, + "wr": 47.8, + "pnl": 208.49, + "sharpe": 1.93, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 224.78, + "monthly_pnl": 9.19, + "years": 1.89 + } + }, + "config_name": "CURRENT (equal, ws=64, 2x)" + }, + "OPTIMAL (grid-searched)": { + "total_capital": 114.0, + "final_equity": 7661.91, + "total_pnl": 7547.91, + "total_ret": 6621.0, + "total_trades": 2617, + "asset_stats": { + "ETH-USD": { + "trades": 572, + "wins": 281, + "wr": 49.1, + "pnl": 582.02, + "sharpe": 3.02, + "weight": 0.1637, + "ws": 64, + "leverage": 2, + "initial": 18.66, + "final": 600.68, + "monthly_pnl": 25.46, + "years": 1.91 + }, + "SOL-USD": { + "trades": 595, + "wins": 281, + "wr": 47.2, + "pnl": 1598.32, + "sharpe": 3.11, + "weight": 0.1112, + "ws": 128, + "leverage": 2, + "initial": 12.68, + "final": 1610.99, + "monthly_pnl": 70.32, + "years": 1.89 + }, + "BTC-USD": { + "trades": 290, + "wins": 137, + "wr": 47.2, + "pnl": 185.81, + "sharpe": 2.44, + "weight": 0.2488, + "ws": 32, + "leverage": 2, + "initial": 28.36, + "final": 214.17, + "monthly_pnl": 8.13, + "years": 1.9 + }, + "DOGE-USD": { + "trades": 293, + "wins": 154, + "wr": 52.6, + "pnl": 1993.88, + "sharpe": 3.15, + "weight": 0.1306, + "ws": 48, + "leverage": 2, + "initial": 14.89, + "final": 2008.77, + "monthly_pnl": 87.57, + "years": 1.9 + }, + "ADA-USD": { + "trades": 291, + "wins": 142, + "wr": 48.8, + "pnl": 1547.55, + "sharpe": 2.37, + "weight": 0.1131, + "ws": 32, + "leverage": 2, + "initial": 12.89, + "final": 1560.44, + "monthly_pnl": 67.74, + "years": 1.9 + }, + "XRP-USD": { + "trades": 295, + "wins": 136, + "wr": 46.1, + "pnl": 294.29, + "sharpe": 2.31, + "weight": 0.0915, + "ws": 96, + "leverage": 2, + "initial": 10.43, + "final": 304.72, + "monthly_pnl": 13.01, + "years": 1.88 + }, + "DOT-USD": { + "trades": 281, + "wins": 138, + "wr": 49.1, + "pnl": 1346.04, + "sharpe": 2.85, + "weight": 0.1411, + "ws": 32, + "leverage": 2, + "initial": 16.09, + "final": 1362.13, + "monthly_pnl": 58.92, + "years": 1.9 + } + }, + "config_name": "OPTIMAL (grid-searched)" + } + } +} \ No newline at end of file diff --git a/experiments/exp15_grid_search/results/results_exp15b_sharpe_optimal_20260309_232545.json b/experiments/exp15_grid_search/results/results_exp15b_sharpe_optimal_20260309_232545.json new file mode 100644 index 0000000..8ee42db --- /dev/null +++ b/experiments/exp15_grid_search/results/results_exp15b_sharpe_optimal_20260309_232545.json @@ -0,0 +1,323 @@ +{ + "A: CURRENT (equal, ws=64, 2x)": { + "total_capital": 114.0, + "final_equity": 3587.5, + "total_pnl": 3473.5, + "total_ret": 3046.9, + "total_trades": 2605, + "asset_stats": { + "ETH-USD": { + "trades": 572, + "wins": 281, + "wr": 49.1, + "pnl": 508.07, + "sharpe": 3.02, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 524.36, + "monthly_pnl": 22.22, + "years": 1.91 + }, + "SOL-USD": { + "trades": 583, + "wins": 267, + "wr": 45.8, + "pnl": 274.84, + "sharpe": 2.17, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 291.13, + "monthly_pnl": 12.02, + "years": 1.91 + }, + "BTC-USD": { + "trades": 310, + "wins": 144, + "wr": 46.5, + "pnl": 101.6, + "sharpe": 2.35, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 117.89, + "monthly_pnl": 4.48, + "years": 1.89 + }, + "DOGE-USD": { + "trades": 281, + "wins": 146, + "wr": 52.0, + "pnl": 1208.62, + "sharpe": 2.89, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 1224.91, + "monthly_pnl": 53.26, + "years": 1.89 + }, + "ADA-USD": { + "trades": 285, + "wins": 143, + "wr": 50.2, + "pnl": 786.14, + "sharpe": 2.78, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 802.43, + "monthly_pnl": 34.64, + "years": 1.89 + }, + "XRP-USD": { + "trades": 296, + "wins": 148, + "wr": 50.0, + "pnl": 385.71, + "sharpe": 2.49, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 402.0, + "monthly_pnl": 17.0, + "years": 1.89 + }, + "DOT-USD": { + "trades": 278, + "wins": 133, + "wr": 47.8, + "pnl": 208.49, + "sharpe": 1.93, + "weight": 0.1429, + "ws": 64, + "leverage": 2, + "initial": 16.29, + "final": 224.78, + "monthly_pnl": 9.19, + "years": 1.89 + } + } + }, + "B: SHARPE-OPTIMAL (max Sharpe, Sharpe/DD weights)": { + "total_capital": 114.0, + "final_equity": 6176.33, + "total_pnl": 6062.33, + "total_ret": 5317.8, + "total_trades": 2612, + "asset_stats": { + "ETH-USD": { + "trades": 572, + "wins": 281, + "wr": 49.1, + "pnl": 522.65, + "sharpe": 3.02, + "weight": 0.147, + "ws": 64, + "leverage": 2, + "initial": 16.76, + "final": 539.41, + "monthly_pnl": 22.86, + "years": 1.91 + }, + "SOL-USD": { + "trades": 595, + "wins": 281, + "wr": 47.2, + "pnl": 1437.34, + "sharpe": 3.11, + "weight": 0.1, + "ws": 128, + "leverage": 2, + "initial": 11.4, + "final": 1448.74, + "monthly_pnl": 63.24, + "years": 1.89 + }, + "BTC-USD": { + "trades": 290, + "wins": 137, + "wr": 47.2, + "pnl": 167.44, + "sharpe": 2.44, + "weight": 0.224, + "ws": 32, + "leverage": 2, + "initial": 25.54, + "final": 192.97, + "monthly_pnl": 7.33, + "years": 1.9 + }, + "DOGE-USD": { + "trades": 293, + "wins": 154, + "wr": 52.6, + "pnl": 1803.49, + "sharpe": 3.15, + "weight": 0.118, + "ws": 48, + "leverage": 2, + "initial": 13.45, + "final": 1816.94, + "monthly_pnl": 79.21, + "years": 1.9 + }, + "ADA-USD": { + "trades": 285, + "wins": 143, + "wr": 50.2, + "pnl": 698.67, + "sharpe": 2.78, + "weight": 0.127, + "ws": 64, + "leverage": 2, + "initial": 14.48, + "final": 713.15, + "monthly_pnl": 30.79, + "years": 1.89 + }, + "XRP-USD": { + "trades": 296, + "wins": 148, + "wr": 50.0, + "pnl": 229.43, + "sharpe": 2.49, + "weight": 0.085, + "ws": 64, + "leverage": 2, + "initial": 9.69, + "final": 239.12, + "monthly_pnl": 10.11, + "years": 1.89 + }, + "DOT-USD": { + "trades": 281, + "wins": 138, + "wr": 49.1, + "pnl": 1211.53, + "sharpe": 2.85, + "weight": 0.127, + "ws": 32, + "leverage": 2, + "initial": 14.48, + "final": 1226.01, + "monthly_pnl": 53.03, + "years": 1.9 + } + } + }, + "C: PNL-OPTIMAL (max PnL, Sharpe/DD weights)": { + "total_capital": 114.0, + "final_equity": 7668.93, + "total_pnl": 7554.93, + "total_ret": 6627.1, + "total_trades": 2617, + "asset_stats": { + "ETH-USD": { + "trades": 572, + "wins": 281, + "wr": 49.1, + "pnl": 583.09, + "sharpe": 3.02, + "weight": 0.164, + "ws": 64, + "leverage": 2, + "initial": 18.7, + "final": 601.79, + "monthly_pnl": 25.5, + "years": 1.91 + }, + "SOL-USD": { + "trades": 595, + "wins": 281, + "wr": 47.2, + "pnl": 1595.44, + "sharpe": 3.11, + "weight": 0.111, + "ws": 128, + "leverage": 2, + "initial": 12.65, + "final": 1608.1, + "monthly_pnl": 70.19, + "years": 1.89 + }, + "BTC-USD": { + "trades": 290, + "wins": 137, + "wr": 47.2, + "pnl": 186.13, + "sharpe": 2.44, + "weight": 0.249, + "ws": 32, + "leverage": 2, + "initial": 28.39, + "final": 214.51, + "monthly_pnl": 8.15, + "years": 1.9 + }, + "DOGE-USD": { + "trades": 293, + "wins": 154, + "wr": 52.6, + "pnl": 2002.18, + "sharpe": 3.15, + "weight": 0.131, + "ws": 48, + "leverage": 2, + "initial": 14.93, + "final": 2017.11, + "monthly_pnl": 87.94, + "years": 1.9 + }, + "ADA-USD": { + "trades": 291, + "wins": 142, + "wr": 48.8, + "pnl": 1546.18, + "sharpe": 2.37, + "weight": 0.113, + "ws": 32, + "leverage": 2, + "initial": 12.88, + "final": 1559.06, + "monthly_pnl": 67.68, + "years": 1.9 + }, + "XRP-USD": { + "trades": 295, + "wins": 136, + "wr": 46.1, + "pnl": 296.71, + "sharpe": 2.31, + "weight": 0.092, + "ws": 96, + "leverage": 2, + "initial": 10.49, + "final": 307.2, + "monthly_pnl": 13.12, + "years": 1.88 + }, + "DOT-USD": { + "trades": 281, + "wins": 138, + "wr": 49.1, + "pnl": 1345.09, + "sharpe": 2.85, + "weight": 0.141, + "ws": 32, + "leverage": 2, + "initial": 16.07, + "final": 1361.16, + "monthly_pnl": 58.88, + "years": 1.9 + } + } + } +} \ No newline at end of file diff --git a/experiments/exp15_grid_search/run.py b/experiments/exp15_grid_search/run.py new file mode 100644 index 0000000..ea467b2 --- /dev/null +++ b/experiments/exp15_grid_search/run.py @@ -0,0 +1,549 @@ +"""Exp15: Grid search for optimal (window_size, leverage) per asset. + +Maximizes PnL per pair, then assembles optimal portfolio with $114 capital. +Grid: ws=[32,48,64,96,128] × leverage=[1,2] = 10 combos per asset. +""" +import json +import sys +import traceback +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) +sys.path.insert(0, str(Path(__file__).parent.parent)) + +import numpy as np +import torch + +from remizov_trader.core import model as model_mod, signals, risk +from remizov_trader.config import ModelConfig, RiskConfig +from common.metrics import compute_metrics, save_results + +INITIAL_CAPITAL = 10_000.0 +TOTAL_PORTFOLIO = 114.0 +K = 2 +CORR_THRESH = 0.5 +TRAILING_STOP = True +TRAIN_RATIO = 0.3 + +WINDOW_SIZES = [32, 48, 64, 96, 128] +LEVERAGES = [1, 2] + +ASSETS = [ + ("ETH/USDC", "ETH-USD", "2h"), + ("SOL/USDC", "SOL-USD", "2h"), + ("BTC/USDC", "BTC-USD", "4h"), + ("DOGE/USDC", "DOGE-USD", "4h"), + ("ADA/USDC", "ADA-USD", "4h"), + ("XRP/USDC", "XRP-USD", "4h"), + ("DOT/USDC", "DOT-USD", "4h"), +] + + +def run_backtest(ticker, prices, dates, ws, leverage, tf="4h"): + """Backtest single asset with given ws and leverage.""" + model_cfg = ModelConfig( + window_size=ws, n_steps=20, total_time=0.5, + shift=7, epochs=200, finetune_epochs=50, lr=0.003, + ) + shift = model_cfg.shift + + data = signals.prepare_windows(prices, ws, shift) + if len(data) < 30: + return None + + n_train = max(int(len(data) * TRAIN_RATIO), 20) + train_data = data[:n_train] + test_data = data[n_train:] + + torch.manual_seed(42) + np.random.seed(42) + mdl = model_mod.create_model(model_cfg) + windows = np.array([d["norm_input"] for d in train_data]) + targets = np.array([d["norm_target"] for d in train_data]) + model_mod.train(mdl, windows, targets, model_cfg.epochs, model_cfg.lr) + + # Risk config with leverage + risk_cfg = RiskConfig(per_trade=0.05, max_position_pct=0.40, + max_open_positions=1, leverage=leverage) + + equity = INITIAL_CAPITAL + peak_equity = INITIAL_CAPITAL + max_drawdown = 0.0 + trades = [] + position = None + + for d in test_data: + price_idx = d["price_idx"] + current_price = float(prices[price_idx]) + + if position is not None: + p = position + if TRAILING_STOP: + p["best_price"], p["stop_price"] = risk.update_trailing_stop( + current_price, p["best_price"], p["stop_price"], + p["stop_dist"], p["direction"]) + stopped = risk.is_stopped(current_price, p["stop_price"], p["direction"]) + bars_held = price_idx - p["entry_bar"] + if stopped or bars_held >= (shift - p["k_used"]): + exit_price = p["stop_price"] if stopped else current_price + pnl_net, _ = risk.calculate_pnl( + p["entry_price"], exit_price, p["direction"], + p["pos_size"], p["pos_value"]) + equity += pnl_net + peak_equity = max(peak_equity, equity) + dd = (peak_equity - equity) / peak_equity if peak_equity > 0 else 0 + max_drawdown = max(max_drawdown, dd) + trades.append({"pnl_net": pnl_net, "equity_at_entry": p["equity_at_entry"]}) + position = None + + if position is None and price_idx >= ws + K: + w = prices[price_idx - ws - K:price_idx - K].copy() + confirm = prices[price_idx - K:price_idx].copy() + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + norm_input = (w - mu) / std + pred = model_mod.predict(mdl, norm_input) + pred_new = pred[-shift:] + corr, confirmed = signals.check_shape_confirmation( + pred_new, confirm, mu, std, K, CORR_THRESH) + + if confirmed: + direction = signals.get_direction(pred_new, K) + if direction is not None: + k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K) + atr = risk.compute_atr(prices, price_idx) + stop_dist = max(atr * stop_mult, current_price * 0.005) + pos_size, pos_value = risk.calculate_position( + equity, current_price, stop_dist, risk_cfg) + position = { + "direction": direction, "entry_price": current_price, + "stop_price": current_price - direction * stop_dist, + "stop_dist": stop_dist, "best_price": current_price, + "pos_size": pos_size, "pos_value": pos_value, + "entry_bar": price_idx, "k_used": k_adj, + "equity_at_entry": equity, + } + + if position: + last_price = float(prices[-1]) + pnl_net, _ = risk.calculate_pnl( + position["entry_price"], last_price, position["direction"], + position["pos_size"], position["pos_value"]) + equity += pnl_net + peak_equity = max(peak_equity, equity) + dd = (peak_equity - equity) / peak_equity if peak_equity > 0 else 0 + max_drawdown = max(max_drawdown, dd) + trades.append({"pnl_net": pnl_net, "equity_at_entry": position["equity_at_entry"]}) + + first_bar = test_data[0]["price_idx"] + last_bar = test_data[-1]["price_idx"] + tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24} + bars_per_day = 24 / tf_hours.get(tf, 4) + years = (last_bar - first_bar) / (365.25 * bars_per_day) + + return { + "ticker": ticker, + "window_size": ws, + "leverage": leverage, + "trades": trades, + "years": years, + "max_drawdown": round(max_drawdown * 100, 1), + "final_equity": round(equity, 2), + } + + +def run_portfolio(asset_params, price_cache): + """Run portfolio sim with optimal params per asset. pos_value = equity × weight × leverage.""" + shift = 7 + total_equity = TOTAL_PORTFOLIO + all_trades = [] + per_asset_trades = {} + per_asset_equity = {} + + for ticker, params in asset_params.items(): + per_asset_equity[ticker] = total_equity * params["weight"] + per_asset_trades[ticker] = [] + + for ticker, params in asset_params.items(): + if ticker not in price_cache: + continue + + prices, dates, tf = price_cache[ticker] + ws = params["ws"] + leverage = params["leverage"] + weight = params["weight"] + + model_cfg = ModelConfig( + window_size=ws, n_steps=20, total_time=0.5, + shift=7, epochs=200, finetune_epochs=50, lr=0.003, + ) + data = signals.prepare_windows(prices, ws, shift) + if len(data) < 30: + continue + + n_train = max(int(len(data) * TRAIN_RATIO), 20) + train_data = data[:n_train] + test_data = data[n_train:] + + torch.manual_seed(42) + np.random.seed(42) + mdl = model_mod.create_model(model_cfg) + windows = np.array([d["norm_input"] for d in train_data]) + targets = np.array([d["norm_target"] for d in train_data]) + model_mod.train(mdl, windows, targets, 200, 0.003) + + position = None + for d in test_data: + price_idx = d["price_idx"] + current_price = float(prices[price_idx]) + + if position is not None: + p = position + if TRAILING_STOP: + p["best_price"], p["stop_price"] = risk.update_trailing_stop( + current_price, p["best_price"], p["stop_price"], + p["stop_dist"], p["direction"]) + stopped = risk.is_stopped(current_price, p["stop_price"], p["direction"]) + bars_held = price_idx - p["entry_bar"] + if stopped or bars_held >= (shift - p["k_used"]): + exit_price = p["stop_price"] if stopped else current_price + pnl_net, _ = risk.calculate_pnl( + p["entry_price"], exit_price, p["direction"], + p["pos_size"], p["pos_value"]) + per_asset_equity[ticker] += pnl_net + per_asset_trades[ticker].append({ + "pnl_net": pnl_net, "equity_at_entry": p["equity_at_entry"]}) + all_trades.append({"ticker": ticker, "pnl_net": pnl_net, + "equity_at_entry": p["equity_at_entry"]}) + position = None + + if position is None and price_idx >= ws + K: + w = prices[price_idx - ws - K:price_idx - K].copy() + confirm = prices[price_idx - K:price_idx].copy() + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + norm_input = (w - mu) / std + pred = model_mod.predict(mdl, norm_input) + pred_new = pred[-shift:] + corr, confirmed = signals.check_shape_confirmation( + pred_new, confirm, mu, std, K, CORR_THRESH) + + if confirmed: + direction = signals.get_direction(pred_new, K) + if direction is not None: + asset_eq = per_asset_equity[ticker] + pos_value = asset_eq * leverage + if pos_value < 1.0: + continue + pos_size = pos_value / current_price + k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K) + atr = risk.compute_atr(prices, price_idx) + stop_dist = max(atr * stop_mult, current_price * 0.005) + position = { + "direction": direction, "entry_price": current_price, + "stop_price": current_price - direction * stop_dist, + "stop_dist": stop_dist, "best_price": current_price, + "pos_size": pos_size, "pos_value": pos_value, + "entry_bar": price_idx, "k_used": k_adj, + "equity_at_entry": asset_eq, + } + + if position is not None: + last_price = float(prices[-1]) + pnl_net, _ = risk.calculate_pnl( + position["entry_price"], last_price, position["direction"], + position["pos_size"], position["pos_value"]) + per_asset_equity[ticker] += pnl_net + per_asset_trades[ticker].append({ + "pnl_net": pnl_net, "equity_at_entry": position["equity_at_entry"]}) + all_trades.append({"ticker": ticker, "pnl_net": pnl_net, + "equity_at_entry": position["equity_at_entry"]}) + + # Compute per-asset stats + final_equity = sum(per_asset_equity.values()) + asset_stats = {} + for ticker, params in asset_params.items(): + trades = per_asset_trades.get(ticker, []) + if not trades: + continue + wins = [t for t in trades if t["pnl_net"] > 0] + pnl = sum(t["pnl_net"] for t in trades) + + if ticker in price_cache: + prices, dates, tf = price_cache[ticker] + data = signals.prepare_windows(prices, params["ws"], shift) + n_train = max(int(len(data) * TRAIN_RATIO), 20) + td = data[n_train:] + if td: + fb, lb = td[0]["price_idx"], td[-1]["price_idx"] + tf_hours = {"2h": 2, "4h": 4} + bpd = 24 / tf_hours.get(params.get("tf", "4h"), 4) + years = (lb - fb) / (365.25 * bpd) + else: + years = 1.0 + else: + years = 1.0 + + 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 + else: + sharpe = 0 + + months = years * 12 + asset_stats[ticker] = { + "trades": len(trades), "wins": len(wins), + "wr": round(len(wins) / len(trades) * 100, 1), + "pnl": round(pnl, 2), "sharpe": round(sharpe, 2), + "weight": params["weight"], "ws": params["ws"], + "leverage": params["leverage"], + "initial": round(TOTAL_PORTFOLIO * params["weight"], 2), + "final": round(per_asset_equity[ticker], 2), + "monthly_pnl": round(pnl / months, 2) if months > 0 else 0, + "years": round(years, 2), + } + + return { + "total_capital": TOTAL_PORTFOLIO, + "final_equity": round(final_equity, 2), + "total_pnl": round(final_equity - TOTAL_PORTFOLIO, 2), + "total_ret": round((final_equity - TOTAL_PORTFOLIO) / TOTAL_PORTFOLIO * 100, 1), + "total_trades": len(all_trades), + "asset_stats": asset_stats, + } + + +def main(): + results_dir = Path(__file__).parent / "results" + + # Fetch data + price_cache = {} + for symbol, ticker, tf in ASSETS: + print(f"Fetching {ticker} ({tf})...", end=" ", flush=True) + try: + prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max") + if prices is not None: + price_cache[ticker] = (prices, dates, tf) + print(f"{len(prices)} bars") + else: + print("SKIP") + except Exception as e: + print(f"ERROR: {e}") + + # ══════════════════════════════════════════════════ + # PHASE 1: Grid search per asset + # ══════════════════════════════════════════════════ + print(f"\n{'='*80}") + print("PHASE 1: GRID SEARCH — ws × leverage per asset") + print(f"{'='*80}") + + grid_results = {} # ticker -> list of {ws, leverage, metrics} + + for symbol, ticker, tf in ASSETS: + if ticker not in price_cache: + continue + prices, dates, _ = price_cache[ticker] + grid_results[ticker] = [] + + print(f"\n {ticker} ({tf}):") + print(f" {'WS':>5s} {'Lev':>4s} | {'Sharpe':>7s} {'PnL':>12s} {'Ret%':>8s} " + f"{'WR%':>6s} {'Trds':>5s} {'DD%':>6s} {'$/mo':>10s}") + print(f" {'-'*70}") + + for ws in WINDOW_SIZES: + for lev in LEVERAGES: + try: + r = run_backtest(ticker, prices, dates, ws, lev, tf) + if not r or not r["trades"]: + print(f" {ws:>5d} {lev:>3d}x | {'no trades':>50s}") + continue + + m = compute_metrics(r["trades"], INITIAL_CAPITAL, r["years"]) + m["max_drawdown"] = r["max_drawdown"] + m["years"] = round(r["years"], 2) + months = r["years"] * 12 + monthly_pnl = m["total_pnl"] / months if months > 0 else 0 + + grid_results[ticker].append({ + "ws": ws, "leverage": lev, + "sharpe": m["sharpe"], "total_pnl": m["total_pnl"], + "total_ret": m["total_ret"], "wr": m["wr"], + "trades": m["trades"], "max_drawdown": r["max_drawdown"], + "monthly_pnl": round(monthly_pnl, 2), + "years": r["years"], + }) + + print(f" {ws:>5d} {lev:>3d}x | {m['sharpe']:>7.2f} " + f"${m['total_pnl']:>+10,.0f} {m['total_ret']:>+7.1f}% " + f"{m['wr']:>5.1f}% {m['trades']:>5d} {r['max_drawdown']:>5.1f}% " + f"${monthly_pnl:>+8,.0f}") + except Exception as e: + print(f" {ws:>5d} {lev:>3d}x | ERROR: {e}") + + # ══════════════════════════════════════════════════ + # PHASE 2: Select optimal params per asset + # ══════════════════════════════════════════════════ + print(f"\n{'='*80}") + print("PHASE 2: OPTIMAL PARAMS PER ASSET (max PnL)") + print(f"{'='*80}") + + optimal = {} + print(f"\n {'Asset':<10s} {'TF':>3s} | {'Best WS':>7s} {'Lev':>4s} | " + f"{'Sharpe':>7s} {'PnL':>12s} {'Ret%':>8s} {'DD%':>6s} {'$/mo':>10s}") + print(f" {'-'*75}") + + for symbol, ticker, tf in ASSETS: + if ticker not in grid_results or not grid_results[ticker]: + continue + + # Select by max PnL + best = max(grid_results[ticker], key=lambda x: x["total_pnl"]) + optimal[ticker] = {"ws": best["ws"], "leverage": best["leverage"], + "tf": tf, "sharpe": best["sharpe"], + "max_drawdown": best["max_drawdown"], + "total_pnl": best["total_pnl"]} + + print(f" {ticker:<10s} {tf:>3s} | {best['ws']:>5d} {best['leverage']:>2d}x | " + f"{best['sharpe']:>7.2f} ${best['total_pnl']:>+10,.0f} " + f"{best['total_ret']:>+7.1f}% {best['max_drawdown']:>5.1f}% " + f"${best['monthly_pnl']:>+8,.0f}") + + # ══════════════════════════════════════════════════ + # PHASE 3: Calculate risk-adjusted weights + # ══════════════════════════════════════════════════ + print(f"\n{'='*80}") + print("PHASE 3: RISK-ADJUSTED ALLOCATION (Sharpe/DD)") + print(f"{'='*80}") + + # weight_i = (Sharpe_i / DD_i) / sum(Sharpe_j / DD_j) + ratios = {} + for ticker, p in optimal.items(): + dd = max(p["max_drawdown"], 0.1) # avoid div by zero + ratios[ticker] = p["sharpe"] / dd + + total_ratio = sum(ratios.values()) + weights = {t: r / total_ratio for t, r in ratios.items()} + + print(f"\n {'Asset':<10s} {'Sharpe':>7s} {'DD%':>6s} {'Ratio':>8s} {'Weight':>7s} {'$114':>7s}") + print(f" {'-'*50}") + for ticker in sorted(weights, key=lambda t: weights[t], reverse=True): + p = optimal[ticker] + print(f" {ticker:<10s} {p['sharpe']:>7.2f} {p['max_drawdown']:>5.1f}% " + f"{ratios[ticker]:>8.3f} {weights[ticker]*100:>6.1f}% " + f"${TOTAL_PORTFOLIO * weights[ticker]:>6.2f}") + + # ══════════════════════════════════════════════════ + # PHASE 4: Portfolio simulation with optimal params + # ══════════════════════════════════════════════════ + print(f"\n{'='*80}") + print("PHASE 4: PORTFOLIO SIMULATION ($114)") + print(f"{'='*80}") + + # Build asset params + asset_params = {} + for ticker, p in optimal.items(): + asset_params[ticker] = { + "ws": p["ws"], "leverage": p["leverage"], + "weight": round(weights[ticker], 4), + "tf": p["tf"], + } + + # Config A: CURRENT (equal, ws=64, 2x) + current_params = {} + for symbol, ticker, tf in ASSETS: + current_params[ticker] = { + "ws": 64, "leverage": 2, + "weight": round(1/7, 4), "tf": tf, + } + + configs = [ + ("CURRENT (equal, ws=64, 2x)", current_params), + ("OPTIMAL (grid-searched)", asset_params), + ] + + portfolio_results = {} + for name, params in configs: + print(f"\n Running: {name}...") + r = run_portfolio(params, price_cache) + r["config_name"] = name + portfolio_results[name] = r + + # Print + print(f"\n {'='*78}") + print(f" {name}") + print(f" {'='*78}") + print(f" Capital: ${r['total_capital']:.0f} → ${r['final_equity']:.2f} " + f"(PnL: ${r['total_pnl']:+.2f}, {r['total_ret']:+.1f}%)") + print(f" Total trades: {r['total_trades']}") + + stats = r["asset_stats"] + if stats: + print(f"\n {'Asset':<10s} {'WS':>4s} {'Lev':>4s} {'Wt%':>5s} " + f"{'Init$':>7s} {'Final$':>8s} {'PnL$':>9s} " + f"{'Sharpe':>7s} {'WR%':>5s} {'Trds':>5s} {'$/mo':>8s}") + print(f" {'-'*78}") + + sorted_stats = sorted(stats.items(), key=lambda x: x[1]["pnl"], reverse=True) + for ticker, s in sorted_stats: + print(f" {ticker:<10s} {s['ws']:>4d} {s['leverage']:>3d}x {s['weight']*100:>4.1f}% " + f"${s['initial']:>6.2f} ${s['final']:>7.2f} ${s['pnl']:>+8.2f} " + f"{s['sharpe']:>7.2f} {s['wr']:>4.1f}% {s['trades']:>5d} ${s['monthly_pnl']:>+7.2f}") + + total_monthly = sum(s["monthly_pnl"] for s in stats.values()) + print(f" {'-'*78}") + print(f" {'TOTAL':<10s} {'':>4s} {'':>4s} {'100%':>5s} " + f"${r['total_capital']:>6.0f} ${r['final_equity']:>7.2f} " + f"${r['total_pnl']:>+8.2f} " + f"{'':>7s} {'':>5s} {r['total_trades']:>5d} ${total_monthly:>+7.2f}") + + # ══════════════════════════════════════════════════ + # COMPARISON + # ══════════════════════════════════════════════════ + if len(portfolio_results) == 2: + r_cur = list(portfolio_results.values())[0] + r_opt = list(portfolio_results.values())[1] + print(f"\n{'='*60}") + print("COMPARISON: CURRENT vs OPTIMAL") + print(f"{'='*60}") + print(f" {'Metric':<20s} {'Current':>12s} {'Optimal':>12s} {'Delta':>12s}") + print(f" {'-'*56}") + for label, k in [("Final Equity", "final_equity"), ("Total PnL", "total_pnl"), + ("Return %", "total_ret"), ("Trades", "total_trades")]: + v1, v2 = r_cur[k], r_opt[k] + d = v2 - v1 + if k in ("final_equity", "total_pnl"): + print(f" {label:<20s} ${v1:>11.2f} ${v2:>11.2f} ${d:>+11.2f}") + elif k == "total_ret": + print(f" {label:<20s} {v1:>11.1f}% {v2:>11.1f}% {d:>+11.1f}%") + else: + print(f" {label:<20s} {v1:>12d} {v2:>12d} {d:>+12d}") + + # ══════════════════════════════════════════════════ + # DEPLOY-READY CONFIG + # ══════════════════════════════════════════════════ + print(f"\n{'='*60}") + print("DEPLOY-READY CONFIG") + print(f"{'='*60}") + for symbol, ticker, tf in ASSETS: + if ticker in asset_params: + p = asset_params[ticker] + print(f" {ticker:<10s} tf={tf} ws={p['ws']:>3d} lev={p['leverage']}x " + f"weight={p['weight']*100:.1f}% (${TOTAL_PORTFOLIO * p['weight']:.2f})") + + # Save + save_data = { + "grid_results": grid_results, + "optimal_params": {t: {**p, "weight": round(weights.get(t, 0), 4)} + for t, p in optimal.items()}, + "weights": {t: round(w, 4) for t, w in weights.items()}, + "portfolio_results": portfolio_results, + } + path = save_results(save_data, results_dir, "exp15_grid_search") + print(f"\nSaved: {path}") + + +if __name__ == "__main__": + main() diff --git a/experiments/exp15_grid_search/run_sharpe_optimal.py b/experiments/exp15_grid_search/run_sharpe_optimal.py new file mode 100644 index 0000000..fa489cd --- /dev/null +++ b/experiments/exp15_grid_search/run_sharpe_optimal.py @@ -0,0 +1,150 @@ +"""Exp15b: Portfolio sim with Sharpe-optimal params on $114. + +Uses max-Sharpe criterion (not max-PnL) from grid search. +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from run import run_portfolio, ASSETS, TOTAL_PORTFOLIO +from remizov_trader.core import signals +from common.metrics import save_results + +# Sharpe-optimal params from exp15 grid search /wait analysis +SHARPE_OPTIMAL = { + "ETH-USD": {"ws": 64, "leverage": 2, "weight": 0.147, "tf": "2h"}, + "SOL-USD": {"ws": 128, "leverage": 2, "weight": 0.100, "tf": "2h"}, + "BTC-USD": {"ws": 32, "leverage": 2, "weight": 0.224, "tf": "4h"}, + "DOGE-USD": {"ws": 48, "leverage": 2, "weight": 0.118, "tf": "4h"}, + "ADA-USD": {"ws": 64, "leverage": 2, "weight": 0.127, "tf": "4h"}, + "XRP-USD": {"ws": 64, "leverage": 2, "weight": 0.085, "tf": "4h"}, + "DOT-USD": {"ws": 32, "leverage": 2, "weight": 0.127, "tf": "4h"}, +} + +# PnL-optimal (from grid search Phase 2) +PNL_OPTIMAL = { + "ETH-USD": {"ws": 64, "leverage": 2, "weight": 0.164, "tf": "2h"}, + "SOL-USD": {"ws": 128, "leverage": 2, "weight": 0.111, "tf": "2h"}, + "BTC-USD": {"ws": 32, "leverage": 2, "weight": 0.249, "tf": "4h"}, + "DOGE-USD": {"ws": 48, "leverage": 2, "weight": 0.131, "tf": "4h"}, + "ADA-USD": {"ws": 32, "leverage": 2, "weight": 0.113, "tf": "4h"}, + "XRP-USD": {"ws": 96, "leverage": 2, "weight": 0.092, "tf": "4h"}, + "DOT-USD": {"ws": 32, "leverage": 2, "weight": 0.141, "tf": "4h"}, +} + +# Current baseline +CURRENT = { + "ETH-USD": {"ws": 64, "leverage": 2, "weight": round(1/7, 4), "tf": "2h"}, + "SOL-USD": {"ws": 64, "leverage": 2, "weight": round(1/7, 4), "tf": "2h"}, + "BTC-USD": {"ws": 64, "leverage": 2, "weight": round(1/7, 4), "tf": "4h"}, + "DOGE-USD": {"ws": 64, "leverage": 2, "weight": round(1/7, 4), "tf": "4h"}, + "ADA-USD": {"ws": 64, "leverage": 2, "weight": round(1/7, 4), "tf": "4h"}, + "XRP-USD": {"ws": 64, "leverage": 2, "weight": round(1/7, 4), "tf": "4h"}, + "DOT-USD": {"ws": 64, "leverage": 2, "weight": round(1/7, 4), "tf": "4h"}, +} + + +def print_result(name, r): + print(f"\n {'='*78}") + print(f" {name}") + print(f" {'='*78}") + print(f" Capital: ${r['total_capital']:.0f} → ${r['final_equity']:.2f} " + f"(PnL: ${r['total_pnl']:+.2f}, {r['total_ret']:+.1f}%)") + print(f" Total trades: {r['total_trades']}") + + stats = r["asset_stats"] + if not stats: + print(" No trades!") + return + + print(f"\n {'Asset':<10s} {'WS':>4s} {'Lev':>4s} {'Wt%':>5s} " + f"{'Init$':>7s} {'Final$':>8s} {'PnL$':>9s} " + f"{'Sharpe':>7s} {'WR%':>5s} {'Trds':>5s} {'$/mo':>8s}") + print(f" {'-'*78}") + + sorted_stats = sorted(stats.items(), key=lambda x: x[1]["pnl"], reverse=True) + for ticker, s in sorted_stats: + print(f" {ticker:<10s} {s['ws']:>4d} {s['leverage']:>3d}x {s['weight']*100:>4.1f}% " + f"${s['initial']:>6.2f} ${s['final']:>7.2f} ${s['pnl']:>+8.2f} " + f"{s['sharpe']:>7.2f} {s['wr']:>4.1f}% {s['trades']:>5d} ${s['monthly_pnl']:>+7.2f}") + + total_monthly = sum(s["monthly_pnl"] for s in stats.values()) + print(f" {'-'*78}") + print(f" {'TOTAL':<10s} {'':>4s} {'':>4s} {'100%':>5s} " + f"${r['total_capital']:>6.0f} ${r['final_equity']:>7.2f} " + f"${r['total_pnl']:>+8.2f} " + f"{'':>7s} {'':>5s} {r['total_trades']:>5d} ${total_monthly:>+7.2f}") + + +def main(): + results_dir = Path(__file__).parent / "results" + + # Fetch data + price_cache = {} + for symbol, ticker, tf in ASSETS: + print(f"Fetching {ticker} ({tf})...", end=" ", flush=True) + try: + prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max") + if prices is not None: + price_cache[ticker] = (prices, dates, tf) + print(f"{len(prices)} bars") + else: + print("SKIP") + except Exception as e: + print(f"ERROR: {e}") + + configs = [ + ("A: CURRENT (equal, ws=64, 2x)", CURRENT), + ("B: SHARPE-OPTIMAL (max Sharpe, Sharpe/DD weights)", SHARPE_OPTIMAL), + ("C: PNL-OPTIMAL (max PnL, Sharpe/DD weights)", PNL_OPTIMAL), + ] + + results = {} + for name, params in configs: + print(f"\nRunning: {name}...") + r = run_portfolio(params, price_cache) + results[name] = r + print_result(name, r) + + # Comparison + print(f"\n{'='*75}") + print("COMPARISON: A vs B vs C") + print(f"{'='*75}") + names = list(results.keys()) + print(f" {'Metric':<16s}", end="") + for n in names: + label = n.split(":")[0] + ":" + n.split(":")[1][:15] + print(f" {label:>18s}", end="") + print() + print(f" {'-'*70}") + + for label, k in [("Final $", "final_equity"), ("PnL $", "total_pnl"), + ("Return %", "total_ret"), ("Trades", "total_trades")]: + print(f" {label:<16s}", end="") + for n in names: + v = results[n][k] + if k in ("final_equity", "total_pnl"): + print(f" ${v:>16.2f}", end="") + elif k == "total_ret": + print(f" {v:>16.1f}%", end="") + else: + print(f" {v:>17d}", end="") + print() + + # Monthly PnL comparison + print(f"\n {'$/mo':<16s}", end="") + for n in names: + stats = results[n]["asset_stats"] + total_monthly = sum(s["monthly_pnl"] for s in stats.values()) + print(f" ${total_monthly:>16.2f}", end="") + print() + + # Save + path = save_results(results, results_dir, "exp15b_sharpe_optimal") + print(f"\nSaved: {path}") + + +if __name__ == "__main__": + main()