feat: фиксированный датасет + per-asset K бэктест (BTC=3, ADA=3)
- common/dataset.py: сохранение/загрузка фиксированного датасета для воспроизводимых экспериментов (данные больше не плывут между запусками) - exp18 run.py, run_per_asset_k.py: переведены на load_or_fetch() - exp18b результат: BTC=3+ADA=3 даёт +$23 (+20.4%) при DD -0.6% (Equity $265.45 vs $242.26 uniform K=2) - Применено в продакшн: config.yaml BTC K=3, ADA K=3 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -8,3 +8,4 @@ data/models/
|
||||
data/trades.db
|
||||
.DS_Store
|
||||
.env
|
||||
experiments/data/
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Fixed dataset management for reproducible experiments.
|
||||
|
||||
Save once with save_dataset.py, then load in any experiment.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
DATA_DIR = Path(__file__).parent.parent / "data"
|
||||
|
||||
ASSETS = [
|
||||
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
|
||||
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
|
||||
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
|
||||
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
|
||||
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
|
||||
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
|
||||
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
|
||||
]
|
||||
|
||||
|
||||
def save_dataset(name: str = "default") -> Path:
|
||||
"""Fetch all assets from exchange and save as fixed dataset."""
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
|
||||
from remizov_trader.core.signals import fetch_prices_ccxt
|
||||
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
dataset_dir = DATA_DIR / name
|
||||
dataset_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
meta = {"assets": {}}
|
||||
|
||||
for a in ASSETS:
|
||||
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
|
||||
print(f" Fetching {ticker} ({tf})...", end=" ", flush=True)
|
||||
|
||||
prices, dates = fetch_prices_ccxt(symbol, tf, "max")
|
||||
if prices is None or len(prices) < 100:
|
||||
print("SKIP (not enough data)")
|
||||
continue
|
||||
|
||||
# Save prices as .npy, dates as strings in .json
|
||||
np.save(dataset_dir / f"{ticker}_prices.npy", prices)
|
||||
dates_str = [str(d) for d in dates]
|
||||
(dataset_dir / f"{ticker}_dates.json").write_text(json.dumps(dates_str))
|
||||
|
||||
meta["assets"][ticker] = {
|
||||
"symbol": symbol, "tf": tf, "ws": a["ws"],
|
||||
"leverage": a["leverage"], "weight": a["weight"],
|
||||
"bars": len(prices),
|
||||
"date_range": f"{dates_str[0]} -> {dates_str[-1]}",
|
||||
}
|
||||
print(f"{len(prices)} bars ({dates_str[0][:10]} -> {dates_str[-1][:10]})")
|
||||
|
||||
from datetime import datetime
|
||||
meta["created"] = datetime.now().isoformat()
|
||||
meta["name"] = name
|
||||
(dataset_dir / "meta.json").write_text(json.dumps(meta, indent=2))
|
||||
|
||||
print(f"\nDataset saved: {dataset_dir}")
|
||||
return dataset_dir
|
||||
|
||||
|
||||
def load_dataset(name: str = "default") -> dict:
|
||||
"""Load fixed dataset. Returns dict[ticker] -> {prices, dates, tf, ws, ...}."""
|
||||
dataset_dir = DATA_DIR / name
|
||||
if not dataset_dir.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Dataset '{name}' not found at {dataset_dir}. "
|
||||
f"Run: .venv/bin/python3 experiments/common/save_dataset.py"
|
||||
)
|
||||
|
||||
meta_path = dataset_dir / "meta.json"
|
||||
meta = json.loads(meta_path.read_text())
|
||||
|
||||
result = {}
|
||||
for ticker, info in meta["assets"].items():
|
||||
prices = np.load(dataset_dir / f"{ticker}_prices.npy")
|
||||
dates_str = json.loads((dataset_dir / f"{ticker}_dates.json").read_text())
|
||||
# Convert to numpy array of date strings for compatibility
|
||||
dates = np.array(dates_str)
|
||||
|
||||
result[ticker] = {
|
||||
"prices": prices,
|
||||
"dates": dates,
|
||||
"tf": info["tf"],
|
||||
"ws": info["ws"],
|
||||
"leverage": info["leverage"],
|
||||
"weight": info["weight"],
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def load_or_fetch(name: str = "default") -> dict:
|
||||
"""Load dataset if exists, otherwise fetch and save."""
|
||||
try:
|
||||
return load_dataset(name)
|
||||
except FileNotFoundError:
|
||||
print(f"Dataset '{name}' not found, fetching from exchange...")
|
||||
save_dataset(name)
|
||||
return load_dataset(name)
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Save fixed dataset from exchange for reproducible experiments.
|
||||
|
||||
Usage:
|
||||
.venv/bin/python3 experiments/common/save_dataset.py [name]
|
||||
|
||||
Default name: "default". Run once, then all experiments use this data.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
|
||||
|
||||
from dataset import save_dataset
|
||||
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else "default"
|
||||
print(f"Saving dataset '{name}'...")
|
||||
save_dataset(name)
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
{
|
||||
"config": {
|
||||
"k_values": [
|
||||
2,
|
||||
3,
|
||||
4
|
||||
],
|
||||
"stop_scales": [
|
||||
0.5,
|
||||
1.0
|
||||
],
|
||||
"corr_thresh": 0.5,
|
||||
"assets": [
|
||||
{
|
||||
"symbol": "BTC/USDC",
|
||||
"ticker": "BTC-USD",
|
||||
"tf": "4h",
|
||||
"ws": 32,
|
||||
"leverage": 2,
|
||||
"weight": 0.241
|
||||
},
|
||||
{
|
||||
"symbol": "ETH/USDC",
|
||||
"ticker": "ETH-USD",
|
||||
"tf": "2h",
|
||||
"ws": 64,
|
||||
"leverage": 2,
|
||||
"weight": 0.158
|
||||
},
|
||||
{
|
||||
"symbol": "ADA/USDC",
|
||||
"ticker": "ADA-USD",
|
||||
"tf": "4h",
|
||||
"ws": 64,
|
||||
"leverage": 2,
|
||||
"weight": 0.137
|
||||
},
|
||||
{
|
||||
"symbol": "DOT/USDC",
|
||||
"ticker": "DOT-USD",
|
||||
"tf": "4h",
|
||||
"ws": 32,
|
||||
"leverage": 2,
|
||||
"weight": 0.137
|
||||
},
|
||||
{
|
||||
"symbol": "DOGE/USDC",
|
||||
"ticker": "DOGE-USD",
|
||||
"tf": "4h",
|
||||
"ws": 48,
|
||||
"leverage": 2,
|
||||
"weight": 0.127
|
||||
},
|
||||
{
|
||||
"symbol": "SOL/USDC",
|
||||
"ticker": "SOL-USD",
|
||||
"tf": "2h",
|
||||
"ws": 128,
|
||||
"leverage": 2,
|
||||
"weight": 0.108
|
||||
},
|
||||
{
|
||||
"symbol": "XRP/USDC",
|
||||
"ticker": "XRP-USD",
|
||||
"tf": "4h",
|
||||
"ws": 64,
|
||||
"leverage": 2,
|
||||
"weight": 0.092
|
||||
}
|
||||
]
|
||||
},
|
||||
"results": {
|
||||
"K=2_ss=0.5": {
|
||||
"trades": 912,
|
||||
"wins": 396,
|
||||
"losses": 516,
|
||||
"wr": 43.4,
|
||||
"total_pnl": 197.42,
|
||||
"total_ret": 173.2,
|
||||
"sharpe": 3.79,
|
||||
"avg_win": 1.13,
|
||||
"avg_loss": -0.48,
|
||||
"max_dd": 5.7,
|
||||
"final_equity": 311.42,
|
||||
"skipped_low_corr": 2361,
|
||||
"skipped_cooldown": 598,
|
||||
"skipped_correlation": 274,
|
||||
"skipped_spot_short": 1211,
|
||||
"skipped_no_margin": 0,
|
||||
"corr_unique_values": 3,
|
||||
"corr_mean": 0.011,
|
||||
"corr_std": 0.998,
|
||||
"corr_pct_positive": 50.4,
|
||||
"years": 1.91
|
||||
},
|
||||
"K=2_ss=1.0": {
|
||||
"trades": 966,
|
||||
"wins": 423,
|
||||
"losses": 543,
|
||||
"wr": 43.8,
|
||||
"total_pnl": 62.38,
|
||||
"total_ret": 54.7,
|
||||
"sharpe": 1.6,
|
||||
"avg_win": 0.87,
|
||||
"avg_loss": -0.56,
|
||||
"max_dd": 13.4,
|
||||
"final_equity": 176.38,
|
||||
"skipped_low_corr": 2437,
|
||||
"skipped_cooldown": 442,
|
||||
"skipped_correlation": 286,
|
||||
"skipped_spot_short": 1225,
|
||||
"skipped_no_margin": 0,
|
||||
"corr_unique_values": 3,
|
||||
"corr_mean": 0.011,
|
||||
"corr_std": 0.999,
|
||||
"corr_pct_positive": 50.4,
|
||||
"years": 1.91
|
||||
},
|
||||
"K=3_ss=0.5": {
|
||||
"trades": 783,
|
||||
"wins": 334,
|
||||
"losses": 449,
|
||||
"wr": 42.7,
|
||||
"total_pnl": 116.43,
|
||||
"total_ret": 102.1,
|
||||
"sharpe": 2.14,
|
||||
"avg_win": 0.9,
|
||||
"avg_loss": -0.41,
|
||||
"max_dd": 4.8,
|
||||
"final_equity": 230.43,
|
||||
"skipped_low_corr": 2970,
|
||||
"skipped_cooldown": 471,
|
||||
"skipped_correlation": 198,
|
||||
"skipped_spot_short": 934,
|
||||
"skipped_no_margin": 0,
|
||||
"corr_unique_values": 201,
|
||||
"corr_mean": -0.001,
|
||||
"corr_std": 0.789,
|
||||
"corr_pct_positive": 49.9,
|
||||
"years": 1.91
|
||||
},
|
||||
"K=3_ss=1.0": {
|
||||
"trades": 811,
|
||||
"wins": 338,
|
||||
"losses": 473,
|
||||
"wr": 41.7,
|
||||
"total_pnl": 34.58,
|
||||
"total_ret": 30.3,
|
||||
"sharpe": 0.82,
|
||||
"avg_win": 0.75,
|
||||
"avg_loss": -0.46,
|
||||
"max_dd": 9.6,
|
||||
"final_equity": 148.58,
|
||||
"skipped_low_corr": 3063,
|
||||
"skipped_cooldown": 324,
|
||||
"skipped_correlation": 207,
|
||||
"skipped_spot_short": 951,
|
||||
"skipped_no_margin": 0,
|
||||
"corr_unique_values": 201,
|
||||
"corr_mean": -0.002,
|
||||
"corr_std": 0.788,
|
||||
"corr_pct_positive": 49.8,
|
||||
"years": 1.91
|
||||
},
|
||||
"K=4_ss=0.5": {
|
||||
"trades": 755,
|
||||
"wins": 353,
|
||||
"losses": 402,
|
||||
"wr": 46.8,
|
||||
"total_pnl": 77.72,
|
||||
"total_ret": 68.2,
|
||||
"sharpe": 1.86,
|
||||
"avg_win": 0.67,
|
||||
"avg_loss": -0.39,
|
||||
"max_dd": 5.7,
|
||||
"final_equity": 191.72,
|
||||
"skipped_low_corr": 3156,
|
||||
"skipped_cooldown": 339,
|
||||
"skipped_correlation": 208,
|
||||
"skipped_spot_short": 898,
|
||||
"skipped_no_margin": 0,
|
||||
"corr_unique_values": 201,
|
||||
"corr_mean": 0.01,
|
||||
"corr_std": 0.724,
|
||||
"corr_pct_positive": 50.9,
|
||||
"years": 1.91
|
||||
},
|
||||
"K=4_ss=1.0": {
|
||||
"trades": 782,
|
||||
"wins": 358,
|
||||
"losses": 424,
|
||||
"wr": 45.8,
|
||||
"total_pnl": 16.62,
|
||||
"total_ret": 14.6,
|
||||
"sharpe": 0.44,
|
||||
"avg_win": 0.57,
|
||||
"avg_loss": -0.44,
|
||||
"max_dd": 10.9,
|
||||
"final_equity": 130.62,
|
||||
"skipped_low_corr": 3223,
|
||||
"skipped_cooldown": 233,
|
||||
"skipped_correlation": 215,
|
||||
"skipped_spot_short": 903,
|
||||
"skipped_no_margin": 0,
|
||||
"corr_unique_values": 201,
|
||||
"corr_mean": 0.009,
|
||||
"corr_std": 0.724,
|
||||
"corr_pct_positive": 50.9,
|
||||
"years": 1.91
|
||||
}
|
||||
}
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
{
|
||||
"config": {
|
||||
"total_capital": 114.0,
|
||||
"slippage": 0.0005,
|
||||
"commission": 0.001,
|
||||
"interest_rate": 0.0002,
|
||||
"stop_scale": 0.5,
|
||||
"k_configs": {
|
||||
"uniform_K2": {
|
||||
"BTC-USD": 2,
|
||||
"ETH-USD": 2,
|
||||
"ADA-USD": 2,
|
||||
"DOT-USD": 2,
|
||||
"DOGE-USD": 2,
|
||||
"SOL-USD": 2,
|
||||
"XRP-USD": 2
|
||||
},
|
||||
"btc_ada_K3": {
|
||||
"BTC-USD": 3,
|
||||
"ETH-USD": 2,
|
||||
"ADA-USD": 3,
|
||||
"DOT-USD": 2,
|
||||
"DOGE-USD": 2,
|
||||
"SOL-USD": 2,
|
||||
"XRP-USD": 2
|
||||
}
|
||||
},
|
||||
"assets": [
|
||||
{
|
||||
"symbol": "BTC/USDC",
|
||||
"ticker": "BTC-USD",
|
||||
"tf": "4h",
|
||||
"ws": 32,
|
||||
"leverage": 2,
|
||||
"weight": 0.241
|
||||
},
|
||||
{
|
||||
"symbol": "ETH/USDC",
|
||||
"ticker": "ETH-USD",
|
||||
"tf": "2h",
|
||||
"ws": 64,
|
||||
"leverage": 2,
|
||||
"weight": 0.158
|
||||
},
|
||||
{
|
||||
"symbol": "ADA/USDC",
|
||||
"ticker": "ADA-USD",
|
||||
"tf": "4h",
|
||||
"ws": 64,
|
||||
"leverage": 2,
|
||||
"weight": 0.137
|
||||
},
|
||||
{
|
||||
"symbol": "DOT/USDC",
|
||||
"ticker": "DOT-USD",
|
||||
"tf": "4h",
|
||||
"ws": 32,
|
||||
"leverage": 2,
|
||||
"weight": 0.137
|
||||
},
|
||||
{
|
||||
"symbol": "DOGE/USDC",
|
||||
"ticker": "DOGE-USD",
|
||||
"tf": "4h",
|
||||
"ws": 48,
|
||||
"leverage": 2,
|
||||
"weight": 0.127
|
||||
},
|
||||
{
|
||||
"symbol": "SOL/USDC",
|
||||
"ticker": "SOL-USD",
|
||||
"tf": "2h",
|
||||
"ws": 128,
|
||||
"leverage": 2,
|
||||
"weight": 0.108
|
||||
},
|
||||
{
|
||||
"symbol": "XRP/USDC",
|
||||
"ticker": "XRP-USD",
|
||||
"tf": "4h",
|
||||
"ws": 64,
|
||||
"leverage": 2,
|
||||
"weight": 0.092
|
||||
}
|
||||
]
|
||||
},
|
||||
"results": {
|
||||
"uniform_K2": {
|
||||
"trades": 912,
|
||||
"wins": 367,
|
||||
"losses": 545,
|
||||
"wr": 40.2,
|
||||
"total_pnl": 128.26,
|
||||
"total_ret": 112.5,
|
||||
"sharpe": 2.89,
|
||||
"avg_win": 0.99,
|
||||
"avg_loss": -0.43,
|
||||
"max_dd": 6.9,
|
||||
"final_equity": 242.26,
|
||||
"total_slippage": 43.24,
|
||||
"total_interest": 1.84,
|
||||
"skipped_low_corr": 2358,
|
||||
"skipped_cooldown": 600,
|
||||
"skipped_correlation": 274,
|
||||
"skipped_spot_short": 1212,
|
||||
"skipped_no_margin": 0,
|
||||
"years": 1.91
|
||||
},
|
||||
"btc_ada_K3": {
|
||||
"trades": 885,
|
||||
"wins": 350,
|
||||
"losses": 535,
|
||||
"wr": 39.5,
|
||||
"total_pnl": 151.45,
|
||||
"total_ret": 132.9,
|
||||
"sharpe": 2.38,
|
||||
"avg_win": 1.14,
|
||||
"avg_loss": -0.46,
|
||||
"max_dd": 6.3,
|
||||
"final_equity": 265.45,
|
||||
"total_slippage": 44.66,
|
||||
"total_interest": 1.78,
|
||||
"skipped_low_corr": 2509,
|
||||
"skipped_cooldown": 576,
|
||||
"skipped_correlation": 243,
|
||||
"skipped_spot_short": 1143,
|
||||
"skipped_no_margin": 0,
|
||||
"years": 1.91
|
||||
}
|
||||
},
|
||||
"asset_results": {
|
||||
"uniform_K2": {
|
||||
"BTC-USD": {
|
||||
"trades": 95,
|
||||
"wins": 36,
|
||||
"losses": 59,
|
||||
"wr": 37.9,
|
||||
"total_pnl": 15.51,
|
||||
"total_ret": 56.4,
|
||||
"sharpe": 0.71,
|
||||
"avg_win": 1.37,
|
||||
"avg_loss": -0.57,
|
||||
"corr_unique": 2,
|
||||
"corr_mean": -0.004,
|
||||
"corr_pct_positive": 49.8
|
||||
},
|
||||
"ETH-USD": {
|
||||
"trades": 185,
|
||||
"wins": 76,
|
||||
"losses": 109,
|
||||
"wr": 41.1,
|
||||
"total_pnl": 21.1,
|
||||
"total_ret": 117.1,
|
||||
"sharpe": 1.52,
|
||||
"avg_win": 0.85,
|
||||
"avg_loss": -0.4,
|
||||
"corr_unique": 2,
|
||||
"corr_mean": 0.009,
|
||||
"corr_pct_positive": 50.5
|
||||
},
|
||||
"ADA-USD": {
|
||||
"trades": 79,
|
||||
"wins": 38,
|
||||
"losses": 41,
|
||||
"wr": 48.1,
|
||||
"total_pnl": 14.93,
|
||||
"total_ret": 95.6,
|
||||
"sharpe": 1.25,
|
||||
"avg_win": 1.06,
|
||||
"avg_loss": -0.62,
|
||||
"corr_unique": 3,
|
||||
"corr_mean": 0.011,
|
||||
"corr_pct_positive": 50.1
|
||||
},
|
||||
"DOT-USD": {
|
||||
"trades": 101,
|
||||
"wins": 38,
|
||||
"losses": 63,
|
||||
"wr": 37.6,
|
||||
"total_pnl": 14.83,
|
||||
"total_ret": 95.0,
|
||||
"sharpe": 0.69,
|
||||
"avg_win": 1.2,
|
||||
"avg_loss": -0.49,
|
||||
"corr_unique": 3,
|
||||
"corr_mean": 0.054,
|
||||
"corr_pct_positive": 52.1
|
||||
},
|
||||
"DOGE-USD": {
|
||||
"trades": 139,
|
||||
"wins": 60,
|
||||
"losses": 79,
|
||||
"wr": 43.2,
|
||||
"total_pnl": 39.88,
|
||||
"total_ret": 275.4,
|
||||
"sharpe": 1.84,
|
||||
"avg_win": 1.36,
|
||||
"avg_loss": -0.53,
|
||||
"corr_unique": 2,
|
||||
"corr_mean": 0.01,
|
||||
"corr_pct_positive": 50.5
|
||||
},
|
||||
"SOL-USD": {
|
||||
"trades": 242,
|
||||
"wins": 96,
|
||||
"losses": 146,
|
||||
"wr": 39.7,
|
||||
"total_pnl": 18.89,
|
||||
"total_ret": 153.4,
|
||||
"sharpe": 1.37,
|
||||
"avg_win": 0.66,
|
||||
"avg_loss": -0.3,
|
||||
"corr_unique": 3,
|
||||
"corr_mean": 0.018,
|
||||
"corr_pct_positive": 50.9
|
||||
},
|
||||
"XRP-USD": {
|
||||
"trades": 71,
|
||||
"wins": 23,
|
||||
"losses": 48,
|
||||
"wr": 32.4,
|
||||
"total_pnl": 3.13,
|
||||
"total_ret": 29.8,
|
||||
"sharpe": 0.36,
|
||||
"avg_win": 0.86,
|
||||
"avg_loss": -0.35,
|
||||
"corr_unique": 3,
|
||||
"corr_mean": -0.021,
|
||||
"corr_pct_positive": 48.7
|
||||
}
|
||||
},
|
||||
"btc_ada_K3": {
|
||||
"BTC-USD": {
|
||||
"trades": 79,
|
||||
"wins": 29,
|
||||
"losses": 50,
|
||||
"wr": 36.7,
|
||||
"total_pnl": 13.92,
|
||||
"total_ret": 50.7,
|
||||
"sharpe": 0.72,
|
||||
"avg_win": 1.51,
|
||||
"avg_loss": -0.6,
|
||||
"corr_unique": 164,
|
||||
"corr_mean": 0.012,
|
||||
"corr_pct_positive": 50.5
|
||||
},
|
||||
"ETH-USD": {
|
||||
"trades": 188,
|
||||
"wins": 77,
|
||||
"losses": 111,
|
||||
"wr": 41.0,
|
||||
"total_pnl": 12.13,
|
||||
"total_ret": 67.3,
|
||||
"sharpe": 1.18,
|
||||
"avg_win": 0.8,
|
||||
"avg_loss": -0.44,
|
||||
"corr_unique": 2,
|
||||
"corr_mean": 0.005,
|
||||
"corr_pct_positive": 50.3
|
||||
},
|
||||
"ADA-USD": {
|
||||
"trades": 64,
|
||||
"wins": 26,
|
||||
"losses": 38,
|
||||
"wr": 40.6,
|
||||
"total_pnl": 34.99,
|
||||
"total_ret": 224.0,
|
||||
"sharpe": 0.82,
|
||||
"avg_win": 2.25,
|
||||
"avg_loss": -0.62,
|
||||
"corr_unique": 158,
|
||||
"corr_mean": -0.042,
|
||||
"corr_pct_positive": 47.4
|
||||
},
|
||||
"DOT-USD": {
|
||||
"trades": 102,
|
||||
"wins": 39,
|
||||
"losses": 63,
|
||||
"wr": 38.2,
|
||||
"total_pnl": 29.45,
|
||||
"total_ret": 188.6,
|
||||
"sharpe": 1.02,
|
||||
"avg_win": 1.61,
|
||||
"avg_loss": -0.53,
|
||||
"corr_unique": 3,
|
||||
"corr_mean": 0.035,
|
||||
"corr_pct_positive": 51.2
|
||||
},
|
||||
"DOGE-USD": {
|
||||
"trades": 139,
|
||||
"wins": 60,
|
||||
"losses": 79,
|
||||
"wr": 43.2,
|
||||
"total_pnl": 43.6,
|
||||
"total_ret": 301.1,
|
||||
"sharpe": 1.84,
|
||||
"avg_win": 1.47,
|
||||
"avg_loss": -0.57,
|
||||
"corr_unique": 2,
|
||||
"corr_mean": 0.01,
|
||||
"corr_pct_positive": 50.5
|
||||
},
|
||||
"SOL-USD": {
|
||||
"trades": 242,
|
||||
"wins": 96,
|
||||
"losses": 146,
|
||||
"wr": 39.7,
|
||||
"total_pnl": 20.08,
|
||||
"total_ret": 163.1,
|
||||
"sharpe": 1.37,
|
||||
"avg_win": 0.71,
|
||||
"avg_loss": -0.33,
|
||||
"corr_unique": 3,
|
||||
"corr_mean": 0.018,
|
||||
"corr_pct_positive": 50.9
|
||||
},
|
||||
"XRP-USD": {
|
||||
"trades": 71,
|
||||
"wins": 23,
|
||||
"losses": 48,
|
||||
"wr": 32.4,
|
||||
"total_pnl": -2.72,
|
||||
"total_ret": -26.0,
|
||||
"sharpe": 0.01,
|
||||
"avg_win": 0.68,
|
||||
"avg_loss": -0.38,
|
||||
"corr_unique": 3,
|
||||
"corr_mean": -0.017,
|
||||
"corr_pct_positive": 48.9
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import torch
|
||||
from remizov_trader.core import model as model_mod, signals, risk
|
||||
from remizov_trader.config import ModelConfig
|
||||
from common.metrics import compute_metrics, save_results, compare_results, print_metrics
|
||||
from common.dataset import load_or_fetch, ASSETS as DATASET_ASSETS
|
||||
|
||||
TOTAL_CAPITAL = 114.0
|
||||
CORR_THRESH = 0.5
|
||||
@@ -316,21 +317,25 @@ def main():
|
||||
print(f"Capital: ${TOTAL_CAPITAL} | Stop scales: {STOP_SCALES} | K values: {K_VALUES}")
|
||||
print()
|
||||
|
||||
# Fetch data + train models (once, shared across all K variants)
|
||||
# Load fixed dataset + train models
|
||||
dataset = load_or_fetch()
|
||||
asset_data = {}
|
||||
max_k = max(K_VALUES)
|
||||
|
||||
for a in ASSETS:
|
||||
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
|
||||
ticker = a["ticker"]
|
||||
ws, leverage, weight = a["ws"], a["leverage"], a["weight"]
|
||||
tf = a["tf"]
|
||||
|
||||
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
|
||||
try:
|
||||
prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max")
|
||||
except Exception as e:
|
||||
print(f"FETCH ERROR: {e}")
|
||||
if ticker not in dataset:
|
||||
print(f" {ticker}: not in dataset")
|
||||
continue
|
||||
if prices is None or len(prices) < ws + max_k + SHIFT + 30:
|
||||
|
||||
ds = dataset[ticker]
|
||||
prices, dates = ds["prices"], ds["dates"]
|
||||
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
|
||||
|
||||
if len(prices) < ws + max_k + SHIFT + 30:
|
||||
print("not enough data")
|
||||
continue
|
||||
|
||||
|
||||
@@ -0,0 +1,491 @@
|
||||
"""Exp18b: Per-asset optimal K with realistic slippage.
|
||||
|
||||
Best K per asset (from exp18 grid):
|
||||
BTC=3, ETH=2, ADA=3, DOT=4, DOGE=2, SOL=2, XRP=2
|
||||
|
||||
Compared against uniform K=2 (current production config).
|
||||
Uses same realistic Bybit margin simulation as exp16 + slippage.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
|
||||
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
|
||||
from common.metrics import compute_metrics, save_results
|
||||
from common.dataset import load_or_fetch
|
||||
|
||||
TOTAL_CAPITAL = 114.0
|
||||
CORR_THRESH = 0.5
|
||||
TRAILING_STOP = True
|
||||
TRAIN_RATIO = 0.3
|
||||
SHIFT = 7
|
||||
|
||||
INTEREST_RATE_DAILY = 0.0002
|
||||
COMMISSION = 0.001
|
||||
SLIPPAGE = 0.0005 # 0.05% per side (market order execution)
|
||||
|
||||
CORRELATED_GROUPS = [
|
||||
{"BTC-USD", "ETH-USD"},
|
||||
{"ADA-USD", "DOT-USD", "XRP-USD"},
|
||||
]
|
||||
|
||||
ASSETS = [
|
||||
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
|
||||
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
|
||||
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
|
||||
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
|
||||
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
|
||||
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
|
||||
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
|
||||
]
|
||||
|
||||
# Per-asset K configs to compare
|
||||
K_CONFIGS = {
|
||||
"uniform_K2": {t["ticker"]: 2 for t in ASSETS},
|
||||
"btc_ada_K3": {
|
||||
"BTC-USD": 3,
|
||||
"ETH-USD": 2,
|
||||
"ADA-USD": 3,
|
||||
"DOT-USD": 2,
|
||||
"DOGE-USD": 2,
|
||||
"SOL-USD": 2,
|
||||
"XRP-USD": 2,
|
||||
},
|
||||
}
|
||||
|
||||
STOP_SCALE = 0.5 # production value
|
||||
|
||||
|
||||
@dataclass
|
||||
class Position:
|
||||
ticker: str
|
||||
direction: int
|
||||
entry_price: float
|
||||
entry_date: str
|
||||
stop_price: float
|
||||
stop_dist: float
|
||||
best_price: float
|
||||
pos_size: float
|
||||
pos_value: float
|
||||
margin_locked: float
|
||||
borrowed: float
|
||||
k_used: int
|
||||
entry_bar: int
|
||||
|
||||
|
||||
def check_correlation_conflict(open_positions: dict, ticker: str, direction: int) -> bool:
|
||||
for g in CORRELATED_GROUPS:
|
||||
if ticker not in g:
|
||||
continue
|
||||
for other in g:
|
||||
if other == ticker:
|
||||
continue
|
||||
if other in open_positions and open_positions[other].direction == direction:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def run_simulation(asset_data: dict, events: list, k_map: dict) -> dict:
|
||||
"""Run simulation with per-asset K values."""
|
||||
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
|
||||
|
||||
free_usdc = TOTAL_CAPITAL
|
||||
open_positions: dict[str, Position] = {}
|
||||
all_trades = []
|
||||
per_asset_trades: dict[str, list] = {t: [] for t in asset_data}
|
||||
last_stop_date: dict[str, str] = {}
|
||||
skipped_no_margin = 0
|
||||
skipped_cooldown = 0
|
||||
skipped_correlation = 0
|
||||
skipped_spot_short = 0
|
||||
skipped_low_corr = 0
|
||||
total_interest_paid = 0.0
|
||||
total_slippage_cost = 0.0
|
||||
peak_equity = TOTAL_CAPITAL
|
||||
max_drawdown = 0.0
|
||||
equity_curve = []
|
||||
|
||||
corr_values_per_asset: dict[str, list] = {t: [] for t in asset_data}
|
||||
|
||||
for date, ticker, window in events:
|
||||
ad = asset_data[ticker]
|
||||
prices = ad["prices"]
|
||||
price_idx = window["price_idx"]
|
||||
current_price = float(prices[price_idx])
|
||||
ws = ad["ws"]
|
||||
leverage = ad["leverage"]
|
||||
weight = ad["weight"]
|
||||
K = k_map[ticker]
|
||||
|
||||
# Check open position
|
||||
if ticker in open_positions:
|
||||
pos = open_positions[ticker]
|
||||
bar_hours = tf_hours.get(ad["tf"], 4)
|
||||
|
||||
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
|
||||
for bar_idx in range(check_from, price_idx + 1):
|
||||
if bar_idx >= len(prices):
|
||||
break
|
||||
bar_price = float(prices[bar_idx])
|
||||
|
||||
if TRAILING_STOP:
|
||||
pos.best_price, pos.stop_price = risk.update_trailing_stop(
|
||||
bar_price, pos.best_price, pos.stop_price,
|
||||
pos.stop_dist, pos.direction)
|
||||
|
||||
stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction)
|
||||
bars_held = bar_idx - pos.entry_bar
|
||||
time_exit = bars_held >= (SHIFT - pos.k_used)
|
||||
|
||||
if stopped or time_exit:
|
||||
exit_price = pos.stop_price if stopped else bar_price
|
||||
# Slippage on exit
|
||||
slip_exit = exit_price * SLIPPAGE * (-pos.direction)
|
||||
exit_price_actual = exit_price + slip_exit
|
||||
exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
|
||||
|
||||
pnl_gross = pos.pos_size * (exit_price_actual - pos.entry_price) * pos.direction
|
||||
commission_cost = pos.pos_value * COMMISSION * 2
|
||||
hold_hours = bars_held * bar_hours
|
||||
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
|
||||
slippage_cost = abs(slip_exit) * pos.pos_size + pos.entry_price * SLIPPAGE * pos.pos_size
|
||||
total_interest_paid += trade_interest
|
||||
total_slippage_cost += slippage_cost
|
||||
pnl_net = pnl_gross - commission_cost - trade_interest
|
||||
|
||||
free_usdc += pos.margin_locked + pnl_net
|
||||
del open_positions[ticker]
|
||||
|
||||
trade = {
|
||||
"ticker": ticker, "pnl_net": pnl_net, "pnl_gross": pnl_gross,
|
||||
"commission": commission_cost, "interest": trade_interest,
|
||||
"slippage": slippage_cost,
|
||||
"equity_at_entry": pos.margin_locked,
|
||||
"exit_reason": "stop" if stopped else "time",
|
||||
"bars_held": bars_held, "date": exit_date,
|
||||
"entry_price": pos.entry_price, "exit_price": exit_price_actual,
|
||||
"direction": pos.direction, "k_used": K,
|
||||
}
|
||||
all_trades.append(trade)
|
||||
per_asset_trades[ticker].append(trade)
|
||||
if stopped:
|
||||
last_stop_date[ticker] = exit_date
|
||||
|
||||
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
|
||||
peak_equity = max(peak_equity, total_equity)
|
||||
dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0
|
||||
max_drawdown = max(max_drawdown, dd)
|
||||
equity_curve.append({"date": exit_date, "equity": round(total_equity, 2)})
|
||||
break
|
||||
|
||||
# New signal
|
||||
if ticker not in open_positions and price_idx >= ws + K:
|
||||
# Cooldown
|
||||
if ticker in last_stop_date:
|
||||
from datetime import date as d
|
||||
days_since = (d.fromisoformat(date[:10]) -
|
||||
d.fromisoformat(last_stop_date[ticker][:10])).days
|
||||
bar_h = tf_hours.get(ad["tf"], 4)
|
||||
candles_since = days_since * 24 // bar_h
|
||||
if candles_since < SHIFT:
|
||||
skipped_cooldown += 1
|
||||
continue
|
||||
|
||||
# Signal with per-asset 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(ad["model"], norm_input)
|
||||
pred_new = pred[-SHIFT:]
|
||||
corr, confirmed = signals.check_shape_confirmation(
|
||||
pred_new, confirm, mu, std, K, CORR_THRESH)
|
||||
|
||||
corr_values_per_asset[ticker].append(corr)
|
||||
|
||||
if not confirmed:
|
||||
skipped_low_corr += 1
|
||||
continue
|
||||
|
||||
direction = signals.get_direction(pred_new, K)
|
||||
if direction is None:
|
||||
continue
|
||||
|
||||
if direction == -1:
|
||||
skipped_spot_short += 1
|
||||
continue
|
||||
|
||||
if check_correlation_conflict(open_positions, ticker, direction):
|
||||
skipped_correlation += 1
|
||||
continue
|
||||
|
||||
# Slippage on entry
|
||||
entry_price = current_price * (1 + SLIPPAGE) # buy higher
|
||||
|
||||
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
|
||||
pos_value = total_equity * weight * leverage
|
||||
if pos_value < 5.0:
|
||||
continue
|
||||
|
||||
margin_needed = pos_value / leverage
|
||||
if free_usdc < margin_needed:
|
||||
margin_needed = free_usdc * 0.95
|
||||
pos_value = margin_needed * leverage
|
||||
if pos_value < 5.0:
|
||||
skipped_no_margin += 1
|
||||
continue
|
||||
|
||||
pos_size = pos_value / entry_price
|
||||
borrowed = pos_value - margin_needed
|
||||
|
||||
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 * STOP_SCALE, entry_price * 0.005)
|
||||
|
||||
free_usdc -= margin_needed
|
||||
open_positions[ticker] = Position(
|
||||
ticker=ticker, direction=direction,
|
||||
entry_price=entry_price, entry_date=date,
|
||||
stop_price=entry_price - direction * stop_dist,
|
||||
stop_dist=stop_dist, best_price=entry_price,
|
||||
pos_size=pos_size, pos_value=pos_value,
|
||||
margin_locked=margin_needed, borrowed=borrowed,
|
||||
k_used=k_adj, entry_bar=price_idx,
|
||||
)
|
||||
|
||||
# Close remaining
|
||||
for ticker, pos in list(open_positions.items()):
|
||||
ad = asset_data[ticker]
|
||||
last_price = float(ad["prices"][-1])
|
||||
exit_price = last_price * (1 - SLIPPAGE)
|
||||
pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
|
||||
commission_cost = pos.pos_value * COMMISSION * 2
|
||||
last_bar = ad["test_data"][-1]["price_idx"]
|
||||
bars_held = last_bar - pos.entry_bar
|
||||
bar_hours = tf_hours.get(ad["tf"], 4)
|
||||
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
|
||||
pnl_net = pnl_gross - commission_cost - trade_interest
|
||||
|
||||
free_usdc += pos.margin_locked + pnl_net
|
||||
trade = {
|
||||
"ticker": ticker, "pnl_net": pnl_net, "pnl_gross": pnl_gross,
|
||||
"commission": commission_cost, "interest": trade_interest,
|
||||
"slippage": 0, "equity_at_entry": pos.margin_locked,
|
||||
"exit_reason": "end", "bars_held": bars_held,
|
||||
"date": str(ad["dates"][-1]),
|
||||
"entry_price": pos.entry_price, "exit_price": exit_price,
|
||||
"direction": pos.direction, "k_used": k_map[ticker],
|
||||
}
|
||||
all_trades.append(trade)
|
||||
per_asset_trades[ticker].append(trade)
|
||||
|
||||
final_equity = free_usdc
|
||||
|
||||
# Years
|
||||
if events:
|
||||
from datetime import date as d
|
||||
first = d.fromisoformat(events[0][0][:10])
|
||||
last = d.fromisoformat(events[-1][0][:10])
|
||||
years = (last - first).days / 365.25
|
||||
else:
|
||||
years = 1.0
|
||||
|
||||
metrics = compute_metrics(all_trades, TOTAL_CAPITAL, years)
|
||||
metrics["max_dd"] = round(max_drawdown * 100, 1)
|
||||
metrics["final_equity"] = round(final_equity, 2)
|
||||
metrics["total_slippage"] = round(total_slippage_cost, 2)
|
||||
metrics["total_interest"] = round(total_interest_paid, 2)
|
||||
metrics["skipped_low_corr"] = skipped_low_corr
|
||||
metrics["skipped_cooldown"] = skipped_cooldown
|
||||
metrics["skipped_correlation"] = skipped_correlation
|
||||
metrics["skipped_spot_short"] = skipped_spot_short
|
||||
metrics["skipped_no_margin"] = skipped_no_margin
|
||||
metrics["years"] = round(years, 2)
|
||||
|
||||
asset_metrics = {}
|
||||
for a in ASSETS:
|
||||
t = a["ticker"]
|
||||
trades = per_asset_trades.get(t, [])
|
||||
if trades:
|
||||
am = compute_metrics(trades, a["weight"] * TOTAL_CAPITAL, years)
|
||||
# Correlation stats
|
||||
cv = corr_values_per_asset.get(t, [])
|
||||
if cv:
|
||||
ca = np.array(cv)
|
||||
am["corr_unique"] = len(np.unique(np.round(ca, 2)))
|
||||
am["corr_mean"] = round(float(ca.mean()), 3)
|
||||
am["corr_pct_positive"] = round(float((ca > 0).sum() / len(ca) * 100), 1)
|
||||
asset_metrics[t] = am
|
||||
|
||||
return {"metrics": metrics, "asset_metrics": asset_metrics,
|
||||
"trades": all_trades, "equity_curve": equity_curve}
|
||||
|
||||
|
||||
def main():
|
||||
results_dir = Path(__file__).parent / "results"
|
||||
|
||||
print(f"{'='*80}")
|
||||
print("EXP18b: PER-ASSET OPTIMAL K (with slippage 0.05%)")
|
||||
print(f"{'='*80}")
|
||||
print(f"Capital: ${TOTAL_CAPITAL} | Slippage: {SLIPPAGE*100:.2f}%/side | "
|
||||
f"Commission: {COMMISSION*100:.1f}%/side")
|
||||
print()
|
||||
|
||||
# Load fixed dataset + train models
|
||||
dataset = load_or_fetch()
|
||||
asset_data = {}
|
||||
max_k = 4
|
||||
|
||||
for a in ASSETS:
|
||||
ticker = a["ticker"]
|
||||
ws, leverage, weight = a["ws"], a["leverage"], a["weight"]
|
||||
tf = a["tf"]
|
||||
|
||||
if ticker not in dataset:
|
||||
print(f" {ticker}: not in dataset")
|
||||
continue
|
||||
|
||||
ds = dataset[ticker]
|
||||
prices, dates = ds["prices"], ds["dates"]
|
||||
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
|
||||
|
||||
if len(prices) < ws + max_k + SHIFT + 30:
|
||||
print("not enough data")
|
||||
continue
|
||||
|
||||
data = signals.prepare_windows(prices, ws, SHIFT)
|
||||
if len(data) < 30:
|
||||
print(f"only {len(data)} windows")
|
||||
continue
|
||||
|
||||
n_train = max(int(len(data) * TRAIN_RATIO), 20)
|
||||
train_data = data[:n_train]
|
||||
test_data = data[n_train:]
|
||||
|
||||
model_cfg = ModelConfig(
|
||||
window_size=ws, n_steps=20, total_time=0.5,
|
||||
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003,
|
||||
)
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(model_cfg)
|
||||
windows_arr = np.array([d["norm_input"] for d in train_data])
|
||||
targets_arr = np.array([d["norm_target"] for d in train_data])
|
||||
model_mod.train(mdl, windows_arr, targets_arr, 200, 0.003)
|
||||
|
||||
asset_data[ticker] = {
|
||||
"prices": prices, "dates": dates, "tf": tf,
|
||||
"model": mdl, "test_data": test_data,
|
||||
"ws": ws, "leverage": leverage, "weight": weight,
|
||||
}
|
||||
print(f"{len(prices)} bars, {len(test_data)} test windows")
|
||||
|
||||
if not asset_data:
|
||||
print("No data!")
|
||||
return
|
||||
|
||||
# Build timeline
|
||||
events = []
|
||||
for ticker, ad in asset_data.items():
|
||||
for d in ad["test_data"]:
|
||||
price_idx = d["price_idx"]
|
||||
date = str(ad["dates"][price_idx])
|
||||
events.append((date, ticker, d))
|
||||
events.sort(key=lambda x: x[0])
|
||||
print(f"\n Events: {len(events)} | Range: {events[0][0]} -> {events[-1][0]}")
|
||||
|
||||
# Run both configs
|
||||
all_results = {}
|
||||
for config_name, k_map in K_CONFIGS.items():
|
||||
k_desc = " ".join(f"{t.replace('-USD','')}={k}" for t, k in k_map.items())
|
||||
print(f"\n{'─'*60}")
|
||||
print(f" {config_name}: {k_desc}")
|
||||
result = run_simulation(asset_data, events, k_map)
|
||||
all_results[config_name] = result
|
||||
m = result["metrics"]
|
||||
print(f" Equity: ${m['final_equity']} | Trades: {m['trades']} | "
|
||||
f"WR: {m['wr']}% | Sharpe: {m['sharpe']} | DD: {m['max_dd']}%")
|
||||
print(f" Slippage: ${m['total_slippage']} | Interest: ${m['total_interest']} | "
|
||||
f"Margin skips: {m['skipped_no_margin']}")
|
||||
|
||||
# Comparison
|
||||
print(f"\n{'='*80}")
|
||||
print("COMPARISON: uniform K=2 vs per-asset optimal K")
|
||||
print(f"{'='*80}")
|
||||
|
||||
u = all_results["uniform_K2"]["metrics"]
|
||||
exp_name = [k for k in K_CONFIGS if k != "uniform_K2"][0]
|
||||
p = all_results[exp_name]["metrics"]
|
||||
|
||||
rows = [
|
||||
("Equity", f"${u['final_equity']}", f"${p['final_equity']}", f"${p['final_equity']-u['final_equity']:+.2f}"),
|
||||
("Return", f"{u['total_ret']:+.1f}%", f"{p['total_ret']:+.1f}%", f"{p['total_ret']-u['total_ret']:+.1f}%"),
|
||||
("Trades", str(u['trades']), str(p['trades']), f"{p['trades']-u['trades']:+d}"),
|
||||
("WR", f"{u['wr']}%", f"{p['wr']}%", f"{p['wr']-u['wr']:+.1f}%"),
|
||||
("Sharpe", f"{u['sharpe']}", f"{p['sharpe']}", f"{p['sharpe']-u['sharpe']:+.2f}"),
|
||||
("MaxDD", f"{u['max_dd']}%", f"{p['max_dd']}%", f"{p['max_dd']-u['max_dd']:+.1f}%"),
|
||||
("Slippage", f"${u['total_slippage']}", f"${p['total_slippage']}", ""),
|
||||
("NoMargin", str(u['skipped_no_margin']), str(p['skipped_no_margin']), ""),
|
||||
]
|
||||
|
||||
print(f"\n {'Metric':<12s} {'K=2 uniform':>14s} {'Per-asset':>14s} {'Delta':>12s}")
|
||||
print(f" {'─'*52}")
|
||||
for name, v1, v2, delta in rows:
|
||||
print(f" {name:<12s} {v1:>14s} {v2:>14s} {delta:>12s}")
|
||||
|
||||
# Per-asset detail
|
||||
print(f"\n{'='*80}")
|
||||
print("PER-ASSET DETAIL")
|
||||
print(f"{'='*80}")
|
||||
print(f"\n {'Asset':<10s} {'K':>2s} {'Trds':>5s} {'WR':>6s} {'PnL':>10s} "
|
||||
f"{'Sharpe':>7s} {'CorrUniq':>9s} {'Corr%+':>7s}")
|
||||
print(f" {'─'*60}")
|
||||
|
||||
for config_name in ["uniform_K2", exp_name]:
|
||||
label = "K=2" if "uniform" in config_name else "OPT"
|
||||
print(f"\n [{label}]")
|
||||
for a in ASSETS:
|
||||
t = a["ticker"]
|
||||
am = all_results[config_name]["asset_metrics"].get(t, {})
|
||||
k = K_CONFIGS[config_name][t]
|
||||
if am:
|
||||
cu = am.get("corr_unique", "?")
|
||||
cp = am.get("corr_pct_positive", "?")
|
||||
print(f" {t:<10s} {k:>2d} {am['trades']:>5d} {am['wr']:>5.1f}% "
|
||||
f"${am['total_pnl']:>+9.2f} {am['sharpe']:>7.2f} "
|
||||
f"{cu:>9} {cp:>6}%")
|
||||
else:
|
||||
print(f" {t:<10s} {k:>2d} no trades")
|
||||
|
||||
# Save
|
||||
save_data = {
|
||||
"config": {
|
||||
"total_capital": TOTAL_CAPITAL,
|
||||
"slippage": SLIPPAGE,
|
||||
"commission": COMMISSION,
|
||||
"interest_rate": INTEREST_RATE_DAILY,
|
||||
"stop_scale": STOP_SCALE,
|
||||
"k_configs": K_CONFIGS,
|
||||
"assets": ASSETS,
|
||||
},
|
||||
"results": {name: r["metrics"] for name, r in all_results.items()},
|
||||
"asset_results": {
|
||||
name: r["asset_metrics"] for name, r in all_results.items()
|
||||
},
|
||||
}
|
||||
path = save_results(save_data, results_dir, "exp18b_per_asset_k")
|
||||
print(f"\nSaved: {path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user