feat: exp30 — каскадный multi-TF (4h→30m/15m fallback)
Без комиссий: 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>
This commit is contained in:
@@ -0,0 +1,393 @@
|
||||
"""Exp30: Cascading multi-timeframe strategy.
|
||||
|
||||
Stage 1: Run formula on 4h, classify each signal window:
|
||||
- WIN: trailing stop profit > 0
|
||||
- LOSS: trailing stop loss
|
||||
- SKIP: no signal (low conf, no shape, short, cooldown)
|
||||
|
||||
Stage 2: For LOSS+SKIP periods, zoom into 2h and 1h:
|
||||
- Retrain model on smaller TF data up to that point
|
||||
- Check if formula catches the move at finer granularity
|
||||
|
||||
Hypothesis: when 4h misses, smaller TF may capture intra-bar moves.
|
||||
"""
|
||||
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 dataclasses import dataclass
|
||||
|
||||
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
|
||||
|
||||
SHIFT = 7
|
||||
MIN_CONFIDENCE = 1.5
|
||||
TRAIN_RATIO = 0.3
|
||||
|
||||
ASSETS = [
|
||||
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "ws": 64, "K": 3},
|
||||
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "ws": 48, "K": 2},
|
||||
]
|
||||
|
||||
FALLBACK_TFS = ["30m", "15m"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class SignalResult:
|
||||
idx: int
|
||||
date: str
|
||||
outcome: str # "win", "loss", "skip_shape", "skip_conf", "skip_short", "skip_cool"
|
||||
pnl_pct: float
|
||||
conf: float
|
||||
corr: float
|
||||
|
||||
|
||||
def _train_model(prices, ws):
|
||||
"""Train model on first TRAIN_RATIO of data."""
|
||||
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 _trailing_stop_pnl(prices, idx, K, entry_price=None):
|
||||
"""Compute trailing stop PnL for a long entry at idx."""
|
||||
entry = entry_price or prices[idx]
|
||||
atr = risk.compute_atr(prices, idx)
|
||||
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
|
||||
stop_dist = max(atr * stop_mult * 0.5, entry * 0.005)
|
||||
stop = entry - stop_dist
|
||||
best = entry
|
||||
|
||||
pnl_pct = 0.0
|
||||
for j in range(1, SHIFT + 1):
|
||||
if idx + j >= len(prices):
|
||||
break
|
||||
p = prices[idx + j]
|
||||
if p > best:
|
||||
best = p
|
||||
stop = best - stop_dist
|
||||
if p <= stop:
|
||||
pnl_pct = (p - entry) / entry * 100
|
||||
break
|
||||
else:
|
||||
end_idx = min(idx + SHIFT, len(prices) - 1)
|
||||
pnl_pct = (prices[end_idx] - entry) / entry * 100
|
||||
|
||||
return pnl_pct
|
||||
|
||||
|
||||
def stage1_classify(prices, dates, mdl, test_data, ws, K):
|
||||
"""Stage 1: classify each test signal on 4h."""
|
||||
results = []
|
||||
last_stop_idx = -999
|
||||
|
||||
for d in test_data:
|
||||
idx = d["price_idx"]
|
||||
if idx + SHIFT >= len(prices) or idx < ws + K:
|
||||
continue
|
||||
|
||||
date_str = str(dates[idx]) if idx < len(dates) else "?"
|
||||
|
||||
# Cooldown check
|
||||
if idx - last_stop_idx < SHIFT:
|
||||
results.append(SignalResult(idx, date_str, "skip_cool", 0, 0, 0))
|
||||
continue
|
||||
|
||||
pred = model_mod.predict(mdl, d["norm_input"])
|
||||
pred_new = pred[-SHIFT:]
|
||||
|
||||
# Shape confirmation
|
||||
confirm = prices[idx - K:idx]
|
||||
corr, confirmed = signals.check_shape_confirmation(
|
||||
pred_new, confirm, d["mu"], d["std"], K, 0.5)
|
||||
|
||||
if not confirmed:
|
||||
results.append(SignalResult(idx, date_str, "skip_shape", 0, 0, float(corr)))
|
||||
continue
|
||||
|
||||
# Confidence
|
||||
atr = risk.compute_atr(prices, idx)
|
||||
conf = 0.0
|
||||
if atr > 0:
|
||||
pred_denorm = pred_new * d["std"] + d["mu"]
|
||||
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
|
||||
conf = abs(corr) * (amp / atr)
|
||||
|
||||
if conf < MIN_CONFIDENCE:
|
||||
results.append(SignalResult(idx, date_str, "skip_conf", 0, conf, float(corr)))
|
||||
continue
|
||||
|
||||
# Direction
|
||||
direction = signals.get_direction(pred_new, K)
|
||||
if direction != 1:
|
||||
results.append(SignalResult(idx, date_str, "skip_short", 0, conf, float(corr)))
|
||||
continue
|
||||
|
||||
# Trade PnL
|
||||
pnl = _trailing_stop_pnl(prices, idx, K)
|
||||
|
||||
if pnl > 0:
|
||||
results.append(SignalResult(idx, date_str, "win", pnl, conf, float(corr)))
|
||||
else:
|
||||
results.append(SignalResult(idx, date_str, "loss", pnl, conf, float(corr)))
|
||||
last_stop_idx = idx
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def stage2_fallback(ticker, symbol, ws, K, miss_periods, dates_4h):
|
||||
"""Stage 2: for missed/loss periods, try smaller TFs."""
|
||||
fallback_results = {}
|
||||
|
||||
for tf in FALLBACK_TFS:
|
||||
print(f"\n Fallback TF={tf}...", end=" ", flush=True)
|
||||
|
||||
try:
|
||||
ohlcv, dates = fetch_ohlcv_ccxt(symbol, tf, "max")
|
||||
except Exception:
|
||||
print("fetch error")
|
||||
continue
|
||||
|
||||
if ohlcv is None or len(ohlcv) < 1000:
|
||||
print(f"only {len(ohlcv) if ohlcv is not None else 0} bars")
|
||||
continue
|
||||
|
||||
prices = ohlcv[:, 3]
|
||||
dates_str = np.array([str(d) for d in dates])
|
||||
|
||||
# Train model on this TF
|
||||
mdl, train, test = _train_model(prices, ws)
|
||||
|
||||
# For each miss period, find corresponding bars in smaller TF
|
||||
wins_in_miss = 0
|
||||
losses_in_miss = 0
|
||||
total_pnl = 0.0
|
||||
signals_found = 0
|
||||
total_miss_periods = 0
|
||||
|
||||
for miss in miss_periods:
|
||||
miss_date = miss.date
|
||||
miss_idx_4h = miss.idx
|
||||
|
||||
# Find the date range: miss_date to miss_date + SHIFT*4h
|
||||
# In smaller TF, this covers more bars
|
||||
if tf.endswith("h"):
|
||||
tf_minutes = int(tf.replace("h", "")) * 60
|
||||
elif tf.endswith("m"):
|
||||
tf_minutes = int(tf.replace("m", ""))
|
||||
else:
|
||||
tf_minutes = int(tf)
|
||||
bars_per_4h = 4 * 60 // tf_minutes
|
||||
|
||||
# Find matching index in smaller TF
|
||||
matching = np.where(dates_str == miss_date)[0]
|
||||
if len(matching) == 0:
|
||||
continue
|
||||
|
||||
total_miss_periods += 1
|
||||
start_bar = matching[0]
|
||||
end_bar = min(start_bar + SHIFT * bars_per_4h, len(prices) - SHIFT)
|
||||
|
||||
# Try each bar in the miss window as potential entry
|
||||
best_signal = None
|
||||
best_conf = 0
|
||||
|
||||
for bar in range(start_bar, end_bar):
|
||||
if bar < ws + K or bar + SHIFT >= len(prices):
|
||||
continue
|
||||
|
||||
# Prepare window
|
||||
w = prices[bar - ws - K:bar - K].copy()
|
||||
confirm = prices[bar - K:bar].copy()
|
||||
mu, std = w.mean(), w.std()
|
||||
if std < 1e-10:
|
||||
continue
|
||||
|
||||
pred = model_mod.predict(mdl, (w - mu) / std)
|
||||
pred_new = pred[-SHIFT:]
|
||||
|
||||
corr, confirmed = signals.check_shape_confirmation(
|
||||
pred_new, confirm, mu, std, K, 0.5)
|
||||
if not confirmed:
|
||||
continue
|
||||
|
||||
atr = risk.compute_atr(prices, bar)
|
||||
if atr <= 0:
|
||||
continue
|
||||
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:
|
||||
continue
|
||||
|
||||
direction = signals.get_direction(pred_new, K)
|
||||
if direction != 1:
|
||||
continue
|
||||
|
||||
if conf > best_conf:
|
||||
best_conf = conf
|
||||
best_signal = bar
|
||||
|
||||
if best_signal is not None:
|
||||
pnl = _trailing_stop_pnl(prices, best_signal, K)
|
||||
signals_found += 1
|
||||
total_pnl += pnl
|
||||
if pnl > 0:
|
||||
wins_in_miss += 1
|
||||
else:
|
||||
losses_in_miss += 1
|
||||
|
||||
n = wins_in_miss + losses_in_miss
|
||||
print(f"checked {total_miss_periods} periods, "
|
||||
f"found {signals_found} signals, "
|
||||
f"W/L={wins_in_miss}/{losses_in_miss}, "
|
||||
f"PnL={total_pnl/n:+.3f}%" if n > 0 else f"no trades")
|
||||
|
||||
fallback_results[tf] = {
|
||||
"miss_periods_checked": total_miss_periods,
|
||||
"signals_found": signals_found,
|
||||
"wins": wins_in_miss,
|
||||
"losses": losses_in_miss,
|
||||
"total_pnl_pct": round(total_pnl, 4),
|
||||
"mean_pnl_pct": round(total_pnl / n, 4) if n > 0 else 0,
|
||||
"wr": round(wins_in_miss / n * 100, 1) if n > 0 else 0,
|
||||
}
|
||||
|
||||
return fallback_results
|
||||
|
||||
|
||||
def main():
|
||||
results_dir = Path(__file__).parent / "results"
|
||||
results_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print("=" * 80)
|
||||
print("EXP30: CASCADING MULTI-TIMEFRAME STRATEGY")
|
||||
print("=" * 80)
|
||||
print("Stage 1: Classify 4h signals → win/loss/skip")
|
||||
print("Stage 2: For losses+skips → try 2h and 1h fallback")
|
||||
|
||||
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})")
|
||||
print(f"{'═' * 60}")
|
||||
|
||||
# Fetch 4h data
|
||||
ohlcv_4h, dates_4h = fetch_ohlcv_ccxt(symbol, "4h", "max")
|
||||
if ohlcv_4h is None:
|
||||
print(" Failed to fetch 4h data")
|
||||
continue
|
||||
|
||||
prices_4h = ohlcv_4h[:, 3]
|
||||
dates_4h_str = np.array([str(d) for d in dates_4h])
|
||||
print(f" 4h: {len(prices_4h)} bars")
|
||||
|
||||
# Stage 1: Train and classify
|
||||
print(f"\n STAGE 1: Classify 4h signals")
|
||||
mdl, train, test = _train_model(prices_4h, ws)
|
||||
s1_results = stage1_classify(prices_4h, dates_4h_str, mdl, test, ws, K)
|
||||
|
||||
wins = [r for r in s1_results if r.outcome == "win"]
|
||||
losses = [r for r in s1_results if r.outcome == "loss"]
|
||||
skips_shape = [r for r in s1_results if r.outcome == "skip_shape"]
|
||||
skips_conf = [r for r in s1_results if r.outcome == "skip_conf"]
|
||||
skips_short = [r for r in s1_results if r.outcome == "skip_short"]
|
||||
skips_cool = [r for r in s1_results if r.outcome == "skip_cool"]
|
||||
|
||||
print(f" Wins: {len(wins):>4d} avg PnL={np.mean([r.pnl_pct for r in wins]):+.3f}%" if wins else " Wins: 0")
|
||||
print(f" Losses: {len(losses):>4d} avg PnL={np.mean([r.pnl_pct for r in losses]):+.3f}%" if losses else " Losses: 0")
|
||||
print(f" Skip shape: {len(skips_shape):>4d}")
|
||||
print(f" Skip conf: {len(skips_conf):>4d}")
|
||||
print(f" Skip short: {len(skips_short):>4d}")
|
||||
print(f" Skip cool: {len(skips_cool):>4d}")
|
||||
|
||||
total_traded = len(wins) + len(losses)
|
||||
if total_traded > 0:
|
||||
total_pnl = sum(r.pnl_pct for r in wins) + sum(r.pnl_pct for r in losses)
|
||||
print(f" Total: {total_traded} trades, PnL={total_pnl/total_traded:+.3f}%/trade")
|
||||
|
||||
# Stage 2: Fallback for misses
|
||||
# "Misses" = losses + skips (excluding cooldown which is mechanical)
|
||||
misses = losses + skips_shape + skips_conf + skips_short
|
||||
print(f"\n STAGE 2: Fallback for {len(misses)} miss periods")
|
||||
|
||||
fallback = stage2_fallback(ticker, symbol, ws, K, misses, dates_4h_str)
|
||||
|
||||
# Combined analysis
|
||||
print(f"\n COMBINED ANALYSIS:")
|
||||
if total_traded > 0:
|
||||
base_pnl = sum(r.pnl_pct for r in wins) + sum(r.pnl_pct for r in losses)
|
||||
base_trades = total_traded
|
||||
print(f" 4h only: {base_trades} trades, total PnL={base_pnl:+.2f}%")
|
||||
|
||||
for tf, fb in fallback.items():
|
||||
if fb["signals_found"] > 0:
|
||||
combined_trades = base_trades + fb["signals_found"]
|
||||
combined_pnl = base_pnl + fb["total_pnl_pct"]
|
||||
print(f" 4h + {tf} fallback: {combined_trades} trades, "
|
||||
f"total PnL={combined_pnl:+.2f}% "
|
||||
f"(+{fb['signals_found']} trades from {tf}, "
|
||||
f"PnL={fb['total_pnl_pct']:+.2f}%)")
|
||||
|
||||
all_results[ticker] = {
|
||||
"stage1": {
|
||||
"wins": len(wins),
|
||||
"losses": len(losses),
|
||||
"skip_shape": len(skips_shape),
|
||||
"skip_conf": len(skips_conf),
|
||||
"skip_short": len(skips_short),
|
||||
"skip_cool": len(skips_cool),
|
||||
"win_avg_pnl": round(float(np.mean([r.pnl_pct for r in wins])), 4) if wins else 0,
|
||||
"loss_avg_pnl": round(float(np.mean([r.pnl_pct for r in losses])), 4) if losses else 0,
|
||||
"total_pnl": round(sum(r.pnl_pct for r in wins + losses), 4),
|
||||
},
|
||||
"stage2_fallback": fallback,
|
||||
}
|
||||
|
||||
# Summary
|
||||
print(f"\n{'═' * 80}")
|
||||
print("SUMMARY: DOES CASCADING HELP?")
|
||||
print(f"{'═' * 80}")
|
||||
for ticker, r in all_results.items():
|
||||
s1 = r["stage1"]
|
||||
base = s1["total_pnl"]
|
||||
base_n = s1["wins"] + s1["losses"]
|
||||
print(f"\n {ticker}:")
|
||||
print(f" 4h baseline: {base_n} trades, PnL={base:+.2f}%")
|
||||
for tf, fb in r["stage2_fallback"].items():
|
||||
if fb["signals_found"] > 0:
|
||||
delta = fb["total_pnl_pct"]
|
||||
extra_n = fb["signals_found"]
|
||||
verdict = "HELPS" if delta > 0 else "HURTS"
|
||||
print(f" +{tf} fallback: +{extra_n} trades, "
|
||||
f"Δ PnL={delta:+.2f}% → {verdict}")
|
||||
else:
|
||||
print(f" +{tf} fallback: no signals found")
|
||||
|
||||
path = save_results(all_results, results_dir, "exp30_cascade")
|
||||
print(f"\nSaved: {path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,422 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"ADA-USD": {
|
||||
"stage1": {
|
||||
"wins": 41,
|
||||
"losses": 51,
|
||||
"skip_shape": 348,
|
||||
"skip_conf": 99,
|
||||
"skip_short": 54,
|
||||
"skip_cool": 0,
|
||||
"win_avg_pnl": 3.1224,
|
||||
"loss_avg_pnl": -1.7502,
|
||||
"total_pnl": 38.757
|
||||
},
|
||||
"stage2_fallback": {
|
||||
"2h": {
|
||||
"miss_periods_checked": 552,
|
||||
"signals_found": 289,
|
||||
"wins": 75,
|
||||
"losses": 214,
|
||||
"total_pnl_pct": -152.5637,
|
||||
"mean_pnl_pct": -0.5279,
|
||||
"wr": 26.0
|
||||
},
|
||||
"1h": {
|
||||
"miss_periods_checked": 552,
|
||||
"signals_found": 369,
|
||||
"wins": 150,
|
||||
"losses": 219,
|
||||
"total_pnl_pct": 32.5737,
|
||||
"mean_pnl_pct": 0.0883,
|
||||
"wr": 40.7
|
||||
}
|
||||
}
|
||||
},
|
||||
"DOGE-USD": {
|
||||
"stage1": {
|
||||
"wins": 48,
|
||||
"losses": 79,
|
||||
"skip_shape": 294,
|
||||
"skip_conf": 87,
|
||||
"skip_short": 87,
|
||||
"skip_cool": 0,
|
||||
"win_avg_pnl": 3.6283,
|
||||
"loss_avg_pnl": -2.2131,
|
||||
"total_pnl": -0.6757
|
||||
},
|
||||
"stage2_fallback": {
|
||||
"2h": {
|
||||
"miss_periods_checked": 547,
|
||||
"signals_found": 312,
|
||||
"wins": 112,
|
||||
"losses": 200,
|
||||
"total_pnl_pct": -22.9433,
|
||||
"mean_pnl_pct": -0.0735,
|
||||
"wr": 35.9
|
||||
},
|
||||
"1h": {
|
||||
"miss_periods_checked": 547,
|
||||
"signals_found": 423,
|
||||
"wins": 181,
|
||||
"losses": 242,
|
||||
"total_pnl_pct": 38.6112,
|
||||
"mean_pnl_pct": 0.0913,
|
||||
"wr": 42.8
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"ADA-USD": {
|
||||
"stage1": {
|
||||
"wins": 41,
|
||||
"losses": 51,
|
||||
"skip_shape": 348,
|
||||
"skip_conf": 99,
|
||||
"skip_short": 54,
|
||||
"skip_cool": 0,
|
||||
"win_avg_pnl": 3.1224,
|
||||
"loss_avg_pnl": -1.7502,
|
||||
"total_pnl": 38.757
|
||||
},
|
||||
"stage2_fallback": {
|
||||
"30m": {
|
||||
"miss_periods_checked": 552,
|
||||
"signals_found": 486,
|
||||
"wins": 253,
|
||||
"losses": 233,
|
||||
"total_pnl_pct": 133.0561,
|
||||
"mean_pnl_pct": 0.2738,
|
||||
"wr": 52.1
|
||||
},
|
||||
"15m": {
|
||||
"miss_periods_checked": 552,
|
||||
"signals_found": 542,
|
||||
"wins": 284,
|
||||
"losses": 258,
|
||||
"total_pnl_pct": 132.4165,
|
||||
"mean_pnl_pct": 0.2443,
|
||||
"wr": 52.4
|
||||
}
|
||||
}
|
||||
},
|
||||
"DOGE-USD": {
|
||||
"stage1": {
|
||||
"wins": 48,
|
||||
"losses": 79,
|
||||
"skip_shape": 294,
|
||||
"skip_conf": 87,
|
||||
"skip_short": 87,
|
||||
"skip_cool": 0,
|
||||
"win_avg_pnl": 3.6283,
|
||||
"loss_avg_pnl": -2.2131,
|
||||
"total_pnl": -0.6757
|
||||
},
|
||||
"stage2_fallback": {
|
||||
"30m": {
|
||||
"miss_periods_checked": 547,
|
||||
"signals_found": 499,
|
||||
"wins": 262,
|
||||
"losses": 237,
|
||||
"total_pnl_pct": 144.713,
|
||||
"mean_pnl_pct": 0.29,
|
||||
"wr": 52.5
|
||||
},
|
||||
"15m": {
|
||||
"miss_periods_checked": 547,
|
||||
"signals_found": 540,
|
||||
"wins": 273,
|
||||
"losses": 267,
|
||||
"total_pnl_pct": 96.1916,
|
||||
"mean_pnl_pct": 0.1781,
|
||||
"wr": 50.6
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"ADA-USD": {
|
||||
"4h_only": {
|
||||
"total_pnl": 11.19,
|
||||
"return_pct": 4.4,
|
||||
"sharpe": 0.08,
|
||||
"max_dd": 33.1,
|
||||
"trades": 90,
|
||||
"trades_4h": 90,
|
||||
"trades_30m": 0,
|
||||
"wins": 34,
|
||||
"wr": 37.8,
|
||||
"total_commission": 59.83,
|
||||
"total_interest": 1.81,
|
||||
"skips": {
|
||||
"4h_shape": 0,
|
||||
"4h_conf": 0,
|
||||
"4h_short": 0,
|
||||
"4h_cool": 0,
|
||||
"30m_none": 0,
|
||||
"margin": 0,
|
||||
"retrain": 0
|
||||
}
|
||||
},
|
||||
"4h+30m": {
|
||||
"total_pnl": -183.3,
|
||||
"return_pct": -72.2,
|
||||
"sharpe": -1.93,
|
||||
"max_dd": 72.2,
|
||||
"trades": 344,
|
||||
"trades_4h": 90,
|
||||
"trades_30m": 254,
|
||||
"wins": 112,
|
||||
"wr": 32.6,
|
||||
"total_commission": 116.65,
|
||||
"total_interest": 1.48,
|
||||
"skips": {
|
||||
"4h_shape": 0,
|
||||
"4h_conf": 0,
|
||||
"4h_short": 0,
|
||||
"4h_cool": 0,
|
||||
"30m_none": 249,
|
||||
"margin": 0,
|
||||
"retrain": 0
|
||||
}
|
||||
},
|
||||
"4h+30m+retrain": {
|
||||
"total_pnl": -185.05,
|
||||
"return_pct": -72.9,
|
||||
"sharpe": -1.76,
|
||||
"max_dd": 72.9,
|
||||
"trades": 357,
|
||||
"trades_4h": 114,
|
||||
"trades_30m": 243,
|
||||
"wins": 117,
|
||||
"wr": 32.8,
|
||||
"total_commission": 135.46,
|
||||
"total_interest": 1.86,
|
||||
"skips": {
|
||||
"4h_shape": 0,
|
||||
"4h_conf": 0,
|
||||
"4h_short": 0,
|
||||
"4h_cool": 0,
|
||||
"30m_none": 236,
|
||||
"margin": 0,
|
||||
"retrain": 50
|
||||
}
|
||||
}
|
||||
},
|
||||
"DOGE-USD": {
|
||||
"4h_only": {
|
||||
"total_pnl": -151.13,
|
||||
"return_pct": -59.5,
|
||||
"sharpe": -0.78,
|
||||
"max_dd": 77.4,
|
||||
"trades": 132,
|
||||
"trades_4h": 132,
|
||||
"trades_30m": 0,
|
||||
"wins": 42,
|
||||
"wr": 31.8,
|
||||
"total_commission": 67.49,
|
||||
"total_interest": 2.01,
|
||||
"skips": {
|
||||
"4h_shape": 0,
|
||||
"4h_conf": 0,
|
||||
"4h_short": 0,
|
||||
"4h_cool": 0,
|
||||
"30m_none": 0,
|
||||
"margin": 0,
|
||||
"retrain": 0
|
||||
}
|
||||
},
|
||||
"4h+30m": {
|
||||
"total_pnl": -223.38,
|
||||
"return_pct": -87.9,
|
||||
"sharpe": -1.45,
|
||||
"max_dd": 91.9,
|
||||
"trades": 382,
|
||||
"trades_4h": 132,
|
||||
"trades_30m": 250,
|
||||
"wins": 117,
|
||||
"wr": 30.6,
|
||||
"total_commission": 131.73,
|
||||
"total_interest": 1.82,
|
||||
"skips": {
|
||||
"4h_shape": 0,
|
||||
"4h_conf": 0,
|
||||
"4h_short": 0,
|
||||
"4h_cool": 0,
|
||||
"30m_none": 213,
|
||||
"margin": 0,
|
||||
"retrain": 0
|
||||
}
|
||||
},
|
||||
"4h+30m+retrain": {
|
||||
"total_pnl": -212.54,
|
||||
"return_pct": -83.7,
|
||||
"sharpe": -1.46,
|
||||
"max_dd": 87.2,
|
||||
"trades": 387,
|
||||
"trades_4h": 143,
|
||||
"trades_30m": 244,
|
||||
"wins": 121,
|
||||
"wr": 31.3,
|
||||
"total_commission": 130.85,
|
||||
"total_interest": 1.88,
|
||||
"skips": {
|
||||
"4h_shape": 0,
|
||||
"4h_conf": 0,
|
||||
"4h_short": 0,
|
||||
"4h_cool": 0,
|
||||
"30m_none": 208,
|
||||
"margin": 0,
|
||||
"retrain": 60
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user