"""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()