Files
anorandClaude Opus 4.6 f6e5d9c115 feat: exp31 — миграция 1h→4h, OHLCV bar-by-bar stops, 18-coin scan
- fix: optimize-windows использует OHLCV high/low для стопов (не close)
- fix: проверка стопа adverse price ПЕРЕД trailing update (conservative)
- feat: exp31_4h_migration — полный набор экспериментов:
  - 18 монет, walk-forward 30/70, delayed entry, leverage
  - Все 18 прибыльны на 4h shift=14 SM=4
  - Top-8: DOGE/APT/FIL/LINK/ETH/INJ/AVAX/WIF
  - Portfolio 1x: $23.5/mo, 75% profitable months
- add: backtest_futures.py, backtest_futures_80.py, backtest_frozen.py

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

153 lines
6.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Delayed entry: skip 1-4 bars after signal, vary hold duration. 4h shift=14."""
import sys, os, pickle
sys.path.insert(0, "/Volumes/Backup/Python_projects/remizov-trader/src")
import numpy as np, torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig, RiskConfig
WS = 64; K = 2; SHIFT = 14; EPOCHS = 300; LR = 0.005
COMM = 0.00055; CAP = 59.0
RCFG = RiskConfig(per_trade=0.05, max_position_pct=0.40, max_open_positions=3, leverage=1)
CACHE_DIR = "/tmp/ohlcv_cache"
def fetch_cached(sym, tf="4h"):
safe = sym.replace("/", "_").replace(":", "_")
path = f"{CACHE_DIR}/{safe}_{tf}.pkl"
if os.path.exists(path):
with open(path, "rb") as f:
return pickle.load(f)
return None, None
def run_bt(prices, highs, lows, mdl, sm, entry_delay, hold_bars, cap):
"""entry_delay: skip N bars after signal before entering.
hold_bars: exit after N bars (0 = use shift-K as before)."""
data = signals.prepare_windows(prices, WS, SHIFT)
n = len(data)
ts, te = int(n * 0.60), int(n * 0.70)
test_data = data[:ts] + data[te:]
if not test_data: return None
eq = cap; pos = None; cool = 0; pending = None
trades = 0; wins = 0; stops = 0; times = 0; pnl_list = []
actual_hold = hold_bars if hold_bars > 0 else (SHIFT - K)
for d in test_data:
pi = d["price_idx"]; cp = float(prices[pi])
# Check pending entry (delayed)
if pending and pi >= pending["enter_at"]:
ei = pending["enter_at"]
ep = float(prices[ei])
atr = risk.compute_atr(prices, ei)
sd = max(atr * sm, ep * 0.005)
sp = ep - pending["dir"] * sd
sz, val = risk.calculate_position(eq, ep, sd, RCFG)
pos = {"dir": pending["dir"], "entry": ep, "stop": sp, "sd": sd,
"best": ep, "sz": sz, "val": val, "bar": ei, "lc": ei}
pending = None
if pos:
sf = pos.get("lc", pos["bar"]) + 1
for bi in range(sf, pi + 1):
h, l = float(highs[bi]), float(lows[bi])
c = float(prices[bi])
adv = l if pos["dir"] == 1 else h
if risk.is_stopped(adv, pos["stop"], pos["dir"]):
pnl, _ = risk.calculate_pnl(pos["entry"], pos["stop"], pos["dir"],
pos["sz"], pos["val"], commission=COMM)
eq += pnl; pnl_list.append(pnl); trades += 1; stops += 1
if pnl > 0: wins += 1
pos = None; cool = bi + 3; break
fav = h if pos["dir"] == 1 else l
pos["best"], pos["stop"] = risk.update_trailing_stop(
fav, pos["best"], pos["stop"], pos["sd"], pos["dir"])
if bi - pos["bar"] >= actual_hold:
pnl, _ = risk.calculate_pnl(pos["entry"], c, pos["dir"],
pos["sz"], pos["val"], commission=COMM)
eq += pnl; pnl_list.append(pnl); trades += 1; times += 1
if pnl > 0: wins += 1
pos = None; break
if pos: pos["lc"] = pi
if pos is None and pending is None and pi >= WS + K and pi >= cool:
w = prices[pi-WS-K:pi-K].copy()
mu, std = w.mean(), w.std()
if std < 1e-10: continue
ni = (w - mu) / std
pred = model_mod.predict(mdl, ni)[-SHIFT:]
d2 = signals.get_direction(pred, K)
if d2:
if entry_delay == 0:
atr = risk.compute_atr(prices, pi)
sd = max(atr * sm, cp * 0.005)
sp = cp - d2 * sd
sz, val = risk.calculate_position(eq, cp, sd, RCFG)
pos = {"dir": d2, "entry": cp, "stop": sp, "sd": sd,
"best": cp, "sz": sz, "val": val, "bar": pi, "lc": pi}
else:
enter_at = min(pi + entry_delay, len(prices) - 1)
pending = {"dir": d2, "enter_at": enter_at}
if pos:
lp = float(prices[-1])
pnl, _ = risk.calculate_pnl(pos["entry"], lp, pos["dir"], pos["sz"], pos["val"], commission=COMM)
eq += pnl; pnl_list.append(pnl); trades += 1
if pnl > 0: wins += 1
total_pnl = eq - cap
wr = wins / trades * 100 if trades else 0
mx = cap; mdd = 0; run = cap
for p in pnl_list:
run += p
if run > mx: mx = run
dd = (mx - run) / mx if mx > 0 else 0
if dd > mdd: mdd = dd
return {"pnl": total_pnl, "trades": trades, "wr": wr, "stops": stops,
"times": times, "max_dd": mdd * 100}
# Top coins from phase 1
COINS = [
("WIF/USDT:USDT", "WIF"),
("APT/USDT:USDT", "APT"),
("UNI/USDT:USDT", "UNI"),
("FIL/USDT:USDT", "FIL"),
]
DELAYS = [0, 1, 2, 3, 4]
HOLDS = [0, 8, 10, 12, 16, 20] # 0 = shift-K=12
print("=" * 90)
print(" DELAYED ENTRY × HOLD DURATION — 4h shift=14 SM=4 trail=on")
print("=" * 90)
for sym, coin in COINS:
ohlcv, dates = fetch_cached(sym)
if ohlcv is None: print(f"{coin}: no cache"); continue
prices = ohlcv[:, 3]; highs = ohlcv[:, 1]; lows = ohlcv[:, 2]
data = signals.prepare_windows(prices, WS, SHIFT)
n = len(data)
ts, te = int(n * 0.60), int(n * 0.70)
train_data = data[ts:te]
mcfg = ModelConfig(window_size=WS, n_steps=20, total_time=0.5, shift=SHIFT,
epochs=EPOCHS, finetune_epochs=50, lr=LR)
torch.manual_seed(42); np.random.seed(42)
mdl = model_mod.create_model(mcfg)
W = np.array([d["norm_input"] for d in train_data])
T = np.array([d["norm_target"] for d in train_data])
model_mod.train(mdl, W, T, EPOCHS, LR)
print(f"\n--- {coin} ---")
print(f"{'delay':>5} {'hold':>5} {'PnL':>8} {'Tr':>5} {'WR':>6} {'Stop':>5} {'Time':>5} {'DD':>6}")
print("-" * 55)
for delay in DELAYS:
for hold in HOLDS:
r = run_bt(prices, highs, lows, mdl, 4.0, delay, hold, CAP)
if r is None: continue
hold_label = f"{hold}" if hold > 0 else "s-K"
mark = " ◄" if r["pnl"] > 0 else ""
print(f"{delay:>5} {hold_label:>5} ${r['pnl']:>+7.2f} {r['trades']:>5} "
f"{r['wr']:>5.1f}% {r['stops']:>5} {r['times']:>5} {r['max_dd']:>5.1f}%{mark}")