Результаты: Daily фильтр ухудшает 4H стратегию. 4H baseline Sharpe 2.07 (BTC) / 2.47 (ETH) — лучший вариант. Daily фильтр режет сделки вдвое без прироста WR. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
456 lines
14 KiB
Python
456 lines
14 KiB
Python
"""
|
|
Multi-Timeframe Strategy Test.
|
|
|
|
Idea: Daily model provides strategic direction filter for 4H entries.
|
|
- Daily (64 days context) → trend direction
|
|
- 4H (10.7 days context) → precise entry timing
|
|
- Only take 4H trades that align with Daily direction
|
|
|
|
Variants:
|
|
A) 4H baseline (no filter)
|
|
B) Direction filter: Daily pred direction must match 4H direction
|
|
C) Confirmed direction: Daily shape confirmed + direction match
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
import warnings
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn as nn
|
|
import yfinance as yf
|
|
|
|
from models import EnhancedRemizovNet
|
|
|
|
warnings.filterwarnings("ignore")
|
|
|
|
WINDOW_SIZE = 64
|
|
N_STEPS = 20
|
|
TOTAL_TIME = 0.5
|
|
EPOCHS = 200
|
|
FINETUNE_EPOCHS = 50
|
|
LR = 3e-3
|
|
SHIFT = 7
|
|
K = 2
|
|
CORR_THRESH = 0.5
|
|
|
|
INITIAL_EQUITY = 10000.0
|
|
RISK_PER_TRADE = 0.02
|
|
COMMISSION = 0.001
|
|
|
|
|
|
def create_model():
|
|
return EnhancedRemizovNet(
|
|
grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME,
|
|
dx=1.0 / WINDOW_SIZE, use_sde=True,
|
|
)
|
|
|
|
|
|
def train_model(model, windows, targets, epochs):
|
|
g = torch.tensor(windows, dtype=torch.float32)
|
|
y = torch.tensor(targets, dtype=torch.float32)
|
|
opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4)
|
|
crit = nn.MSELoss()
|
|
bs = min(64, len(windows))
|
|
for _ in range(epochs):
|
|
model.train()
|
|
perm = torch.randperm(len(g))
|
|
for i in range(0, len(g), bs):
|
|
idx = perm[i:i + bs]
|
|
opt.zero_grad()
|
|
loss = crit(model(g[idx], stochastic=True), y[idx])
|
|
loss.backward()
|
|
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
opt.step()
|
|
|
|
|
|
def predict(model, norm_input):
|
|
model.eval()
|
|
with torch.no_grad():
|
|
inp = torch.tensor(norm_input, dtype=torch.float32).unsqueeze(0)
|
|
return model(inp, stochastic=False).squeeze(0).numpy()
|
|
|
|
|
|
def fetch_data(ticker, interval="1d", period="max"):
|
|
hist = yf.Ticker(ticker).history(period=period, interval=interval)
|
|
if hist.empty:
|
|
return None, None
|
|
close = hist["Close"].dropna().values.astype(np.float64)
|
|
dates = [d.date() if hasattr(d, 'date') else d for d in hist["Close"].dropna().index]
|
|
return close, dates
|
|
|
|
|
|
def prepare_data(prices):
|
|
data = []
|
|
n = len(prices)
|
|
for t in range(WINDOW_SIZE, n - SHIFT, SHIFT):
|
|
w = prices[t - WINDOW_SIZE:t].copy()
|
|
future = prices[t:t + SHIFT].copy()
|
|
if len(future) < SHIFT:
|
|
continue
|
|
mu, std = w.mean(), w.std()
|
|
if std < 1e-10:
|
|
continue
|
|
s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy()
|
|
data.append({
|
|
"future_prices": future,
|
|
"norm_input": (w - mu) / std,
|
|
"norm_target": (s - mu) / std,
|
|
"mu": mu, "std": std,
|
|
"price_idx": t,
|
|
})
|
|
return data
|
|
|
|
|
|
def compute_atr(prices, idx, period=14):
|
|
if idx < period + 1:
|
|
return prices[idx] * 0.02
|
|
trs = [abs(prices[i] - prices[i - 1]) for i in range(idx - period, idx)]
|
|
return np.mean(trs) if trs else prices[idx] * 0.02
|
|
|
|
|
|
def build_daily_signals(daily_prices, daily_dates, daily_data):
|
|
"""Train daily model, produce direction signals with confirmation dates.
|
|
|
|
Returns list of (confirmed_date, direction, is_confirmed) sorted by date.
|
|
confirmed_date = date when shape confirmation completed (entry would happen).
|
|
"""
|
|
train_size = min(80, len(daily_data) - 10)
|
|
if train_size < 20:
|
|
return []
|
|
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
model = create_model()
|
|
windows = np.array([d["norm_input"] for d in daily_data[:train_size]])
|
|
targets = np.array([d["norm_target"] for d in daily_data[:train_size]])
|
|
train_model(model, windows, targets, EPOCHS)
|
|
|
|
signals = []
|
|
retrain_ctr = 0
|
|
|
|
for i in range(train_size, len(daily_data)):
|
|
d = daily_data[i]
|
|
pred = predict(model, d["norm_input"])
|
|
pred_new = pred[-SHIFT:]
|
|
pred_confirm = pred_new[:K]
|
|
|
|
if len(pred_confirm) < 2:
|
|
continue
|
|
|
|
# Direction from prediction (always available)
|
|
pred_direction = pred_new[-1] - pred_new[K - 1]
|
|
if abs(pred_direction) < 1e-10:
|
|
continue
|
|
direction = 1 if pred_direction > 0 else -1
|
|
|
|
# Shape confirmation check
|
|
actual_norm = (d["future_prices"][:K] - d["mu"]) / d["std"]
|
|
corr = np.corrcoef(pred_confirm, actual_norm)[0, 1]
|
|
confirmed = not np.isnan(corr) and corr >= CORR_THRESH
|
|
|
|
# Date when this signal is known: after K bars of the prediction window
|
|
pidx = d["price_idx"]
|
|
confirm_idx = min(pidx + K - 1, len(daily_dates) - 1)
|
|
confirm_date = daily_dates[confirm_idx]
|
|
|
|
signals.append({
|
|
"date": confirm_date,
|
|
"direction": direction,
|
|
"confirmed": confirmed,
|
|
})
|
|
|
|
retrain_ctr += 1
|
|
if retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in daily_data[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in daily_data[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
return signals
|
|
|
|
|
|
def build_daily_lookup(signals):
|
|
"""Build date → (direction, confirmed) lookup.
|
|
|
|
For any date, return the most recent daily signal that was confirmed
|
|
BEFORE that date (no look-ahead).
|
|
"""
|
|
if not signals:
|
|
return {}
|
|
|
|
# Sort by date
|
|
sorted_sigs = sorted(signals, key=lambda s: s["date"])
|
|
|
|
# For each date, the active signal is the latest one confirmed on or before that date
|
|
# Build a list for binary search
|
|
return sorted_sigs
|
|
|
|
|
|
def lookup_daily(sorted_signals, query_date):
|
|
"""Find latest daily signal confirmed on or before query_date.
|
|
|
|
Returns (direction, confirmed) or None if no signal available.
|
|
"""
|
|
if not sorted_signals:
|
|
return None
|
|
|
|
# Binary search for latest signal <= query_date
|
|
lo, hi = 0, len(sorted_signals) - 1
|
|
result = None
|
|
while lo <= hi:
|
|
mid = (lo + hi) // 2
|
|
if sorted_signals[mid]["date"] <= query_date:
|
|
result = sorted_signals[mid]
|
|
lo = mid + 1
|
|
else:
|
|
hi = mid - 1
|
|
|
|
return result
|
|
|
|
|
|
def run_4h_backtest(prices_4h, dates_4h, data_4h, daily_signals, mode="baseline"):
|
|
"""Run 4H backtest with optional daily filter.
|
|
|
|
mode:
|
|
"baseline" - no daily filter
|
|
"direction" - daily direction must match (any daily pred, no confirmation needed)
|
|
"confirmed" - daily shape confirmed AND direction must match
|
|
"""
|
|
train_size = min(80, len(data_4h) - 10)
|
|
if train_size < 20:
|
|
return {"trades": [], "n_windows": len(data_4h)}
|
|
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
model = create_model()
|
|
windows = np.array([d["norm_input"] for d in data_4h[:train_size]])
|
|
targets = np.array([d["norm_target"] for d in data_4h[:train_size]])
|
|
train_model(model, windows, targets, EPOCHS)
|
|
|
|
equity = INITIAL_EQUITY
|
|
trades = []
|
|
retrain_ctr = 0
|
|
filtered_by_daily = 0
|
|
|
|
for i in range(train_size, len(data_4h)):
|
|
d = data_4h[i]
|
|
pred = predict(model, d["norm_input"])
|
|
pred_new = pred[-SHIFT:]
|
|
pred_confirm = pred_new[:K]
|
|
|
|
if len(pred_confirm) < 2:
|
|
continue
|
|
|
|
actual_norm = (d["future_prices"][:K] - d["mu"]) / d["std"]
|
|
corr = np.corrcoef(pred_confirm, actual_norm)[0, 1]
|
|
|
|
if np.isnan(corr) or corr < CORR_THRESH:
|
|
retrain_ctr += 1
|
|
if retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data_4h[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data_4h[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
continue
|
|
|
|
# 4H direction
|
|
pred_direction = pred_new[-1] - pred_new[K - 1]
|
|
if abs(pred_direction) < 1e-10:
|
|
continue
|
|
direction_4h = 1 if pred_direction > 0 else -1
|
|
|
|
# Daily filter
|
|
if mode != "baseline" and daily_signals:
|
|
pidx = d["price_idx"]
|
|
bar_date = dates_4h[min(pidx, len(dates_4h) - 1)]
|
|
daily_sig = lookup_daily(daily_signals, bar_date)
|
|
|
|
if daily_sig is None:
|
|
filtered_by_daily += 1
|
|
continue
|
|
|
|
if mode == "confirmed" and not daily_sig["confirmed"]:
|
|
filtered_by_daily += 1
|
|
continue
|
|
|
|
if daily_sig["direction"] != direction_4h:
|
|
filtered_by_daily += 1
|
|
continue
|
|
|
|
entry_price = d["future_prices"][K - 1]
|
|
direction = direction_4h
|
|
|
|
# ATR stop
|
|
pidx = d["price_idx"]
|
|
atr = compute_atr(prices_4h, pidx)
|
|
stop_dist = max(atr * 2.0, entry_price * 0.005)
|
|
|
|
risk_amount = equity * RISK_PER_TRADE
|
|
pos_size = risk_amount / stop_dist
|
|
pos_value = pos_size * entry_price
|
|
if pos_value > equity:
|
|
pos_size = equity / entry_price
|
|
pos_value = equity
|
|
|
|
# Trailing stop
|
|
exit_price = d["future_prices"][-1]
|
|
stopped = False
|
|
best_price = entry_price
|
|
for hp in d["future_prices"][K:]:
|
|
if direction == 1:
|
|
best_price = max(best_price, hp)
|
|
if hp <= best_price - stop_dist:
|
|
exit_price = best_price - stop_dist
|
|
stopped = True
|
|
break
|
|
else:
|
|
best_price = min(best_price, hp)
|
|
if hp >= best_price + stop_dist:
|
|
exit_price = best_price + stop_dist
|
|
stopped = True
|
|
break
|
|
|
|
pnl_gross = pos_size * (exit_price - entry_price) * direction
|
|
commission_cost = pos_value * COMMISSION * 2
|
|
pnl_net = pnl_gross - commission_cost
|
|
equity += pnl_net
|
|
|
|
trade_date = dates_4h[min(pidx, len(dates_4h) - 1)]
|
|
trades.append({
|
|
"date": trade_date,
|
|
"pnl_pct": pnl_net / pos_value * 100 if pos_value > 0 else 0,
|
|
"pnl_net": pnl_net,
|
|
"win": pnl_net > 0,
|
|
"stopped": stopped,
|
|
"equity": equity,
|
|
})
|
|
|
|
retrain_ctr += 1
|
|
if retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data_4h[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data_4h[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
return {"trades": trades, "n_windows": len(data_4h), "filtered": filtered_by_daily}
|
|
|
|
|
|
def print_result(trades, label, n_windows, filtered=0):
|
|
if not trades:
|
|
print(f" {label:<35s} win={n_windows:>5d} filt={filtered:>4d} NO TRADES")
|
|
return
|
|
|
|
n = len(trades)
|
|
wins = sum(1 for t in trades if t["win"])
|
|
final_eq = trades[-1]["equity"]
|
|
total_ret = (final_eq / INITIAL_EQUITY - 1) * 100
|
|
wr = wins / n * 100
|
|
|
|
peak = INITIAL_EQUITY
|
|
max_dd = 0
|
|
for t in trades:
|
|
peak = max(peak, t["equity"])
|
|
dd = (t["equity"] - peak) / peak
|
|
max_dd = min(max_dd, dd)
|
|
|
|
trade_rets = [t["pnl_pct"] / 100 for t in trades]
|
|
first = trades[0]["date"]
|
|
last = trades[-1]["date"]
|
|
if hasattr(first, 'date'):
|
|
first = first.date()
|
|
if hasattr(last, 'date'):
|
|
last = last.date()
|
|
days = (last - first).days
|
|
years = days / 365.25 if days > 0 else 1
|
|
tpy = n / years
|
|
|
|
if len(trade_rets) > 2 and np.std(trade_rets) > 0:
|
|
sharpe = np.mean(trade_rets) / np.std(trade_rets) * np.sqrt(tpy)
|
|
else:
|
|
sharpe = 0
|
|
|
|
stopped = sum(1 for t in trades if t["stopped"])
|
|
monthly_pnl = sum(t["pnl_net"] for t in trades) / max(years * 12, 1)
|
|
|
|
print(f" {label:<35s} win={n_windows:>5d} N={n:>4d} WR={wr:>4.0f}% "
|
|
f"Ret={total_ret:>+7.1f}% Sharpe={sharpe:>+5.2f} DD={max_dd:>+5.1f}% "
|
|
f"Stops={stopped:>3d} filt={filtered:>3d} $/mo={monthly_pnl:>+7.0f} Eq=${final_eq:>9,.0f}")
|
|
|
|
|
|
def main():
|
|
t0 = time.time()
|
|
|
|
print("=" * 120)
|
|
print("MULTI-TIMEFRAME STRATEGY TEST: Daily filter for 4H entries")
|
|
print("=" * 120)
|
|
print(" A) 4H baseline (no filter)")
|
|
print(" B) Direction filter: Daily pred direction must match 4H")
|
|
print(" C) Confirmed direction: Daily shape confirmed + direction match")
|
|
print()
|
|
|
|
assets = ["BTC-USD", "ETH-USD"]
|
|
|
|
for asset in assets:
|
|
print(f"\n{'=' * 120}")
|
|
print(f" {asset}")
|
|
print(f"{'=' * 120}")
|
|
|
|
# Fetch daily data
|
|
print("\n Fetching daily data...", end=" ", flush=True)
|
|
daily_prices, daily_dates = fetch_data(asset, "1d", "max")
|
|
if daily_prices is None:
|
|
print("ERROR")
|
|
continue
|
|
print(f"{len(daily_prices)} bars")
|
|
|
|
# Fetch 4H data
|
|
print(" Fetching 4H data...", end=" ", flush=True)
|
|
prices_4h, dates_4h = fetch_data(asset, "4h", "730d")
|
|
if prices_4h is None:
|
|
print("ERROR")
|
|
continue
|
|
print(f"{len(prices_4h)} bars")
|
|
|
|
# Prepare data
|
|
daily_data = prepare_data(daily_prices)
|
|
data_4h = prepare_data(prices_4h)
|
|
|
|
# Build daily signals
|
|
print(" Training daily model...", end=" ", flush=True)
|
|
daily_signals = build_daily_signals(daily_prices, daily_dates, daily_data)
|
|
n_confirmed = sum(1 for s in daily_signals if s["confirmed"])
|
|
print(f"done ({len(daily_signals)} signals, {n_confirmed} confirmed)")
|
|
|
|
# Date range overlap
|
|
if daily_signals and dates_4h:
|
|
d_start = daily_signals[0]["date"]
|
|
d_end = daily_signals[-1]["date"]
|
|
h_start = dates_4h[0]
|
|
h_end = dates_4h[-1]
|
|
print(f" Daily signals: {d_start} to {d_end}")
|
|
print(f" 4H data: {h_start} to {h_end}")
|
|
|
|
# Test 3 modes
|
|
modes = [
|
|
("baseline", "A) 4H baseline"),
|
|
("direction", "B) 4H + Daily direction"),
|
|
("confirmed", "C) 4H + Daily confirmed dir"),
|
|
]
|
|
|
|
for mode, label in modes:
|
|
print(f"\n Testing {label}...", end=" ", flush=True)
|
|
r = run_4h_backtest(prices_4h, dates_4h, data_4h, daily_signals, mode=mode)
|
|
print("done")
|
|
print_result(r["trades"], label, r["n_windows"], r.get("filtered", 0))
|
|
|
|
elapsed = time.time() - t0
|
|
print(f"\n\nCompleted in {elapsed:.0f}s")
|
|
print("=" * 120)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|