feat: hourly backtest + ccxt monitor + результаты сравнения

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>
This commit is contained in:
anor
2026-03-08 13:55:14 +10:00
co-authored by Claude Opus 4.6
parent 389a173611
commit 8fcd83d55e
3 changed files with 711 additions and 3 deletions
+468
View File
@@ -0,0 +1,468 @@
"""
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()
+242 -3
View File
@@ -1,14 +1,16 @@
"""
Paper trading system for RemizovNet.
Runs daily via cron. Uses best strategy: ATR stop + Trailing stop.
Uses best strategy: ATR stop + Trailing stop.
Maintains persistent state (model, positions, equity) between runs.
Usage:
python paper_trader.py # daily update (for cron)
Modes:
python paper_trader.py # daily update (signals + stops via yfinance)
python paper_trader.py --init # initialize: train models, create state
python paper_trader.py --status # show current positions and equity
python paper_trader.py --history # show trade history
python paper_trader.py --monitor # realtime stop monitor via Binance (ccxt)
python paper_trader.py --monitor --interval 240 # check every 4h (default)
State file: paper_state.json
Trade log: logs/paper_trades.jsonl (append-only)
@@ -26,6 +28,7 @@ import warnings
from datetime import date, datetime, timedelta
from pathlib import Path
import ccxt
import numpy as np
import torch
import torch.nn as nn
@@ -57,6 +60,14 @@ MODEL_DIR = Path(__file__).parent / "paper_models"
LOG_DIR = Path(__file__).parent / "logs"
TRADE_LOG = LOG_DIR / "paper_trades.jsonl"
# Yahoo Finance ticker -> Binance symbol mapping
BINANCE_SYMBOLS = {
"BTC-USD": "BTC/USDT",
"ETH-USD": "ETH/USDT",
"SOL-USD": "SOL/USDT",
"BNB-USD": "BNB/USDT",
}
# Best strategy per asset from A/B testing
ASSET_CONFIGS = {
"BTC-USD": {
@@ -693,6 +704,228 @@ def show_history():
f"({event['windows']} windows)")
# -- Realtime stop monitor via Binance (ccxt) --------------------------------
def _fetch_realtime_price(exchange, asset):
"""Get current price from Binance."""
symbol = BINANCE_SYMBOLS.get(asset)
if not symbol:
return None
try:
ticker = exchange.fetch_ticker(symbol)
return ticker["last"]
except Exception as e:
print(f" {asset}: fetch error ({e})")
return None
def _monitor_check_stops(state, exchange):
"""Check all open positions against realtime prices. Close if stopped."""
closed_any = False
now = datetime.now()
for asset in ASSET_CONFIGS:
asset_state = state["assets"].get(asset)
if asset_state is None:
continue
pos = asset_state.get("open_position")
if pos is None:
continue
price = _fetch_realtime_price(exchange, asset)
if price is None:
continue
direction = pos["direction"]
entry_price = pos["entry_price"]
stop_price = pos["stop_price"]
stop_dist = pos["stop_dist"]
best_price = pos["best_price"]
pos_size = pos["pos_size"]
pos_value = pos["pos_value"]
entry_date = date.fromisoformat(pos["entry_date"])
days_held = (date.today() - entry_date).days
# Update trailing stop
cfg = asset_state["config"]
if cfg.get("trailing_stop", False):
if direction == 1 and price > best_price:
pos["best_price"] = price
best_price = price
elif direction == -1 and price < best_price:
pos["best_price"] = price
best_price = price
if direction == 1:
new_stop = best_price - stop_dist
if new_stop > stop_price:
pos["stop_price"] = new_stop
stop_price = new_stop
else:
new_stop = best_price + stop_dist
if new_stop < stop_price:
pos["stop_price"] = new_stop
stop_price = new_stop
# Check stop
stopped = False
if direction == 1 and price <= stop_price:
stopped = True
elif direction == -1 and price >= stop_price:
stopped = True
# Check time exit
max_hold = SHIFT - pos.get("K_used", 2)
time_exit = days_held >= max_hold
dir_str = "LONG" if direction == 1 else "SHORT"
unrealized = pos_size * (price - entry_price) * direction
if stopped or time_exit:
exit_price = stop_price if stopped else price
exit_reason = "stop" if stopped else "time"
pnl_gross = pos_size * (exit_price - entry_price) * direction
commission_cost = pos_value * COMMISSION * 2
pnl_net = pnl_gross - commission_cost
pnl_pct = pnl_net / pos_value * 100 if pos_value > 0 else 0
asset_state["equity"] += pnl_net
asset_state["peak_equity"] = max(
asset_state["peak_equity"], asset_state["equity"]
)
asset_state["trades_count"] += 1
asset_state["total_pnl"] += pnl_net
win = pnl_net > 0
if win:
asset_state["wins"] += 1
else:
asset_state["losses"] += 1
asset_state["open_position"] = None
closed_any = True
win_str = "WIN" if win else "LOSS"
print(f" {now.strftime('%H:%M:%S')} {asset} CLOSED {dir_str}: "
f"${entry_price:,.2f} → ${exit_price:,.2f} ({exit_reason}) "
f"PnL ${pnl_net:+,.2f} ({pnl_pct:+.2f}%) [{win_str}]")
log_event({
"type": "close",
"asset": asset,
"direction": dir_str,
"entry_price": entry_price,
"exit_price": exit_price,
"entry_date": pos["entry_date"],
"exit_date": str(date.today()),
"days_held": days_held,
"exit_reason": exit_reason,
"pnl_net": round(pnl_net, 2),
"pnl_pct": round(pnl_pct, 4),
"equity_after": round(asset_state["equity"], 2),
"win": win,
"source": "monitor",
})
else:
print(f" {now.strftime('%H:%M:%S')} {asset} {dir_str}: "
f"${price:,.2f} (stop ${stop_price:,.2f}, "
f"unreal ${unrealized:+,.2f}, day {days_held})")
return closed_any
def run_monitor(interval_minutes=240):
"""Run continuous position monitor. Shows realtime prices from Binance.
NOTE: Hourly backtest proved that intraday stop monitoring HURTS results
(Sharpe drops by 0.5-1.0 across all assets due to noise stops on wicks).
Stops are only checked on DAILY close via daily_update().
This monitor shows unrealized P&L only — no stop execution.
"""
state = load_state()
if state is None:
print("ERROR: No state found. Run with --init first.")
sys.exit(1)
exchange = ccxt.binance({"enableRateLimit": True})
print(f"{'=' * 70}")
print(f"POSITION MONITOR (Binance, every {interval_minutes}min)")
print(f"{'=' * 70}")
print(f" NOTE: stops checked on DAILY close only (hourly hurts results)")
# Check which assets have open positions
open_assets = []
for asset in ASSET_CONFIGS:
a = state["assets"].get(asset)
if a and a.get("open_position"):
pos = a["open_position"]
d = "LONG" if pos["direction"] == 1 else "SHORT"
print(f" {asset}: {d} @ ${pos['entry_price']:,.2f}, "
f"stop ${pos['stop_price']:,.2f}")
open_assets.append(asset)
if not open_assets:
print("\n No open positions to monitor.")
print(" Run daily update first to generate signals.")
return
print(f"\n Monitoring {len(open_assets)} positions...")
print(f" Press Ctrl+C to stop.\n")
try:
while True:
state = load_state()
if state is None:
break
has_open = any(
state["assets"].get(a, {}).get("open_position")
for a in ASSET_CONFIGS
)
if not has_open:
print(f"\n All positions closed. Stopping monitor.")
break
# Show current prices and unrealized P&L (NO stop execution)
now = datetime.now()
for asset in ASSET_CONFIGS:
asset_state = state["assets"].get(asset)
if not asset_state:
continue
pos = asset_state.get("open_position")
if not pos:
continue
price = _fetch_realtime_price(exchange, asset)
if price is None:
continue
direction = pos["direction"]
entry_price = pos["entry_price"]
stop_price = pos["stop_price"]
pos_size = pos["pos_size"]
entry_date = date.fromisoformat(pos["entry_date"])
days_held = (date.today() - entry_date).days
unrealized = pos_size * (price - entry_price) * direction
dir_str = "LONG" if direction == 1 else "SHORT"
dist_to_stop = abs(price - stop_price)
print(f" {now.strftime('%H:%M:%S')} {asset} {dir_str}: "
f"${price:,.2f} (stop ${stop_price:,.2f}, "
f"dist ${dist_to_stop:,.2f}, "
f"unreal ${unrealized:+,.2f}, day {days_held})")
time.sleep(interval_minutes * 60)
except KeyboardInterrupt:
print(f"\n\n Monitor stopped.")
_print_portfolio_summary(state)
# -- Entry point -------------------------------------------------------------
def main():
@@ -703,6 +936,10 @@ def main():
help="Show current positions and equity")
parser.add_argument("--history", action="store_true",
help="Show trade history")
parser.add_argument("--monitor", action="store_true",
help="Realtime stop monitor via Binance")
parser.add_argument("--interval", type=int, default=240,
help="Monitor check interval in minutes (default: 240)")
args = parser.parse_args()
if args.init:
@@ -711,6 +948,8 @@ def main():
show_status()
elif args.history:
show_history()
elif args.monitor:
run_monitor(args.interval)
else:
daily_update()
+1
View File
@@ -3,4 +3,5 @@ scipy>=1.12
torch>=2.2
matplotlib>=3.8
yfinance>=0.2.36
ccxt>=4.5
remizov-net @ file:///Users/alchemist/Python_projects/remizov-net