315 lines
9.7 KiB
Python
315 lines
9.7 KiB
Python
"""
|
||
Test RemizovNet on smaller timeframes (4h, 1h).
|
||
|
||
Model is timeframe-agnostic: 64-bar input, 7-bar prediction.
|
||
Daily: 64 days input → predict 7 days (~40 trades/year)
|
||
4H: 64×4h input → predict 7×4h (~200 trades/month?)
|
||
1H: 64×1h input → predict 7×1h (~500 trades/month?)
|
||
|
||
Key question: does shape confirmation still work on shorter bars?
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import time
|
||
import warnings
|
||
from datetime import date
|
||
|
||
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
|
||
|
||
INITIAL_EQUITY = 10000.0
|
||
RISK_PER_TRADE = 0.02
|
||
COMMISSION = 0.001 # 0.1% per side
|
||
|
||
|
||
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_timeframe(ticker, interval="1d", period="max"):
|
||
"""Fetch OHLCV data at given interval."""
|
||
hist = yf.Ticker(ticker).history(period=period, interval=interval)
|
||
if hist.empty:
|
||
return None, 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, len(close)
|
||
|
||
|
||
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 run_backtest(prices, dates, data, K, corr_thresh, fast=False):
|
||
"""Run backtest with ATR + Trailing stop (best strategy)."""
|
||
train_size = min(80, len(data) - 10)
|
||
if train_size < 20:
|
||
return {"trades": [], "n_windows": len(data)}
|
||
|
||
epochs = EPOCHS // 2 if fast else EPOCHS
|
||
finetune_ep = FINETUNE_EPOCHS // 2 if fast else FINETUNE_EPOCHS
|
||
|
||
torch.manual_seed(42)
|
||
np.random.seed(42)
|
||
model = create_model()
|
||
windows = np.array([d["norm_input"] for d in data[:train_size]])
|
||
targets = np.array([d["norm_target"] for d in data[:train_size]])
|
||
train_model(model, windows, targets, epochs)
|
||
|
||
equity = INITIAL_EQUITY
|
||
trades = []
|
||
retrain_ctr = 0
|
||
|
||
for i in range(train_size, len(data)):
|
||
d = data[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[:i + 1]])
|
||
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
|
||
train_model(model, ws, ts, finetune_ep)
|
||
retrain_ctr = 0
|
||
continue
|
||
|
||
entry_price = d["future_prices"][K - 1]
|
||
pred_direction = pred_new[-1] - pred_new[K - 1]
|
||
if abs(pred_direction) < 1e-10:
|
||
continue
|
||
direction = 1 if pred_direction > 0 else -1
|
||
|
||
# ATR stop
|
||
pidx = d["price_idx"]
|
||
atr = compute_atr(prices, 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 simulation
|
||
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[min(pidx, len(dates) - 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[:i + 1]])
|
||
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
|
||
train_model(model, ws, ts, finetune_ep)
|
||
retrain_ctr = 0
|
||
|
||
return {"trades": trades, "n_windows": len(data)}
|
||
|
||
|
||
def calc_and_print(trades, label, n_windows):
|
||
if not trades:
|
||
print(f" {label:<30s} windows={n_windows:>5d} 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]
|
||
if len(trade_rets) > 2 and np.std(trade_rets) > 0:
|
||
# Annualize: estimate trades per year
|
||
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
|
||
sharpe = np.mean(trade_rets) / np.std(trade_rets) * np.sqrt(tpy)
|
||
else:
|
||
sharpe = 0
|
||
years = 0
|
||
tpy = 0
|
||
|
||
stopped = sum(1 for t in trades if t["stopped"])
|
||
avg_pnl = np.mean([t["pnl_pct"] for t in trades])
|
||
|
||
# Monthly average
|
||
monthly_pnl = sum(t["pnl_net"] for t in trades) / max(years * 12, 1)
|
||
|
||
print(f" {label:<30s} 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:>4d} $/mo={monthly_pnl:>+7.0f} Eq=${final_eq:>9,.0f}")
|
||
|
||
|
||
def main():
|
||
t0 = time.time()
|
||
|
||
print("=" * 110)
|
||
print("TIMEFRAME COMPARISON TEST")
|
||
print("=" * 110)
|
||
print(" Model: 64-bar input, 7-bar prediction, ATR+Trailing stop")
|
||
print(" Strategy: shape confirmation (K=2, corr>0.5)")
|
||
print()
|
||
|
||
assets = ["BTC-USD", "ETH-USD"] # test on top 2 first
|
||
|
||
timeframes = [
|
||
("1d", "max", "Daily (64d→7d)"),
|
||
("4h", "730d", "4H (10.7d→28h)"),
|
||
("1h", "365d", "1H (2.7d→7h)"), # 365d to keep compute manageable
|
||
]
|
||
|
||
K = 2
|
||
corr_thresh = 0.5
|
||
|
||
for asset in assets:
|
||
print(f"\n{'=' * 110}")
|
||
print(f" {asset}")
|
||
print(f"{'=' * 110}")
|
||
|
||
for interval, period, label in timeframes:
|
||
print(f"\n Fetching {interval} data...", end=" ", flush=True)
|
||
|
||
try:
|
||
prices, dates, n_bars = fetch_timeframe(asset, interval, period)
|
||
except Exception as e:
|
||
print(f"ERROR: {e}")
|
||
continue
|
||
|
||
if prices is None or len(prices) < WINDOW_SIZE + SHIFT + 20:
|
||
print(f"not enough data ({n_bars} bars)")
|
||
continue
|
||
|
||
print(f"{n_bars} bars")
|
||
data = prepare_data(prices)
|
||
|
||
fast = interval == "1h"
|
||
print(f" Training & backtesting {label}{'(fast)' if fast else ''}...", end=" ", flush=True)
|
||
r = run_backtest(prices, dates, data, K, corr_thresh, fast=fast)
|
||
print("done")
|
||
calc_and_print(r["trades"], label, r["n_windows"])
|
||
|
||
elapsed = time.time() - t0
|
||
print(f"\n\nCompleted in {elapsed:.0f}s")
|
||
print("=" * 110)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|