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:
anor
2026-03-09 23:38:49 +10:00
co-authored by Claude Opus 4.6
parent 5351cefe08
commit ff51c5e5cf
8 changed files with 2856 additions and 0 deletions
View File
+93
View File
@@ -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}")
@@ -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
}
}
}
}
+373
View File
@@ -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()
@@ -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
}
}
}
}
+549
View File
@@ -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()
@@ -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()