- 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>
492 lines
18 KiB
Python
492 lines
18 KiB
Python
"""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()
|