feat: event-driven retrain вместо каждых 10 сигналов

Переобучение по событиям (Sharpe 3.23 vs 3.05 baseline):
- После 3 лоссов подряд
- При смене ATR-режима (low/normal/high)

Finetune вместо обучения с нуля:
- Загружает существующую модель
- 20 эпох при lr*0.3 на последних 200 окнах

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-09 14:17:50 +10:00
co-authored by Claude Opus 4.6
parent 5a5afa6a4c
commit 0c7364a008
2 changed files with 74 additions and 18 deletions
+69 -17
View File
@@ -115,15 +115,20 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
elif pos is None and cb_active:
logs.append(f"{ticker}: CB active ({cb_reason}) — skip signal")
# Equity snapshot
# Equity snapshot + track ATR regime
asset = _get_or_skip(conn, ticker)
if asset:
add_equity_snapshot(conn, ticker, asset["equity"], last_price, last_date)
current_regime = _get_atr_regime(prices, len(prices) - 1)
if asset.get("last_atr_regime") != current_regime:
update_asset(conn, ticker, last_atr_regime=current_regime)
# Retrain check
if asset and asset["signals_since_retrain"] >= 10:
_retrain(conn, ticker, prices, cfg)
logs.append(f"{ticker}: retrained")
# Event-driven retrain check
if asset:
retrain_reason = _should_retrain(asset, prices, len(prices) - 1)
if retrain_reason:
_retrain(conn, ticker, prices, cfg)
logs.append(f"{ticker}: retrained ({retrain_reason})")
return logs
@@ -222,12 +227,16 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
new_peak = max(asset["peak_equity"], new_equity)
win = pnl_net > 0
consecutive_losses = (asset.get("consecutive_losses") or 0)
consecutive_losses = 0 if win else consecutive_losses + 1
update_asset(conn, asset["ticker"],
equity=new_equity, peak_equity=new_peak,
trades_count=asset["trades_count"] + 1,
wins=asset["wins"] + (1 if win else 0),
losses=asset["losses"] + (0 if win else 1),
total_pnl=asset["total_pnl"] + pnl_net)
total_pnl=asset["total_pnl"] + pnl_net,
consecutive_losses=consecutive_losses)
dir_str = "LONG" if direction == 1 else "SHORT"
win_str = "WIN" if win else "LOSS"
@@ -392,20 +401,63 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
return msg
def _retrain(conn, ticker, prices, cfg):
"""Retrain model on all available data."""
import numpy as np
import torch
def _get_atr_regime(prices, idx):
"""Classify ATR regime: low/normal/high."""
atr14 = risk.compute_atr(prices, idx, period=14)
atr50 = risk.compute_atr(prices, idx, period=50)
ratio = atr14 / atr50 if atr50 > 0 else 1.0
if ratio < 0.7:
return "low"
if ratio > 1.5:
return "high"
return "normal"
def _should_retrain(asset, prices, idx):
"""Event-driven retrain: 3 consecutive losses OR ATR regime change.
Returns reason string or None.
"""
consecutive_losses = asset.get("consecutive_losses") or 0
if consecutive_losses >= 3:
return f"{consecutive_losses}_losses"
current_regime = _get_atr_regime(prices, idx)
last_regime = asset.get("last_atr_regime")
if last_regime and current_regime != last_regime:
return f"regime_{last_regime}_to_{current_regime}"
return None
def _retrain(conn, ticker, prices, cfg):
"""Finetune existing model on recent data."""
data = signals.prepare_windows(prices, cfg.model.window_size, cfg.model.shift)
if len(data) < 20:
return
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(cfg.model)
windows = np.array([d["norm_input"] for d in data])
targets = np.array([d["norm_target"] for d in data])
model_mod.train(mdl, windows, targets, cfg.model.finetune_epochs, cfg.model.lr)
# Use last 200 windows (recent data, not full history)
recent = data[-200:]
windows = np.array([d["norm_input"] for d in recent])
targets = np.array([d["norm_target"] for d in recent])
# Load existing model and finetune (not from scratch)
mdl = model_mod.load_model(ticker, cfg.model)
if mdl is None:
mdl = model_mod.create_model(cfg.model)
epochs = cfg.model.finetune_epochs
lr = cfg.model.lr
else:
epochs = 20
lr = cfg.model.lr * 0.3
model_mod.train(mdl, windows, targets, epochs, lr)
model_mod.save_model(mdl, ticker)
update_asset(conn, ticker, signals_since_retrain=0, last_train_date=str(date.today()))
# Track regime for next check
current_regime = _get_atr_regime(prices, len(prices) - 1)
update_asset(conn, ticker,
signals_since_retrain=0,
consecutive_losses=0,
last_atr_regime=current_regime,
last_train_date=str(date.today()))
+5 -1
View File
@@ -96,10 +96,14 @@ def init_db(conn: sqlite3.Connection) -> None:
CREATE INDEX IF NOT EXISTS idx_signals_ticker ON signals(ticker);
CREATE INDEX IF NOT EXISTS idx_equity_ticker ON equity_snapshots(ticker);
""")
# Migration: add cb_activated_at if missing
# Migrations
cols = {r[1] for r in conn.execute("PRAGMA table_info(assets)").fetchall()}
if "cb_activated_at" not in cols:
conn.execute("ALTER TABLE assets ADD COLUMN cb_activated_at TEXT")
if "consecutive_losses" not in cols:
conn.execute("ALTER TABLE assets ADD COLUMN consecutive_losses INTEGER DEFAULT 0")
if "last_atr_regime" not in cols:
conn.execute("ALTER TABLE assets ADD COLUMN last_atr_regime TEXT")
conn.commit()