exp27: 25 пар из топ-50 → NEAR/TIA/PEPE с edge, но реалистичный бэктест показал слабее ADA+DOGE (+$122 vs +$289) exp28: volume/range анализ → нулевой эффект для ADA/DOGE exp29: 20 пар × 6 TF → 4h единственный рабочий таймфрейм Вывод: текущий прод (ADA+DOGE, 4h) остаётся оптимальным Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
256 lines
8.1 KiB
Python
256 lines
8.1 KiB
Python
"""Exp29: Timeframe scan for Remizov formula.
|
|
|
|
Tests top crypto pairs across multiple timeframes.
|
|
Pipeline per (asset, tf): fetch → train → amplitude corr → conf PnL → bootstrap.
|
|
"""
|
|
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 scipy import stats
|
|
|
|
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
|
|
MIN_BARS = 1500
|
|
|
|
TIMEFRAMES = ["1h", "2h", "4h", "6h", "12h", "1d"]
|
|
|
|
# Include our current pairs + top candidates from exp27
|
|
PAIRS = [
|
|
"ADA/USDC", "DOGE/USDC", # current prod
|
|
"BTC/USDC", "ETH/USDC", "SOL/USDC", # previously tested (for comparison)
|
|
"NEAR/USDC", "TIA/USDC", "PEPE/USDC", # exp27 winners
|
|
"AVAX/USDC", "LINK/USDC", "LTC/USDC", # large caps
|
|
"UNI/USDC", "ATOM/USDC", "OP/USDC",
|
|
"ARB/USDC", "SUI/USDC", "APT/USDC",
|
|
"FIL/USDC", "SHIB/USDC", "SEI/USDC",
|
|
]
|
|
|
|
# ws=64, K=2 as default (good balance from exp26e/27)
|
|
WS = 64
|
|
K = 2
|
|
|
|
|
|
def _ticker(symbol):
|
|
return symbol.replace("/", "-").replace("USDC", "USD")
|
|
|
|
|
|
def _run_tests(prices, ws, K):
|
|
"""Train model and run amplitude + PnL + bootstrap tests."""
|
|
data = signals.prepare_windows(prices, ws, SHIFT)
|
|
n_train = max(int(len(data) * TRAIN_RATIO), 20)
|
|
train, test = data[:n_train], data[n_train:]
|
|
|
|
if len(test) < 30:
|
|
return None
|
|
|
|
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)
|
|
|
|
# Amplitude correlation
|
|
pred_amps, actual_amps = [], []
|
|
for d in test:
|
|
idx = d["price_idx"]
|
|
if idx + SHIFT >= len(prices):
|
|
continue
|
|
pred = model_mod.predict(mdl, d["norm_input"])
|
|
pred_new = pred[-SHIFT:]
|
|
pred_denorm = pred_new * d["std"] + d["mu"]
|
|
pred_amps.append(float(np.max(pred_denorm) - np.min(pred_denorm)))
|
|
future = prices[idx:idx + SHIFT]
|
|
actual_amps.append(float(np.max(future) - np.min(future)))
|
|
|
|
if len(pred_amps) < 30:
|
|
return None
|
|
|
|
r_amp, _ = stats.pearsonr(pred_amps, actual_amps)
|
|
|
|
# Conf-filtered PnL with trailing stop
|
|
trade_pnls = []
|
|
for d in test:
|
|
idx = d["price_idx"]
|
|
if idx + SHIFT >= len(prices) or idx < ws + K:
|
|
continue
|
|
|
|
pred = model_mod.predict(mdl, d["norm_input"])
|
|
pred_new = pred[-SHIFT:]
|
|
|
|
confirm = prices[idx - K:idx]
|
|
corr, confirmed = signals.check_shape_confirmation(
|
|
pred_new, confirm, d["mu"], d["std"], K, 0.5)
|
|
if not confirmed:
|
|
continue
|
|
|
|
atr = risk.compute_atr(prices, idx)
|
|
if atr <= 0:
|
|
continue
|
|
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:
|
|
continue
|
|
|
|
direction = signals.get_direction(pred_new, K)
|
|
if direction != 1:
|
|
continue
|
|
|
|
entry = 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:
|
|
pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100
|
|
trade_pnls.append(pnl_pct)
|
|
|
|
n_trades = len(trade_pnls)
|
|
if n_trades < 5:
|
|
return {
|
|
"r_amp": round(float(r_amp), 4),
|
|
"mean_pnl": 0, "n_trades": n_trades,
|
|
"p_positive": 0, "ci_lo": 0, "ci_hi": 0,
|
|
}
|
|
|
|
mean_pnl = float(np.mean(trade_pnls))
|
|
wr = sum(1 for t in trade_pnls if t > 0) / n_trades * 100
|
|
|
|
# Bootstrap
|
|
arr = np.array(trade_pnls)
|
|
means = np.array([float(np.mean(np.random.choice(arr, len(arr), replace=True)))
|
|
for _ in range(1000)])
|
|
p_pos = float(np.mean(means > 0)) * 100
|
|
ci = np.percentile(means, [2.5, 97.5])
|
|
|
|
return {
|
|
"r_amp": round(float(r_amp), 4),
|
|
"mean_pnl": round(mean_pnl, 4),
|
|
"n_trades": n_trades,
|
|
"wr": round(wr, 1),
|
|
"p_positive": round(p_pos, 1),
|
|
"ci_lo": round(float(ci[0]), 4),
|
|
"ci_hi": round(float(ci[1]), 4),
|
|
}
|
|
|
|
|
|
def main():
|
|
results_dir = Path(__file__).parent / "results"
|
|
results_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
print("=" * 80)
|
|
print("EXP29: TIMEFRAME SCAN")
|
|
print("=" * 80)
|
|
print(f"Pairs: {len(PAIRS)} | Timeframes: {TIMEFRAMES}")
|
|
print(f"ws={WS}, K={K}, conf>={MIN_CONFIDENCE}")
|
|
|
|
all_results = []
|
|
winners = []
|
|
|
|
for symbol in PAIRS:
|
|
ticker = _ticker(symbol)
|
|
print(f"\n{'─' * 50}")
|
|
print(f" {ticker}")
|
|
|
|
for tf in TIMEFRAMES:
|
|
print(f" {tf:>3s}: ", end="", flush=True)
|
|
|
|
try:
|
|
ohlcv, dates = fetch_ohlcv_ccxt(symbol, tf, "max")
|
|
except Exception as e:
|
|
print(f"fetch error")
|
|
continue
|
|
|
|
if ohlcv is None or len(ohlcv) < MIN_BARS:
|
|
bars = len(ohlcv) if ohlcv is not None else 0
|
|
print(f"{bars} bars (need {MIN_BARS})")
|
|
continue
|
|
|
|
prices = ohlcv[:, 3]
|
|
result = _run_tests(prices, WS, K)
|
|
|
|
if result is None:
|
|
print(f"{len(prices)} bars, insufficient test data")
|
|
continue
|
|
|
|
r = result
|
|
entry = {
|
|
"ticker": ticker, "tf": tf, "bars": len(prices),
|
|
**r,
|
|
}
|
|
all_results.append(entry)
|
|
|
|
flag = ""
|
|
if r["mean_pnl"] > 0 and r["p_positive"] >= 90 and r["n_trades"] >= 10:
|
|
flag = " ★"
|
|
winners.append(entry)
|
|
|
|
print(f"{len(prices):>5d} bars r={r['r_amp']:+.3f} "
|
|
f"PnL={r['mean_pnl']:+.3f}% N={r['n_trades']:>3d} "
|
|
f"P={r['p_positive']:>4.0f}%{flag}")
|
|
|
|
# Summary
|
|
print(f"\n{'═' * 80}")
|
|
print(f"WINNERS (PnL>0, P>=90%, N>=10)")
|
|
print(f"{'═' * 80}")
|
|
|
|
if winners:
|
|
winners.sort(key=lambda x: x["mean_pnl"] * x["p_positive"] / 100, reverse=True)
|
|
print(f" {'Ticker':<12s} {'TF':>3s} {'Bars':>5s} {'r_amp':>6s} "
|
|
f"{'PnL%':>7s} {'N':>4s} {'WR%':>5s} {'P%':>5s} {'CI':>15s}")
|
|
print(f" {'-' * 65}")
|
|
for w in winners:
|
|
print(f" {w['ticker']:<12s} {w['tf']:>3s} {w['bars']:>5d} "
|
|
f"{w['r_amp']:>+5.3f} {w['mean_pnl']:>+6.3f}% "
|
|
f"{w['n_trades']:>4d} {w.get('wr', 0):>4.1f}% "
|
|
f"{w['p_positive']:>4.0f}% "
|
|
f"[{w['ci_lo']:+.3f}, {w['ci_hi']:+.3f}]")
|
|
else:
|
|
print(" None found.")
|
|
|
|
# Compare 4h vs other TFs for our current pairs
|
|
print(f"\n{'═' * 80}")
|
|
print(f"ADA + DOGE: ALL TIMEFRAMES")
|
|
print(f"{'═' * 80}")
|
|
for t in ["ADA-USD", "DOGE-USD"]:
|
|
entries = [r for r in all_results if r["ticker"] == t]
|
|
if entries:
|
|
print(f"\n {t}:")
|
|
for e in sorted(entries, key=lambda x: TIMEFRAMES.index(x["tf"])):
|
|
flag = " ★" if e["mean_pnl"] > 0 and e["p_positive"] >= 90 else ""
|
|
print(f" {e['tf']:>3s}: r={e['r_amp']:+.3f} "
|
|
f"PnL={e['mean_pnl']:+.3f}% N={e['n_trades']:>3d} "
|
|
f"P={e['p_positive']:>4.0f}%{flag}")
|
|
|
|
path = save_results({"results": all_results, "winners": winners},
|
|
results_dir, "exp29_tf_scan")
|
|
print(f"\nSaved: {path}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|