feat: прод на UNI/ATOM/NEAR — точные параметры из grid search
- config.yaml: 3 актива с per-asset shift, K, lr, stop_mult, stop_scale, cooldown - config.py: per-asset overrides (shift, epochs, lr, stop_mult, stop_scale, cooldown_bars, min_confidence, shape_confirm) - executor.py: per-asset stop_mult (вместо regime_adaptive), shape_confirm флаг, per-asset cooldown_bars, trailing stop порядок (check→trail) - cli.py: train на 30% данных (TRAIN_RATIO=0.3, как в тесте) - walk-forward: evaluate_wf.py + runner_wf.py - dashboard: WF таб с отдельными заголовками/pills/данными - runner.py: параллельный grid search (ProcessPoolExecutor, --workers) - evaluate.py: OHLCV стопы, OOS holdout, Sharpe sqrt(365) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -52,13 +52,16 @@ def init():
|
||||
|
||||
model_cfg = cfg.model_for(asset_cfg)
|
||||
data = signals.prepare_windows(prices, model_cfg.window_size, model_cfg.shift)
|
||||
click.echo(f" {len(prices)} bars, {len(data)} windows (ws={model_cfg.window_size})...", nl=False)
|
||||
# Train on first 30% of windows (matches autoresearch TRAIN_RATIO=0.3)
|
||||
n_train = max(int(len(data) * 0.3), 20)
|
||||
train_data = data[:n_train]
|
||||
click.echo(f" {len(prices)} bars, {len(data)} windows, train={n_train} (ws={model_cfg.window_size})...", nl=False)
|
||||
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(model_cfg)
|
||||
windows = np.array([d["norm_input"] for d in data])
|
||||
targets = np.array([d["norm_target"] for d in data])
|
||||
windows = np.array([d["norm_input"] for d in train_data])
|
||||
targets = np.array([d["norm_target"] for d in train_data])
|
||||
model_mod.train(mdl, windows, targets, model_cfg.epochs, model_cfg.lr)
|
||||
model_mod.save_model(mdl, ticker)
|
||||
|
||||
|
||||
@@ -23,6 +23,15 @@ class AssetConfig:
|
||||
window_size: int = 0 # per-asset override; 0 = use global model.window_size
|
||||
weight: float = 0.0 # portfolio weight (0 = equal allocation)
|
||||
leverage: int = 0 # per-asset leverage; 0 = use global risk.leverage
|
||||
# Per-asset model/risk overrides (0 = use global)
|
||||
shift: int = 0
|
||||
epochs: int = 0
|
||||
lr: float = 0.0
|
||||
stop_mult: float = 0.0 # fixed ATR multiplier; 0 = use regime_adaptive
|
||||
stop_scale: float = 0.0 # 0 = use global risk.stop_scale
|
||||
cooldown_bars: int = -1 # -1 = use shift as cooldown; >=0 = explicit
|
||||
min_confidence: float = -1.0 # -1 = use global; >=0 = per-asset override
|
||||
shape_confirm: bool = True # False = skip correlation check entirely
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -106,18 +115,22 @@ class Config:
|
||||
llm: LLMConfig = field(default_factory=LLMConfig)
|
||||
|
||||
def model_for(self, asset: AssetConfig) -> ModelConfig:
|
||||
"""Get ModelConfig with per-asset window_size override."""
|
||||
"""Get ModelConfig with per-asset overrides."""
|
||||
ws = asset.window_size or self.model.window_size
|
||||
if ws == self.model.window_size:
|
||||
shift = asset.shift or self.model.shift
|
||||
epochs = asset.epochs or self.model.epochs
|
||||
lr = asset.lr or self.model.lr
|
||||
if (ws == self.model.window_size and shift == self.model.shift
|
||||
and epochs == self.model.epochs and lr == self.model.lr):
|
||||
return self.model
|
||||
return ModelConfig(
|
||||
window_size=ws,
|
||||
n_steps=self.model.n_steps,
|
||||
total_time=self.model.total_time,
|
||||
shift=self.model.shift,
|
||||
epochs=self.model.epochs,
|
||||
shift=shift,
|
||||
epochs=epochs,
|
||||
finetune_epochs=self.model.finetune_epochs,
|
||||
lr=self.model.lr,
|
||||
lr=lr,
|
||||
)
|
||||
|
||||
def leverage_for(self, asset: AssetConfig) -> int:
|
||||
|
||||
@@ -243,17 +243,17 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
|
||||
from datetime import date as d
|
||||
days_held = (d.fromisoformat(last_date) - d.fromisoformat(entry_date)).days
|
||||
|
||||
# Update trailing stop
|
||||
if asset_cfg.trailing_stop:
|
||||
# Check stop FIRST (before trailing update, matches backtest)
|
||||
stopped = risk.is_stopped(last_price, stop_price, direction)
|
||||
|
||||
# Update trailing stop only if NOT stopped (matches backtest order)
|
||||
if not stopped and asset_cfg.trailing_stop:
|
||||
best_price, stop_price = risk.update_trailing_stop(
|
||||
last_price, best_price, stop_price, stop_dist, direction,
|
||||
)
|
||||
update_position(conn, pos["id"],
|
||||
best_price=best_price, stop_price=stop_price)
|
||||
|
||||
# Check stop
|
||||
stopped = risk.is_stopped(last_price, stop_price, direction)
|
||||
|
||||
# Check time exit (use per-asset model config) — can be disabled via config
|
||||
time_exit = False
|
||||
if cfg.risk.time_exit:
|
||||
@@ -330,23 +330,29 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
|
||||
|
||||
def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
"""Check for new trading signal. Returns log message or None."""
|
||||
# Cooldown after stop: skip `shift` candles to avoid re-entering same failed trade
|
||||
# Cooldown after stop
|
||||
last_stop = asset.get("last_stop_date")
|
||||
if last_stop:
|
||||
from datetime import date as d
|
||||
model_cfg = cfg.model_for(asset_cfg)
|
||||
days_since_stop = (d.fromisoformat(str(dates[-1])) - d.fromisoformat(last_stop)).days
|
||||
tf_str = asset_cfg.timeframe or cfg.timeframe
|
||||
tf_hours = int(tf_str.replace("h", ""))
|
||||
tf_hours = int(tf_str.replace("h", "").replace("d", "")) if "d" not in tf_str else 24
|
||||
candles_since_stop = days_since_stop * 24 // tf_hours
|
||||
if candles_since_stop < model_cfg.shift:
|
||||
return f"cooldown {candles_since_stop}/{model_cfg.shift} candles after stop — SKIP"
|
||||
# Per-asset cooldown_bars; -1 = use shift as cooldown
|
||||
cooldown = asset_cfg.cooldown_bars if asset_cfg.cooldown_bars >= 0 else model_cfg.shift
|
||||
if candles_since_stop < cooldown:
|
||||
return f"cooldown {candles_since_stop}/{cooldown} candles after stop — SKIP"
|
||||
|
||||
K_base = asset_cfg.K
|
||||
corr_thresh_base = asset_cfg.corr_thresh
|
||||
|
||||
# Regime adaptive: adjust K and stop_mult based on volatility
|
||||
K, stop_mult = risk.regime_adaptive_params(prices, len(prices) - 1, K_base)
|
||||
# Per-asset stop_mult: fixed value skips regime_adaptive
|
||||
if asset_cfg.stop_mult > 0:
|
||||
K = K_base
|
||||
stop_mult = asset_cfg.stop_mult
|
||||
else:
|
||||
K, stop_mult = risk.regime_adaptive_params(prices, len(prices) - 1, K_base)
|
||||
|
||||
# Adaptive corr threshold: adjust based on recent win rate
|
||||
corr_thresh = risk.adaptive_corr_threshold(
|
||||
@@ -368,7 +374,7 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
pred = model_mod.predict(mdl, sw["norm_input"])
|
||||
pred_new = pred[-model_cfg.shift:]
|
||||
|
||||
# Shape confirmation
|
||||
# Shape confirmation (can be disabled per-asset)
|
||||
corr, confirmed = signals.check_shape_confirmation(
|
||||
pred_new, sw["confirm_prices"], sw["mu"], sw["std"], K, corr_thresh,
|
||||
)
|
||||
@@ -376,24 +382,25 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
update_asset(conn, ticker,
|
||||
signals_since_retrain=asset["signals_since_retrain"] + 1)
|
||||
|
||||
if not confirmed:
|
||||
if asset_cfg.shape_confirm and not confirmed:
|
||||
log_signal(conn, ticker=ticker, date=str(dates[-1]),
|
||||
correlation=corr, action="skip_corr",
|
||||
details=f"thresh={corr_thresh:.2f} K={K}")
|
||||
return f"corr={corr:.3f} < {corr_thresh:.2f} (adaptive) K={K} — SKIP"
|
||||
|
||||
# Confidence filter: |corr| × (pred_amplitude / ATR) — exp22
|
||||
if cfg.risk.min_confidence > 0:
|
||||
# Confidence filter (per-asset override: -1 = use global)
|
||||
effective_min_conf = asset_cfg.min_confidence if asset_cfg.min_confidence >= 0 else cfg.risk.min_confidence
|
||||
if effective_min_conf > 0:
|
||||
atr = risk.compute_atr(prices, len(prices) - 1)
|
||||
if atr > 0:
|
||||
pred_denorm = pred_new * sw["std"] + sw["mu"]
|
||||
amplitude = float(np.max(pred_denorm) - np.min(pred_denorm))
|
||||
confidence = abs(corr) * (amplitude / atr)
|
||||
if confidence < cfg.risk.min_confidence:
|
||||
if confidence < effective_min_conf:
|
||||
log_signal(conn, ticker=ticker, date=str(dates[-1]),
|
||||
correlation=corr, action="skip_confidence",
|
||||
details=f"conf={confidence:.2f} < {cfg.risk.min_confidence}")
|
||||
return (f"confidence={confidence:.2f} < {cfg.risk.min_confidence} "
|
||||
details=f"conf={confidence:.2f} < {effective_min_conf}")
|
||||
return (f"confidence={confidence:.2f} < {effective_min_conf} "
|
||||
f"(corr={corr:.3f}, amp/atr={amplitude/atr:.2f}) — SKIP")
|
||||
|
||||
# Direction
|
||||
@@ -418,9 +425,10 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
|
||||
entry_price = sw["last_price"]
|
||||
|
||||
# Stop with regime-adaptive multiplier × stop_scale
|
||||
# Stop: ATR × stop_mult × stop_scale (per-asset or global)
|
||||
atr = risk.compute_atr(prices, len(prices) - 1)
|
||||
stop_dist = max(atr * stop_mult * cfg.risk.stop_scale, entry_price * 0.005)
|
||||
effective_stop_scale = asset_cfg.stop_scale if asset_cfg.stop_scale > 0 else cfg.risk.stop_scale
|
||||
stop_dist = max(atr * stop_mult * effective_stop_scale, entry_price * 0.005)
|
||||
stop_price = entry_price - direction * stop_dist
|
||||
|
||||
# Position sizing: weight-based with free balance check
|
||||
|
||||
Reference in New Issue
Block a user