exp23: weight optimization (EQUAL лучше всех) exp24: realistic backtest с retrain (retrain вреден) exp25: порт на backtrader, retrain modes comparison exp26: ablation study ADA — shape_confirm #1 фактор exp26b: direction accuracy = 51% (random) exp26c: trailing stop WR edge vs random = 0pp exp26d: amplitude prediction — r=0.164 для ADA (Q4/Q1=1.5x) Главный вывод: формула Ремизова = детектор волатильности, не predictor направления. Прибыльность = trailing stop asymmetry + amplitude filter. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
375 lines
15 KiB
Python
375 lines
15 KiB
Python
"""Exp26c: Trend prediction quality of Remizov formula.
|
||
|
||
Correct metrics for trailing-stop strategy:
|
||
1. Initial trend match: does price move in predicted direction in first 1-3 bars?
|
||
2. Max Favorable Excursion (MFE): how far does price go in pred direction?
|
||
3. Trailing-stop simulation: would this signal be profitable with ATR trailing stop?
|
||
4. Shape path correlation: does the SHAPE of the move match prediction?
|
||
|
||
All metrics computed on trading-aligned windows (K-offset, as in prod).
|
||
"""
|
||
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 common.dataset import load_or_fetch
|
||
from common.metrics import save_results
|
||
|
||
TRAIN_RATIO = 0.3
|
||
STOP_SCALE = 0.5 # prod stop_scale
|
||
STOP_MULT = 2.0 # base stop multiplier
|
||
LOOKAHEAD = 30 # bars to simulate after entry (enough for trailing stop)
|
||
|
||
ASSETS = [
|
||
{"ticker": "BTC-USD", "ws": 32, "K": 3, "shift": 7, "tf_h": 4},
|
||
{"ticker": "ETH-USD", "ws": 64, "K": 2, "shift": 7, "tf_h": 2},
|
||
{"ticker": "ADA-USD", "ws": 64, "K": 3, "shift": 7, "tf_h": 4},
|
||
{"ticker": "DOGE-USD", "ws": 48, "K": 2, "shift": 7, "tf_h": 4},
|
||
{"ticker": "SOL-USD", "ws": 128, "K": 2, "shift": 7, "tf_h": 2},
|
||
]
|
||
|
||
|
||
def _train_model(prices, ws, shift):
|
||
data = signals.prepare_windows(prices, ws, shift)
|
||
n_train = max(int(len(data) * TRAIN_RATIO), 20)
|
||
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)
|
||
model_mod.train(mdl,
|
||
np.array([d["norm_input"] for d in data[:n_train]]),
|
||
np.array([d["norm_target"] for d in data[:n_train]]),
|
||
200, 0.003)
|
||
return mdl, data, n_train
|
||
|
||
|
||
def _simulate_trailing_stop(prices, entry_idx, direction, stop_dist, max_bars):
|
||
"""Simulate trailing stop from entry. Returns (pnl_pct, bars_held, mfe_pct, mae_pct)."""
|
||
entry_price = prices[entry_idx]
|
||
best_price = entry_price
|
||
stop_price = entry_price - direction * stop_dist
|
||
|
||
mfe = 0.0 # max favorable excursion
|
||
mae = 0.0 # max adverse excursion
|
||
|
||
for i in range(1, max_bars + 1):
|
||
bar_idx = entry_idx + i
|
||
if bar_idx >= len(prices):
|
||
break
|
||
price = prices[bar_idx]
|
||
|
||
# Track excursions
|
||
move = (price - entry_price) / entry_price * direction
|
||
mfe = max(mfe, move)
|
||
mae = min(mae, move)
|
||
|
||
# Trailing stop update
|
||
best_price, stop_price = risk.update_trailing_stop(
|
||
price, best_price, stop_price, stop_dist, direction)
|
||
|
||
# Stop hit?
|
||
if risk.is_stopped(price, stop_price, direction):
|
||
pnl_pct = (price - entry_price) / entry_price * direction * 100
|
||
return pnl_pct, i, mfe * 100, mae * 100
|
||
|
||
# Not stopped within max_bars — close at last bar
|
||
last = prices[min(entry_idx + max_bars, len(prices) - 1)]
|
||
pnl_pct = (last - entry_price) / entry_price * direction * 100
|
||
return pnl_pct, max_bars, mfe * 100, mae * 100
|
||
|
||
|
||
def _analyze_asset(ticker, prices, ws, K, shift):
|
||
"""Analyze trend prediction quality for one asset."""
|
||
mdl, data, n_train = _train_model(prices, ws, shift)
|
||
test_data = data[n_train:]
|
||
if len(test_data) < 10:
|
||
return None
|
||
|
||
results = []
|
||
for d in test_data:
|
||
idx = d["price_idx"]
|
||
if idx + LOOKAHEAD >= len(prices):
|
||
continue
|
||
if idx < ws + K + 1:
|
||
continue
|
||
|
||
# Trading-aligned window (K-offset, as in prod)
|
||
w = prices[idx - ws - K: idx - K].copy()
|
||
mu, std = w.mean(), w.std()
|
||
if std < 1e-10:
|
||
continue
|
||
|
||
pred = model_mod.predict(mdl, (w - mu) / std)
|
||
pred_new = pred[-shift:]
|
||
|
||
# Direction
|
||
pred_dir = signals.get_direction(pred_new, K)
|
||
if pred_dir is None:
|
||
continue
|
||
|
||
# Shape confirmation + confidence (as in prod)
|
||
confirm = prices[idx - K:idx].copy()
|
||
corr, confirmed = signals.check_shape_confirmation(
|
||
pred_new, confirm, mu, std, K, 0.5)
|
||
atr = risk.compute_atr(prices, idx)
|
||
pred_denorm = pred_new * std + mu
|
||
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
|
||
confidence = abs(corr) * (amp / atr) if atr > 0 else 0
|
||
|
||
# --- Metric 1: Initial trend match (first N bars after entry) ---
|
||
entry_price = prices[idx]
|
||
initial_match = {}
|
||
for n_bars in [1, 2, 3, 5]:
|
||
if idx + n_bars < len(prices):
|
||
actual_move = prices[idx + n_bars] - entry_price
|
||
initial_match[n_bars] = 1 if (actual_move * pred_dir > 0) else 0
|
||
|
||
# --- Metric 2: Predicted shape vs actual path ---
|
||
# The prediction covers from idx-K to idx+shift-K-1
|
||
# Actual future from entry (idx): prices[idx:idx+shift-K]
|
||
future_len = shift - K
|
||
if future_len > 0 and idx + future_len <= len(prices):
|
||
actual_path = prices[idx:idx + future_len]
|
||
# Predicted path: pred_new[K:] denormalized (the actual future part)
|
||
pred_path = pred_new[K:] * std + mu
|
||
if len(actual_path) == len(pred_path) and len(pred_path) >= 2:
|
||
# Path changes (returns), not levels
|
||
actual_changes = np.diff(actual_path)
|
||
pred_changes = np.diff(pred_path)
|
||
# Direction match per bar
|
||
bar_matches = sum(1 for a, p in zip(actual_changes, pred_changes)
|
||
if a * p > 0)
|
||
bar_match_pct = bar_matches / len(actual_changes) * 100
|
||
with np.errstate(invalid="ignore"):
|
||
path_corr = np.corrcoef(pred_changes, actual_changes)[0, 1]
|
||
if np.isnan(path_corr):
|
||
path_corr = 0.0
|
||
else:
|
||
bar_match_pct = 0
|
||
path_corr = 0.0
|
||
else:
|
||
bar_match_pct = 0
|
||
path_corr = 0.0
|
||
|
||
# --- Metric 3: Trailing stop simulation ---
|
||
stop_dist = max(atr * STOP_MULT * STOP_SCALE, entry_price * 0.005)
|
||
pnl_pct, bars_held, mfe_pct, mae_pct = _simulate_trailing_stop(
|
||
prices, idx, pred_dir, stop_dist, LOOKAHEAD)
|
||
is_win = pnl_pct > 0
|
||
|
||
results.append({
|
||
"idx": idx, "pred_dir": pred_dir, "entry_price": entry_price,
|
||
"confirmed": confirmed, "confidence": confidence, "corr": corr,
|
||
# Metrics
|
||
"initial_match": initial_match,
|
||
"bar_match_pct": bar_match_pct, "path_corr": path_corr,
|
||
"pnl_pct": pnl_pct, "bars_held": bars_held,
|
||
"mfe_pct": mfe_pct, "mae_pct": mae_pct, "is_win": is_win,
|
||
"is_long": pred_dir == 1,
|
||
})
|
||
|
||
return results
|
||
|
||
|
||
def _print_report(ticker, results, K, shift):
|
||
n = len(results)
|
||
longs = [r for r in results if r["is_long"]]
|
||
shorts = [r for r in results if not r["is_long"]]
|
||
|
||
print(f"\n{'═' * 70}")
|
||
print(f" {ticker} — {n} signals ({len(longs)} LONG, {len(shorts)} SHORT)")
|
||
print(f"{'═' * 70}")
|
||
|
||
if not results:
|
||
return {}
|
||
|
||
# ── 1. Initial trend match ──
|
||
print(f"\n 1. INITIAL TREND MATCH (does price move in predicted direction?)")
|
||
for n_bars in [1, 2, 3, 5]:
|
||
vals = [r["initial_match"].get(n_bars, 0) for r in results
|
||
if n_bars in r["initial_match"]]
|
||
if vals:
|
||
acc = sum(vals) / len(vals) * 100
|
||
marker = " ✓" if acc > 55 else (" ✗" if acc < 45 else "")
|
||
print(f" After {n_bars} bar(s): {sum(vals)}/{len(vals)} = {acc:.1f}%{marker}")
|
||
|
||
# Long only
|
||
print(f" --- LONG only ---")
|
||
for n_bars in [1, 2, 3, 5]:
|
||
vals = [r["initial_match"].get(n_bars, 0) for r in longs
|
||
if n_bars in r["initial_match"]]
|
||
if vals:
|
||
acc = sum(vals) / len(vals) * 100
|
||
marker = " ✓" if acc > 55 else (" ✗" if acc < 45 else "")
|
||
print(f" After {n_bars} bar(s): {sum(vals)}/{len(vals)} = {acc:.1f}%{marker}")
|
||
|
||
# ── 2. Path correlation ──
|
||
print(f"\n 2. PREDICTED PATH vs ACTUAL PATH")
|
||
corrs = [r["path_corr"] for r in results]
|
||
bmatch = [r["bar_match_pct"] for r in results]
|
||
print(f" Path correlation: mean={np.mean(corrs):.3f} median={np.median(corrs):.3f}")
|
||
print(f" Bar-by-bar direction match: mean={np.mean(bmatch):.1f}%")
|
||
|
||
# ── 3. Trailing stop simulation ──
|
||
print(f"\n 3. TRAILING STOP SIMULATION (ATR×{STOP_MULT}×{STOP_SCALE})")
|
||
wins = [r for r in results if r["is_win"]]
|
||
wr = len(wins) / n * 100
|
||
avg_pnl = np.mean([r["pnl_pct"] for r in results])
|
||
avg_win = np.mean([r["pnl_pct"] for r in wins]) if wins else 0
|
||
avg_loss = np.mean([r["pnl_pct"] for r in results if not r["is_win"]])
|
||
avg_mfe = np.mean([r["mfe_pct"] for r in results])
|
||
avg_mae = np.mean([r["mae_pct"] for r in results])
|
||
print(f" Win rate: {len(wins)}/{n} = {wr:.1f}%")
|
||
print(f" Avg PnL: {avg_pnl:+.2f}% | Avg win: {avg_win:+.2f}% | Avg loss: {avg_loss:+.2f}%")
|
||
print(f" Avg MFE: {avg_mfe:+.2f}% | Avg MAE: {avg_mae:+.2f}%")
|
||
if avg_loss < 0:
|
||
profit_factor = abs(sum(r["pnl_pct"] for r in wins)) / abs(sum(r["pnl_pct"] for r in results if not r["is_win"]))
|
||
print(f" Profit factor: {profit_factor:.2f}")
|
||
|
||
# Long only
|
||
if longs:
|
||
l_wins = [r for r in longs if r["is_win"]]
|
||
l_wr = len(l_wins) / len(longs) * 100
|
||
l_avg = np.mean([r["pnl_pct"] for r in longs])
|
||
l_mfe = np.mean([r["mfe_pct"] for r in longs])
|
||
print(f" --- LONG only: WR={l_wr:.1f}% avg={l_avg:+.2f}% MFE={l_mfe:+.2f}%")
|
||
|
||
# ── 4. By filter stages ──
|
||
print(f"\n 4. TRAILING STOP WR BY FILTER")
|
||
for label, subset in [
|
||
("All signals", results),
|
||
("LONG only", longs),
|
||
("Shape confirmed", [r for r in results if r["confirmed"]]),
|
||
("Conf>=1.5", [r for r in results if r["confidence"] >= 1.5]),
|
||
("PROD (shape+conf+long)", [r for r in longs if r["confirmed"]
|
||
and r["confidence"] >= 1.5]),
|
||
]:
|
||
if subset:
|
||
w = sum(1 for r in subset if r["is_win"])
|
||
wr_s = w / len(subset) * 100
|
||
avg_s = np.mean([r["pnl_pct"] for r in subset])
|
||
mfe_s = np.mean([r["mfe_pct"] for r in subset])
|
||
marker = " ✓" if wr_s > 40 else ""
|
||
print(f" {label:<25s} WR={wr_s:5.1f}% avg={avg_s:+5.2f}% "
|
||
f"MFE={mfe_s:+5.2f}% N={len(subset)}{marker}")
|
||
|
||
# ── 5. Random baseline comparison ──
|
||
print(f"\n 5. RANDOM BASELINE (coin flip direction, same stops)")
|
||
# Just flip all directions and re-check
|
||
random_wins = 0
|
||
random_pnls = []
|
||
for r in results:
|
||
rev_dir = -r["pred_dir"]
|
||
pnl, _, _, _ = _simulate_trailing_stop(
|
||
prices_cache[ticker], r["idx"], rev_dir,
|
||
max(risk.compute_atr(prices_cache[ticker], r["idx"]) * STOP_MULT * STOP_SCALE,
|
||
r["entry_price"] * 0.005),
|
||
LOOKAHEAD)
|
||
random_pnls.append(pnl)
|
||
if pnl > 0:
|
||
random_wins += 1
|
||
rand_wr = random_wins / n * 100
|
||
rand_avg = np.mean(random_pnls)
|
||
edge_wr = wr - rand_wr
|
||
edge_pnl = avg_pnl - rand_avg
|
||
print(f" Reverse direction: WR={rand_wr:.1f}% avg={rand_avg:+.2f}%")
|
||
print(f" MODEL EDGE: WR Δ={edge_wr:+.1f}pp PnL Δ={edge_pnl:+.2f}%")
|
||
|
||
return {
|
||
"ticker": ticker, "n_signals": n,
|
||
"initial_1bar": round(sum(r["initial_match"].get(1, 0) for r in results
|
||
if 1 in r["initial_match"]) /
|
||
max(1, sum(1 for r in results if 1 in r["initial_match"])) * 100, 1),
|
||
"initial_3bar": round(sum(r["initial_match"].get(3, 0) for r in results
|
||
if 3 in r["initial_match"]) /
|
||
max(1, sum(1 for r in results if 3 in r["initial_match"])) * 100, 1),
|
||
"path_corr": round(float(np.mean(corrs)), 3),
|
||
"bar_match": round(float(np.mean(bmatch)), 1),
|
||
"trail_wr": round(wr, 1),
|
||
"trail_avg_pnl": round(avg_pnl, 2),
|
||
"trail_mfe": round(avg_mfe, 2),
|
||
"rand_wr": round(rand_wr, 1),
|
||
"edge_wr": round(edge_wr, 1),
|
||
"edge_pnl": round(edge_pnl, 2),
|
||
"prod_wr": 0, "prod_n": 0,
|
||
}
|
||
|
||
|
||
# Global price cache for random baseline
|
||
prices_cache = {}
|
||
|
||
|
||
def main():
|
||
results_dir = Path(__file__).parent / "results"
|
||
print("=" * 70)
|
||
print("EXP26c: TREND PREDICTION QUALITY — REMIZOV FORMULA")
|
||
print("=" * 70)
|
||
print("Trading-aligned windows (K-offset, as in prod)")
|
||
print(f"Trailing stop: ATR × {STOP_MULT} × {STOP_SCALE}, lookahead={LOOKAHEAD} bars")
|
||
print("Includes random baseline (reverse direction) for edge measurement\n")
|
||
|
||
dataset = load_or_fetch("default")
|
||
all_summaries = []
|
||
|
||
for a in ASSETS:
|
||
ticker = a["ticker"]
|
||
if ticker not in dataset:
|
||
print(f" {ticker}: not in dataset, skip")
|
||
continue
|
||
|
||
prices = dataset[ticker]["prices"]
|
||
prices_cache[ticker] = prices
|
||
print(f" Training {ticker} (ws={a['ws']}, K={a['K']})...", end=" ", flush=True)
|
||
results = _analyze_asset(ticker, prices, a["ws"], a["K"], a["shift"])
|
||
if results is None:
|
||
print("not enough data")
|
||
continue
|
||
print(f"{len(results)} signals")
|
||
|
||
# Update prod filter stats
|
||
summary = _print_report(ticker, results, a["K"], a["shift"])
|
||
prod = [r for r in results if r["is_long"] and r["confirmed"]
|
||
and r["confidence"] >= 1.5]
|
||
if prod:
|
||
summary["prod_wr"] = round(sum(1 for r in prod if r["is_win"]) /
|
||
len(prod) * 100, 1)
|
||
summary["prod_n"] = len(prod)
|
||
all_summaries.append(summary)
|
||
|
||
# ── Cross-asset summary ──
|
||
print(f"\n{'═' * 70}")
|
||
print("CROSS-ASSET SUMMARY")
|
||
print(f"{'═' * 70}")
|
||
print(f" {'Asset':<10s} {'1-bar':>5s} {'3-bar':>5s} {'Path r':>6s} "
|
||
f"{'TS WR':>5s} {'TS avg':>6s} {'Rand':>5s} {'Edge':>5s} "
|
||
f"{'PROD':>5s} {'N':>4s}")
|
||
print(f" {'-' * 65}")
|
||
for s in all_summaries:
|
||
print(f" {s['ticker']:<10s} {s['initial_1bar']:>4.1f}% {s['initial_3bar']:>4.1f}% "
|
||
f"{s['path_corr']:>6.3f} {s['trail_wr']:>4.1f}% {s['trail_avg_pnl']:>+5.2f}% "
|
||
f"{s['rand_wr']:>4.1f}% {s['edge_wr']:>+4.1f} "
|
||
f"{s['prod_wr']:>4.1f}% {s['prod_n']:>4d}")
|
||
|
||
if all_summaries:
|
||
print(f"\n Avg initial 1-bar: {np.mean([s['initial_1bar'] for s in all_summaries]):.1f}%")
|
||
print(f" Avg initial 3-bar: {np.mean([s['initial_3bar'] for s in all_summaries]):.1f}%")
|
||
print(f" Avg trail WR: {np.mean([s['trail_wr'] for s in all_summaries]):.1f}% "
|
||
f"(random: {np.mean([s['rand_wr'] for s in all_summaries]):.1f}%)")
|
||
avg_edge = np.mean([s['edge_wr'] for s in all_summaries])
|
||
print(f" Avg WR edge vs random: {avg_edge:+.1f}pp")
|
||
print(f" Avg PnL edge vs random: "
|
||
f"{np.mean([s['edge_pnl'] for s in all_summaries]):+.2f}%")
|
||
|
||
path = save_results({"summaries": all_summaries}, results_dir, "exp26c_trend")
|
||
print(f"\nSaved: {path}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|