Files
remizov-trader/experiments/exp14_portfolio_sim/run.py
T
anorandClaude Opus 4.6 ff51c5e5cf 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>
2026-03-09 23:38:49 +10:00

374 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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()