hourly_backtest.py: сравнение daily vs hourly stop мониторинга Результат: hourly ХУЖЕ на всех 4 активах (Sharpe -0.5...-1.0) Причина: intraday фитили срабатывают стопы на шуме paper_trader.py: monitor mode через Binance (ccxt) --monitor показывает realtime цены и unrealized P&L Стопы проверяются только по daily close (доказано бэктестом) requirements.txt: добавлен ccxt>=4.5 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
469 lines
16 KiB
Python
469 lines
16 KiB
Python
"""
|
|
Hourly stop monitoring backtest.
|
|
|
|
Compares strategy performance with:
|
|
1. Daily stop checks (baseline — current approach)
|
|
2. Hourly stop checks (more granular)
|
|
|
|
Model still trains on daily data. Only stop monitoring changes.
|
|
Uses best strategy: ATR + Trailing stop.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
import warnings
|
|
from datetime import date, datetime
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn as nn
|
|
import yfinance as yf
|
|
|
|
from models import EnhancedRemizovNet
|
|
|
|
warnings.filterwarnings("ignore")
|
|
|
|
# -- Config ------------------------------------------------------------------
|
|
|
|
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
|
|
|
|
ASSET_CONFIGS = {
|
|
"BTC-USD": {"K": 2, "corr_thresh": 0.7},
|
|
"ETH-USD": {"K": 2, "corr_thresh": 0.5},
|
|
"SOL-USD": {"K": 3, "corr_thresh": 0.5},
|
|
"BNB-USD": {"K": 3, "corr_thresh": 0.5},
|
|
}
|
|
|
|
|
|
# -- Model -------------------------------------------------------------------
|
|
|
|
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()
|
|
|
|
|
|
# -- Data --------------------------------------------------------------------
|
|
|
|
def fetch_daily(ticker):
|
|
"""Fetch daily close prices for full history."""
|
|
hist = yf.Ticker(ticker).history(period="max")
|
|
prices = hist["Close"].dropna()
|
|
dates = [d.date() for d in prices.index]
|
|
return prices.values.astype(np.float64), dates
|
|
|
|
|
|
def fetch_hourly(ticker):
|
|
"""Fetch hourly OHLC for last 2 years."""
|
|
hist = yf.Ticker(ticker).history(period="730d", interval="1h")
|
|
return hist
|
|
|
|
|
|
def build_hourly_map(hourly_df):
|
|
"""Build date -> list of hourly prices map."""
|
|
hourly_by_date = {}
|
|
for ts, row in hourly_df.iterrows():
|
|
d = ts.date()
|
|
if d not in hourly_by_date:
|
|
hourly_by_date[d] = []
|
|
hourly_by_date[d].append({
|
|
"time": ts,
|
|
"open": row["Open"],
|
|
"high": row["High"],
|
|
"low": row["Low"],
|
|
"close": row["Close"],
|
|
})
|
|
return hourly_by_date
|
|
|
|
|
|
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
|
|
|
|
|
|
# -- Backtest engine with hourly stops --------------------------------------
|
|
|
|
def run_backtest(
|
|
prices, dates, data, cfg,
|
|
hourly_map=None, # None = daily stops, dict = hourly stops
|
|
use_trailing=True,
|
|
):
|
|
"""Run backtest. If hourly_map provided, check stops on hourly bars."""
|
|
K = cfg["K"]
|
|
corr_thresh = cfg["corr_thresh"]
|
|
train_size = 80
|
|
|
|
n = len(data)
|
|
if n < train_size + 5:
|
|
return {"trades": [], "equity_curve": []}
|
|
|
|
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, n):
|
|
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_EPOCHS)
|
|
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
|
|
|
|
stop_price = entry_price - direction * stop_dist
|
|
exit_price = d["future_prices"][-1]
|
|
stopped = False
|
|
|
|
# Get trade dates for hourly lookup
|
|
entry_date_idx = pidx + K - 1
|
|
trade_dates = []
|
|
for dd in range(entry_date_idx, min(entry_date_idx + SHIFT - K + 1, len(dates))):
|
|
if dd < len(dates):
|
|
trade_dates.append(dates[dd])
|
|
|
|
if hourly_map is not None and trade_dates:
|
|
# HOURLY stop monitoring
|
|
best_price = entry_price
|
|
exited = False
|
|
|
|
for td in trade_dates[1:]: # skip entry day
|
|
hourly_bars = hourly_map.get(td, [])
|
|
for bar in hourly_bars:
|
|
price_check = bar["low"] if direction == 1 else bar["high"]
|
|
|
|
if use_trailing:
|
|
if direction == 1:
|
|
best_price = max(best_price, bar["high"])
|
|
current_stop = best_price - stop_dist
|
|
if bar["low"] <= current_stop:
|
|
exit_price = current_stop
|
|
stopped = True
|
|
exited = True
|
|
break
|
|
else:
|
|
best_price = min(best_price, bar["low"])
|
|
current_stop = best_price + stop_dist
|
|
if bar["high"] >= current_stop:
|
|
exit_price = current_stop
|
|
stopped = True
|
|
exited = True
|
|
break
|
|
else:
|
|
if direction == 1 and bar["low"] <= stop_price:
|
|
exit_price = stop_price
|
|
stopped = True
|
|
exited = True
|
|
break
|
|
elif direction == -1 and bar["high"] >= stop_price:
|
|
exit_price = stop_price
|
|
stopped = True
|
|
exited = True
|
|
break
|
|
if exited:
|
|
break
|
|
else:
|
|
# DAILY stop monitoring (baseline)
|
|
best_price = entry_price
|
|
for hp in d["future_prices"][K:]:
|
|
if use_trailing:
|
|
if direction == 1:
|
|
best_price = max(best_price, hp)
|
|
trailing_stop = best_price - stop_dist
|
|
if hp <= trailing_stop:
|
|
exit_price = trailing_stop
|
|
stopped = True
|
|
break
|
|
else:
|
|
best_price = min(best_price, hp)
|
|
trailing_stop = best_price + stop_dist
|
|
if hp >= trailing_stop:
|
|
exit_price = trailing_stop
|
|
stopped = True
|
|
break
|
|
else:
|
|
if direction == 1 and hp <= stop_price:
|
|
exit_price = stop_price
|
|
stopped = True
|
|
break
|
|
elif direction == -1 and hp >= stop_price:
|
|
exit_price = stop_price
|
|
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,
|
|
"direction": "L" if direction == 1 else "S",
|
|
"entry": entry_price,
|
|
"exit": exit_price,
|
|
"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_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
return {"trades": trades}
|
|
|
|
|
|
def calc_metrics(trades, label=""):
|
|
if not trades:
|
|
return {"label": label, "n": 0, "ret": 0, "sharpe": 0, "dd": 0,
|
|
"wr": 0, "stops": 0, "eq": INITIAL_EQUITY}
|
|
|
|
wins = [t for t in trades if t["win"]]
|
|
losses = [t for t in trades if not t["win"]]
|
|
final_eq = trades[-1]["equity"]
|
|
total_ret = (final_eq / INITIAL_EQUITY - 1) * 100
|
|
wr = len(wins) / len(trades) * 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)
|
|
|
|
first_date = trades[0]["date"]
|
|
last_date = trades[-1]["date"]
|
|
years = (last_date - first_date).days / 365.25
|
|
trade_rets = [t["pnl_pct"] / 100 for t in trades]
|
|
if len(trade_rets) > 2 and np.std(trade_rets) > 0 and years > 0:
|
|
tpy = len(trade_rets) / years
|
|
sharpe = np.mean(trade_rets) / np.std(trade_rets) * np.sqrt(tpy)
|
|
else:
|
|
sharpe = 0
|
|
|
|
pf = abs(sum(t["pnl_pct"] for t in wins) / sum(t["pnl_pct"] for t in losses)) \
|
|
if losses and sum(t["pnl_pct"] for t in losses) != 0 else float("inf")
|
|
|
|
return {
|
|
"label": label, "n": len(trades), "w": len(wins), "l": len(losses),
|
|
"wr": round(wr, 1), "ret": round(total_ret, 1),
|
|
"sharpe": round(sharpe, 2), "dd": round(max_dd * 100, 1),
|
|
"pf": round(pf, 2), "stops": sum(1 for t in trades if t["stopped"]),
|
|
"eq": round(final_eq, 0),
|
|
}
|
|
|
|
|
|
def print_row(m):
|
|
print(f" {m['label']:<30s} {m['n']:>4d} {m['w']:>3d}/{m['l']:<3d} "
|
|
f"{m['wr']:>5.1f}% {m['ret']:>+8.1f}% {m['sharpe']:>6.2f} "
|
|
f"{m['dd']:>+6.1f}% {m['pf']:>5.2f} {m['stops']:>5d} ${m['eq']:>9,.0f}")
|
|
|
|
|
|
# -- Main --------------------------------------------------------------------
|
|
|
|
def main():
|
|
t0 = time.time()
|
|
|
|
print("=" * 100)
|
|
print("HOURLY vs DAILY STOP MONITORING COMPARISON")
|
|
print("=" * 100)
|
|
print(" Strategy: ATR stop + Trailing stop")
|
|
print(" Hourly data: last 2 years (yfinance)")
|
|
print(" Daily data: full history (model training)")
|
|
print()
|
|
|
|
for asset, cfg in ASSET_CONFIGS.items():
|
|
print(f"\n{'=' * 100}")
|
|
print(f" {asset}")
|
|
print(f"{'=' * 100}")
|
|
|
|
time.sleep(1)
|
|
|
|
# Fetch data
|
|
print(f" Fetching daily data...", end=" ", flush=True)
|
|
prices, dates = fetch_daily(asset)
|
|
data = prepare_data(prices)
|
|
print(f"{len(data)} windows")
|
|
|
|
print(f" Fetching hourly data...", end=" ", flush=True)
|
|
hourly_df = fetch_hourly(asset)
|
|
hourly_map = build_hourly_map(hourly_df)
|
|
n_hourly_days = len(hourly_map)
|
|
print(f"{len(hourly_df)} bars ({n_hourly_days} days)")
|
|
|
|
# Filter data to only overlap period (where hourly data exists)
|
|
hourly_dates = set(hourly_map.keys())
|
|
min_hourly = min(hourly_dates)
|
|
|
|
# Find data indices that fall within hourly period
|
|
overlap_indices = []
|
|
for i, d in enumerate(data):
|
|
pidx = d["price_idx"]
|
|
if pidx < len(dates) and dates[pidx] >= min_hourly:
|
|
overlap_indices.append(i)
|
|
|
|
if not overlap_indices:
|
|
print(f" No overlapping data — skipping")
|
|
continue
|
|
|
|
# We need train_size=80 before the overlap
|
|
first_overlap = overlap_indices[0]
|
|
if first_overlap < 80:
|
|
print(f" Not enough training data before hourly period — using full daily")
|
|
# Still run both, but hourly map may miss some early trades
|
|
else:
|
|
print(f" Overlap: {len(overlap_indices)} windows from {min_hourly}")
|
|
|
|
print()
|
|
print(f" {'Label':<30s} {'N':>4s} {'W/L':>7s} "
|
|
f"{'WR%':>6s} {'Ret%':>9s} {'Sharpe':>6s} "
|
|
f"{'DD%':>7s} {'PF':>5s} {'Stops':>5s} {'Equity':>10s}")
|
|
print(f" {'─' * 95}")
|
|
|
|
# 1. Daily stops + trailing (baseline)
|
|
r1 = run_backtest(prices, dates, data, cfg, hourly_map=None, use_trailing=True)
|
|
m1 = calc_metrics(r1["trades"], "Daily + Trailing (baseline)")
|
|
print_row(m1)
|
|
|
|
# 2. Hourly stops + trailing
|
|
r2 = run_backtest(prices, dates, data, cfg, hourly_map=hourly_map, use_trailing=True)
|
|
m2 = calc_metrics(r2["trades"], "Hourly + Trailing")
|
|
print_row(m2)
|
|
|
|
# 3. Daily stops, no trailing
|
|
r3 = run_backtest(prices, dates, data, cfg, hourly_map=None, use_trailing=False)
|
|
m3 = calc_metrics(r3["trades"], "Daily + Fixed stop")
|
|
print_row(m3)
|
|
|
|
# 4. Hourly stops, no trailing
|
|
r4 = run_backtest(prices, dates, data, cfg, hourly_map=hourly_map, use_trailing=False)
|
|
m4 = calc_metrics(r4["trades"], "Hourly + Fixed stop")
|
|
print_row(m4)
|
|
|
|
# Analysis
|
|
print()
|
|
if m1["n"] > 0 and m2["n"] > 0:
|
|
sharpe_diff = m2["sharpe"] - m1["sharpe"]
|
|
ret_diff = m2["ret"] - m1["ret"]
|
|
stop_diff = m2["stops"] - m1["stops"]
|
|
print(f" Hourly vs Daily trailing: "
|
|
f"Sharpe {sharpe_diff:+.2f}, "
|
|
f"Return {ret_diff:+.1f}%, "
|
|
f"Stops {stop_diff:+d}")
|
|
|
|
if m2["sharpe"] > m1["sharpe"]:
|
|
print(f" → Hourly monitoring IMPROVES results")
|
|
else:
|
|
print(f" → Hourly monitoring HURTS results (more noise stops)")
|
|
|
|
elapsed = time.time() - t0
|
|
print(f"\n\nCompleted in {elapsed:.0f}s")
|
|
print("=" * 100)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|