Без комиссий: 30m fallback добавляет +133% ADA, +145% DOGE С комиссиями: 30m edge (~0.27%/trade) < round-trip 0.2% → убыток Вывод: каскад не работает с реальными комиссиями Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
423 lines
14 KiB
Python
423 lines
14 KiB
Python
"""Exp30c: Realistic cascade backtest with Bybit margin model.
|
|
|
|
4h primary + 30m fallback for miss periods.
|
|
Full costs: commission 0.1%, interest 0.02%/day, CVR/haircut.
|
|
"""
|
|
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))
|
|
|
|
import numpy as np
|
|
import torch
|
|
|
|
from remizov_trader.core import model as model_mod, signals, risk
|
|
from remizov_trader.core.net import EnhancedRemizovNet
|
|
from remizov_trader.core.signals import fetch_ohlcv_ccxt
|
|
from common.metrics import save_results
|
|
|
|
TOTAL_CAPITAL = 254.0
|
|
SHIFT = 7
|
|
MIN_CONFIDENCE = 1.5
|
|
TRAIN_RATIO = 0.3
|
|
|
|
COMMISSION_PCT = 0.001 # 0.1% per trade
|
|
INTEREST_RATE_DAILY = 0.0002 # 0.02%/day
|
|
CVR = 0.85
|
|
SPOT_IM = 0.05
|
|
MARKET_ORDER_BUFFER = 0.02
|
|
|
|
ASSETS = [
|
|
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "ws": 64, "K": 3},
|
|
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "ws": 48, "K": 2},
|
|
]
|
|
|
|
# Configs to compare
|
|
MODES = ["4h_only", "4h+30m", "4h+30m+retrain"]
|
|
|
|
|
|
def _train_model(prices, ws):
|
|
data = signals.prepare_windows(prices, ws, SHIFT)
|
|
n_train = max(int(len(data) * TRAIN_RATIO), 20)
|
|
train, test = data[:n_train], data[n_train:]
|
|
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
|
|
dx=1.0 / ws, use_sde=True)
|
|
w = np.array([d["norm_input"] for d in train])
|
|
t = np.array([d["norm_target"] for d in train])
|
|
model_mod.train(mdl, w, t, 200, 0.003)
|
|
return mdl, train, test
|
|
|
|
|
|
def _check_signal(mdl, prices, idx, ws, K):
|
|
"""Check for a valid long signal at idx. Returns (conf, corr) or None."""
|
|
if idx < ws + K or idx + SHIFT >= len(prices):
|
|
return None
|
|
|
|
w = prices[idx - ws - K:idx - K].copy()
|
|
confirm = prices[idx - K:idx].copy()
|
|
mu, std = w.mean(), w.std()
|
|
if std < 1e-10:
|
|
return None
|
|
|
|
pred = model_mod.predict(mdl, (w - mu) / std)
|
|
pred_new = pred[-SHIFT:]
|
|
|
|
corr_thresh = 0.5
|
|
corr, confirmed = signals.check_shape_confirmation(
|
|
pred_new, confirm, mu, std, K, corr_thresh)
|
|
if not confirmed:
|
|
return None
|
|
|
|
atr = risk.compute_atr(prices, idx)
|
|
if atr <= 0:
|
|
return None
|
|
|
|
pred_denorm = pred_new * std + mu
|
|
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
|
|
conf = abs(corr) * (amp / atr)
|
|
if conf < MIN_CONFIDENCE:
|
|
return None
|
|
|
|
direction = signals.get_direction(pred_new, K)
|
|
if direction != 1:
|
|
return None
|
|
|
|
return {"conf": conf, "corr": float(corr), "atr": atr}
|
|
|
|
|
|
def _open_position(equity, price, atr, K, prices, idx, leverage=2):
|
|
"""Open position, return frozen capital and position info."""
|
|
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
|
|
stop_dist = max(atr * stop_mult * 0.5, price * 0.005)
|
|
|
|
pos_value = equity * leverage
|
|
if pos_value < 5.0:
|
|
return None
|
|
|
|
margin = pos_value / leverage
|
|
borrowed = pos_value - margin
|
|
haircut = (1.0 - CVR) * pos_value
|
|
spot_im = borrowed * SPOT_IM
|
|
buf = pos_value * MARKET_ORDER_BUFFER
|
|
total_frozen = margin + haircut + spot_im + buf
|
|
|
|
if total_frozen > equity:
|
|
# Cap position
|
|
freeze_rate = 1/leverage + (1-CVR) + (1-1/leverage)*SPOT_IM + MARKET_ORDER_BUFFER
|
|
pos_value = equity / freeze_rate
|
|
if pos_value < 5.0:
|
|
return None
|
|
margin = pos_value / leverage
|
|
borrowed = pos_value - margin
|
|
|
|
return {
|
|
"entry_price": price,
|
|
"entry_idx": idx,
|
|
"stop_price": price - stop_dist,
|
|
"stop_dist": stop_dist,
|
|
"best_price": price,
|
|
"pos_size": pos_value / price,
|
|
"pos_value": pos_value,
|
|
"margin": margin,
|
|
"borrowed": borrowed,
|
|
}
|
|
|
|
|
|
def _close_position(pos, exit_price, exit_idx, tf_minutes):
|
|
"""Close position, compute PnL with costs."""
|
|
bars_held = exit_idx - pos["entry_idx"]
|
|
hours_held = bars_held * tf_minutes / 60
|
|
|
|
pnl_gross = pos["pos_size"] * (exit_price - pos["entry_price"])
|
|
commission = pos["pos_value"] * COMMISSION_PCT * 2
|
|
interest = pos["borrowed"] * INTEREST_RATE_DAILY * hours_held / 24
|
|
|
|
return {
|
|
"pnl_gross": pnl_gross,
|
|
"commission": commission,
|
|
"interest": interest,
|
|
"pnl_net": pnl_gross - commission - interest,
|
|
"bars_held": bars_held,
|
|
}
|
|
|
|
|
|
def _simulate_trailing_stop(prices, pos, start_idx, tf_minutes):
|
|
"""Simulate trailing stop from start_idx. Returns (exit_idx, exit_price, result)."""
|
|
best = pos["best_price"]
|
|
stop = pos["stop_price"]
|
|
stop_dist = pos["stop_dist"]
|
|
|
|
for j in range(1, SHIFT * (240 // tf_minutes) + 1): # SHIFT 4h-bars worth
|
|
idx = start_idx + j
|
|
if idx >= len(prices):
|
|
break
|
|
p = prices[idx]
|
|
if p > best:
|
|
best = p
|
|
stop = best - stop_dist
|
|
if p <= stop:
|
|
return idx, p, _close_position(pos, p, idx, tf_minutes)
|
|
|
|
# Time exit
|
|
end_idx = min(start_idx + SHIFT * (240 // tf_minutes), len(prices) - 1)
|
|
return end_idx, prices[end_idx], _close_position(pos, prices[end_idx], end_idx, tf_minutes)
|
|
|
|
|
|
def run_strategy(ticker, prices_4h, dates_4h, prices_30m, dates_30m,
|
|
mdl_4h, test_4h, mdl_30m, ws, K, mode, retrain_mode="off"):
|
|
"""Run one strategy variant."""
|
|
equity = TOTAL_CAPITAL
|
|
peak_equity = equity
|
|
max_dd = 0.0
|
|
trades = []
|
|
last_stop_idx_4h = -999
|
|
consecutive_losses = 0
|
|
in_position = False
|
|
|
|
tf_4h_minutes = 240
|
|
tf_30m_minutes = 30
|
|
bars_30m_per_4h = tf_4h_minutes // tf_30m_minutes # 8
|
|
|
|
total_commission = 0.0
|
|
total_interest = 0.0
|
|
skips = {"4h_shape": 0, "4h_conf": 0, "4h_short": 0, "4h_cool": 0,
|
|
"30m_none": 0, "margin": 0, "retrain": 0}
|
|
|
|
for d in test_4h:
|
|
idx_4h = d["price_idx"]
|
|
if idx_4h + SHIFT >= len(prices_4h) or idx_4h < ws + K:
|
|
continue
|
|
|
|
# Cooldown
|
|
if idx_4h - last_stop_idx_4h < SHIFT:
|
|
skips["4h_cool"] += 1
|
|
continue
|
|
|
|
if in_position:
|
|
continue
|
|
|
|
# Retrain check
|
|
if retrain_mode == "losses_only" and consecutive_losses >= 3:
|
|
data = signals.prepare_windows(prices_4h[:idx_4h + 1], ws, SHIFT)
|
|
if len(data) >= 20:
|
|
recent = data[-200:]
|
|
w = np.array([dd["norm_input"] for dd in recent])
|
|
t = np.array([dd["norm_target"] for dd in recent])
|
|
model_mod.train(mdl_4h, w, t, epochs=20, lr=0.003 * 0.3)
|
|
consecutive_losses = 0
|
|
skips["retrain"] += 1
|
|
|
|
# Try 4h signal
|
|
sig_4h = _check_signal(mdl_4h, prices_4h, idx_4h, ws, K)
|
|
|
|
if sig_4h is not None:
|
|
# Open on 4h
|
|
price = prices_4h[idx_4h]
|
|
pos = _open_position(equity, price, sig_4h["atr"], K, prices_4h, idx_4h)
|
|
if pos is None:
|
|
skips["margin"] += 1
|
|
continue
|
|
|
|
exit_idx, exit_price, result = _simulate_trailing_stop(
|
|
prices_4h, pos, idx_4h, tf_4h_minutes)
|
|
|
|
equity += result["pnl_net"]
|
|
total_commission += result["commission"]
|
|
total_interest += result["interest"]
|
|
trades.append({"source": "4h", **result})
|
|
|
|
if result["pnl_net"] > 0:
|
|
consecutive_losses = 0
|
|
else:
|
|
consecutive_losses += 1
|
|
last_stop_idx_4h = idx_4h
|
|
|
|
peak_equity = max(peak_equity, equity)
|
|
dd = (peak_equity - equity) / peak_equity if peak_equity > 0 else 0
|
|
max_dd = max(max_dd, dd)
|
|
continue
|
|
|
|
# 4h missed — try 30m fallback if enabled
|
|
if mode == "4h_only":
|
|
continue
|
|
|
|
# Find corresponding 30m bars
|
|
date_4h = str(dates_4h[idx_4h])
|
|
matching_30m = np.where(np.array([str(d) for d in dates_30m]) == date_4h)[0]
|
|
if len(matching_30m) == 0:
|
|
skips["30m_none"] += 1
|
|
continue
|
|
|
|
# Search within this 4h window in 30m data
|
|
start_30m = matching_30m[0]
|
|
found_30m = False
|
|
|
|
for offset in range(min(bars_30m_per_4h, len(matching_30m))):
|
|
bar_30m = start_30m + offset
|
|
if bar_30m < ws + K or bar_30m + SHIFT >= len(prices_30m):
|
|
continue
|
|
|
|
sig_30m = _check_signal(mdl_30m, prices_30m, bar_30m, ws, K)
|
|
if sig_30m is None:
|
|
continue
|
|
|
|
# Open on 30m
|
|
price = prices_30m[bar_30m]
|
|
pos = _open_position(equity, price, sig_30m["atr"], K, prices_30m, bar_30m)
|
|
if pos is None:
|
|
skips["margin"] += 1
|
|
break
|
|
|
|
exit_idx, exit_price, result = _simulate_trailing_stop(
|
|
prices_30m, pos, bar_30m, tf_30m_minutes)
|
|
|
|
equity += result["pnl_net"]
|
|
total_commission += result["commission"]
|
|
total_interest += result["interest"]
|
|
trades.append({"source": "30m", **result})
|
|
|
|
if result["pnl_net"] > 0:
|
|
consecutive_losses = 0
|
|
else:
|
|
consecutive_losses += 1
|
|
last_stop_idx_4h = idx_4h # cooldown in 4h terms
|
|
|
|
peak_equity = max(peak_equity, equity)
|
|
dd = (peak_equity - equity) / peak_equity if peak_equity > 0 else 0
|
|
max_dd = max(max_dd, dd)
|
|
found_30m = True
|
|
break
|
|
|
|
if not found_30m:
|
|
skips["30m_none"] += 1
|
|
|
|
# Results
|
|
n = len(trades)
|
|
wins = sum(1 for t in trades if t["pnl_net"] > 0)
|
|
n_4h = sum(1 for t in trades if t["source"] == "4h")
|
|
n_30m = sum(1 for t in trades if t["source"] == "30m")
|
|
|
|
total_pnl = equity - TOTAL_CAPITAL
|
|
|
|
# Sharpe
|
|
if n >= 2:
|
|
rets = np.array([t["pnl_net"] / TOTAL_CAPITAL for t in trades])
|
|
if np.std(rets) > 0:
|
|
sharpe = float(np.mean(rets) / np.std(rets) * np.sqrt(n / 1.9)) # ~1.9 years
|
|
else:
|
|
sharpe = 0
|
|
else:
|
|
sharpe = 0
|
|
|
|
return {
|
|
"total_pnl": round(total_pnl, 2),
|
|
"return_pct": round(total_pnl / TOTAL_CAPITAL * 100, 1),
|
|
"sharpe": round(sharpe, 2),
|
|
"max_dd": round(max_dd * 100, 1),
|
|
"trades": n,
|
|
"trades_4h": n_4h,
|
|
"trades_30m": n_30m,
|
|
"wins": wins,
|
|
"wr": round(wins / n * 100, 1) if n else 0,
|
|
"total_commission": round(total_commission, 2),
|
|
"total_interest": round(total_interest, 2),
|
|
"skips": skips,
|
|
}
|
|
|
|
|
|
def main():
|
|
results_dir = Path(__file__).parent / "results"
|
|
results_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
print("=" * 80)
|
|
print("EXP30c: REALISTIC CASCADE BACKTEST")
|
|
print("=" * 80)
|
|
print(f"Capital: ${TOTAL_CAPITAL} | Commission: 0.1% | Interest: 0.02%/day")
|
|
|
|
all_results = {}
|
|
|
|
for asset in ASSETS:
|
|
ticker = asset["ticker"]
|
|
symbol = asset["symbol"]
|
|
ws, K = asset["ws"], asset["K"]
|
|
|
|
print(f"\n{'═' * 60}")
|
|
print(f" {ticker} (ws={ws}, K={K})")
|
|
|
|
# Fetch data
|
|
print(" Fetching 4h...", end=" ", flush=True)
|
|
ohlcv_4h, dates_4h = fetch_ohlcv_ccxt(symbol, "4h", "max")
|
|
prices_4h = ohlcv_4h[:, 3]
|
|
print(f"{len(prices_4h)} bars")
|
|
|
|
print(" Fetching 30m...", end=" ", flush=True)
|
|
ohlcv_30m, dates_30m = fetch_ohlcv_ccxt(symbol, "30m", "max")
|
|
prices_30m = ohlcv_30m[:, 3]
|
|
print(f"{len(prices_30m)} bars")
|
|
|
|
# Train models
|
|
print(" Training 4h model...", end=" ", flush=True)
|
|
mdl_4h, train_4h, test_4h = _train_model(prices_4h, ws)
|
|
print("done")
|
|
|
|
print(" Training 30m model...", end=" ", flush=True)
|
|
mdl_30m, train_30m, test_30m = _train_model(prices_30m, ws)
|
|
print("done")
|
|
|
|
asset_results = {}
|
|
|
|
for mode in MODES:
|
|
retrain = "losses_only" if "+retrain" in mode else "off"
|
|
base_mode = mode.replace("+retrain", "")
|
|
|
|
# Re-train fresh model for each mode
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
mdl_4h_fresh = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
|
|
dx=1.0 / ws, use_sde=True)
|
|
data_4h = signals.prepare_windows(prices_4h, ws, SHIFT)
|
|
n_train = max(int(len(data_4h) * TRAIN_RATIO), 20)
|
|
w = np.array([d["norm_input"] for d in data_4h[:n_train]])
|
|
t = np.array([d["norm_target"] for d in data_4h[:n_train]])
|
|
model_mod.train(mdl_4h_fresh, w, t, 200, 0.003)
|
|
|
|
print(f"\n [{mode}]...", end=" ", flush=True)
|
|
r = run_strategy(ticker, prices_4h, dates_4h, prices_30m, dates_30m,
|
|
mdl_4h_fresh, data_4h[n_train:], mdl_30m, ws, K,
|
|
base_mode, retrain)
|
|
|
|
print(f"PnL=${r['total_pnl']:+.0f} ({r['return_pct']:+.1f}%) "
|
|
f"Sharpe={r['sharpe']:.2f} DD={r['max_dd']:.1f}% "
|
|
f"Trades={r['trades']} (4h:{r['trades_4h']} 30m:{r['trades_30m']}) "
|
|
f"WR={r['wr']:.1f}% Comm=${r['total_commission']:.0f}")
|
|
|
|
asset_results[mode] = r
|
|
|
|
all_results[ticker] = asset_results
|
|
|
|
# Summary
|
|
print(f"\n{'═' * 80}")
|
|
print("SUMMARY")
|
|
print(f"{'═' * 80}")
|
|
print(f" {'Ticker':<10s} {'Mode':<20s} {'PnL$':>6s} {'Ret%':>6s} {'Shrp':>5s} "
|
|
f"{'DD%':>5s} {'Trds':>5s} {'4h':>4s} {'30m':>4s} {'WR%':>5s} {'Comm$':>6s}")
|
|
print(f" {'-' * 80}")
|
|
for ticker, modes in all_results.items():
|
|
for mode, r in modes.items():
|
|
print(f" {ticker:<10s} {mode:<20s} ${r['total_pnl']:>+5.0f} "
|
|
f"{r['return_pct']:>+5.1f}% {r['sharpe']:>5.2f} "
|
|
f"{r['max_dd']:>4.1f}% {r['trades']:>5d} "
|
|
f"{r['trades_4h']:>4d} {r['trades_30m']:>4d} "
|
|
f"{r['wr']:>4.1f}% ${r['total_commission']:>5.0f}")
|
|
|
|
path = save_results(all_results, results_dir, "exp30c_realistic_cascade")
|
|
print(f"\nSaved: {path}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|