Files
remizov-trader/experiments/exp16_realistic_sim/run.py
T
anorandClaude Opus 4.6 536e32261a feat: exp16-17 бэктесты (реалистичный Bybit, OHLC, объёмы)
- exp16: реалистичная симуляция Bybit spot margin
- exp16b: grid search stop_scale (0.75x лучший)
- exp16c-d: check frequency + time_exit analysis
- exp16e: комбо-тест stop_scale × time_exit (0.5x + no TE → Sharpe 4.15)
- exp16f: OHLC валидация (Close-only = production behavior)
- exp17: объёмы (VWAP +9% Sharpe, vol_filter WR 51%)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 02:16:09 +10:00

487 lines
20 KiB
Python

"""Exp16: Realistic Bybit spot margin simulation.
Key differences from exp15:
- Single shared USDC pool (not per-asset equity)
- Margin requirement: pos_value / leverage locked as collateral
- Positions compete for same capital
- Interest on borrowed amount (~0.02%/day)
- Cooldown after stop (shift candles)
- Correlation groups (BTC+ETH, ADA+DOT+XRP)
- Chronological bar-by-bar processing across all assets
"""
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
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAILING_STOP = True
TRAIN_RATIO = 0.3
SHIFT = 7
# Bybit spot margin
INTEREST_RATE_DAILY = 0.0002 # 0.02%/day on borrowed amount
COMMISSION = 0.001 # 0.1% per side
# Correlation groups — same as production
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
# Sharpe-optimal config from exp15
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},
]
@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 # USDC locked as collateral
borrowed: float # amount borrowed from exchange
k_used: int
entry_bar: int
def check_correlation_conflict(open_positions: dict, ticker: str, direction: int) -> str | None:
"""Check if opening conflicts with correlated open position."""
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 f"correlated with {other} {'LONG' if direction == 1 else 'SHORT'} — SKIP"
return None
def main():
results_dir = Path(__file__).parent / "results"
# ══════════════════════════════════════════════════
# FETCH DATA + TRAIN MODELS
# ══════════════════════════════════════════════════
print(f"{'='*80}")
print("EXP16: REALISTIC BYBIT SPOT MARGIN SIMULATION")
print(f"{'='*80}")
print(f"Capital: ${TOTAL_CAPITAL} | Interest: {INTEREST_RATE_DAILY*100:.3f}%/day | "
f"Commission: {COMMISSION*100:.1f}%/side")
print()
asset_data = {} # ticker -> {prices, dates, tf, model, test_data, ws, leverage, weight}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws, leverage, weight = a["ws"], a["leverage"], a["weight"]
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}")
continue
if prices is None or len(prices) < ws + 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 CHRONOLOGICAL EVENT TIMELINE
# ══════════════════════════════════════════════════
# Each test window is a potential signal check point.
# Collect all (date, ticker, window_data) and sort by date.
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]) # chronological order
print(f"\n Total events: {len(events)} across {len(asset_data)} assets")
print(f" Date range: {events[0][0]} → {events[-1][0]}")
# ══════════════════════════════════════════════════
# SIMULATE WITH SHARED USDC POOL
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("SIMULATION")
print(f"{'='*80}\n")
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] = {} # ticker -> date of last stop
skipped_no_margin = 0
skipped_cooldown = 0
skipped_correlation = 0
skipped_spot_short = 0
total_interest_paid = 0.0
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
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"]
# --- Check open position for this asset (every bar, not just windows) ---
if ticker in open_positions:
pos = open_positions[ticker]
bar_hours = tf_hours.get(ad["tf"], 4)
closed = False
# Check EVERY bar from last check to current price_idx
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
exit_bar_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
pnl_gross = pos.pos_size * (exit_price - 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
total_interest_paid += trade_interest
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,
"equity_at_entry": pos.margin_locked,
"exit_reason": "stop" if stopped else "time",
"bars_held": bars_held, "date": exit_bar_date,
"entry_price": pos.entry_price, "exit_price": exit_price,
"direction": pos.direction,
}
all_trades.append(trade)
per_asset_trades[ticker].append(trade)
if stopped:
last_stop_date[ticker] = exit_bar_date
# Track drawdown on realized equity
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)
closed = True
break
if closed:
pass # position already handled
# --- Check for new signal (if no position) ---
if ticker not in open_positions and price_idx >= ws + K:
# Cooldown after stop
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 generation
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)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None:
continue
# Spot mode: skip SHORT
if direction == -1:
skipped_spot_short += 1
continue
# Correlation filter
conflict = check_correlation_conflict(open_positions, ticker, direction)
if conflict:
skipped_correlation += 1
continue
# Position sizing: weight-based
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: # Bybit minimum
continue
# Margin check: need pos_value / leverage as collateral
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
# Try reduced position with available margin
margin_needed = free_usdc * 0.95 # keep 5% buffer
pos_value = margin_needed * leverage
if pos_value < 5.0:
skipped_no_margin += 1
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed # borrowed from exchange
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)
# Lock margin
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price, entry_date=date,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
)
# Close any remaining open positions at last price
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
pnl_gross = pos.pos_size * (last_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,
"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": last_price,
"direction": pos.direction,
}
all_trades.append(trade)
per_asset_trades[ticker].append(trade)
final_equity = free_usdc
# ══════════════════════════════════════════════════
# RESULTS
# ══════════════════════════════════════════════════
total_pnl = final_equity - TOTAL_CAPITAL
total_ret = total_pnl / TOTAL_CAPITAL * 100
total_commission = sum(t["commission"] for t in all_trades)
# Compute years from date range
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
wins = [t for t in all_trades if t["pnl_net"] > 0]
losses = [t for t in all_trades if t["pnl_net"] <= 0]
print(f"\n{'='*80}")
print("RESULTS: REALISTIC BYBIT SIMULATION")
print(f"{'='*80}")
print(f"\n Capital: ${TOTAL_CAPITAL:.0f} → ${final_equity:.2f} "
f"(PnL: ${total_pnl:+.2f}, {total_ret:+.1f}%)")
print(f" Max Drawdown: {max_drawdown*100:.1f}%")
print(f" Trades: {len(all_trades)} ({len(wins)} wins, {len(losses)} losses)")
if all_trades:
wr = len(wins) / len(all_trades) * 100
print(f" Win Rate: {wr:.1f}%")
print(f" Total Commission: ${total_commission:.2f}")
print(f" Total Interest: ${total_interest_paid:.2f}")
print()
print(f" Skipped (no margin): {skipped_no_margin}")
print(f" Skipped (cooldown): {skipped_cooldown}")
print(f" Skipped (correlation): {skipped_correlation}")
print(f" Skipped (spot short): {skipped_spot_short}")
if len(all_trades) > 1 and years > 0:
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in all_trades if t["equity_at_entry"] > 0])
tpy = len(all_trades) / years
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
monthly_pnl = total_pnl / months if months > 0 else 0
print(f"\n Sharpe: {sharpe:.2f}")
print(f" Monthly PnL: ${monthly_pnl:.2f}")
print(f" Period: {years:.1f} years")
# Per-asset breakdown
print(f"\n {'Asset':<10s} {'TF':>3s} {'WS':>4s} {'Lev':>4s} {'Wt%':>5s} "
f"{'Trds':>5s} {'Wins':>5s} {'WR%':>5s} {'PnL':>10s} {'Comm':>7s} {'Int':>6s}")
print(f" {'-'*75}")
for a in ASSETS:
ticker = a["ticker"]
trades = per_asset_trades.get(ticker, [])
if not trades:
print(f" {ticker:<10s} {a['tf']:>3s} {a['ws']:>4d} {a['leverage']:>3d}x "
f"{a['weight']*100:>4.1f}% {'':>5s} {'':>5s} {'':>5s} {'no trades':>10s}")
continue
w = [t for t in trades if t["pnl_net"] > 0]
pnl = sum(t["pnl_net"] for t in trades)
comm = sum(t["commission"] for t in trades)
intr = sum(t["interest"] for t in trades)
wr = len(w) / len(trades) * 100
print(f" {ticker:<10s} {a['tf']:>3s} {a['ws']:>4d} {a['leverage']:>3d}x "
f"{a['weight']*100:>4.1f}% {len(trades):>5d} {len(w):>5d} {wr:>4.1f}% "
f"${pnl:>+9.2f} ${comm:>6.2f} ${intr:>5.2f}")
# ══════════════════════════════════════════════════
# COMPARISON: exp15 (no margin) vs exp16 (realistic)
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("IMPACT OF REALISTIC MARGIN SIMULATION")
print(f"{'='*80}")
print(f"\n {'Metric':<25s} {'exp15 (ideal)':>15s} {'exp16 (real)':>15s}")
print(f" {'-'*55}")
print(f" {'Margin model':<25s} {'per-asset':>15s} {'shared USDC':>15s}")
print(f" {'Interest':<25s} {'none':>15s} {'0.02%/day':>15s}")
print(f" {'Cooldown after stop':<25s} {'none':>15s} {f'{SHIFT} candles':>15s}")
print(f" {'Correlation filter':<25s} {'none':>15s} {'yes':>15s}")
print(f" {'Skipped (no margin)':<25s} {'0':>15s} {skipped_no_margin:>15d}")
print(f" {'Total interest paid':<25s} {'$0.00':>15s} ${total_interest_paid:>14.2f}")
print(f" {'Final equity':<25s} {'':>15s} ${final_equity:>14.2f}")
print(f" {'Max drawdown':<25s} {'':>15s} {max_drawdown*100:>14.1f}%")
# Save
save_data = {
"config": {
"total_capital": TOTAL_CAPITAL,
"interest_rate": INTEREST_RATE_DAILY,
"commission": COMMISSION,
"cooldown_candles": SHIFT,
"assets": ASSETS,
},
"results": {
"final_equity": round(final_equity, 2),
"total_pnl": round(total_pnl, 2),
"total_ret": round(total_ret, 1),
"max_drawdown": round(max_drawdown * 100, 1),
"total_trades": len(all_trades),
"wins": len(wins),
"wr": round(len(wins) / len(all_trades) * 100, 1) if all_trades else 0,
"total_commission": round(total_commission, 2),
"total_interest": round(total_interest_paid, 2),
"skipped_no_margin": skipped_no_margin,
"skipped_cooldown": skipped_cooldown,
"skipped_correlation": skipped_correlation,
"skipped_spot_short": skipped_spot_short,
"years": round(years, 2),
},
"trades": all_trades,
}
path = save_results(save_data, results_dir, "exp16_realistic")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()