Files
remizov-trader/src/remizov_trader/config.py
T
anorandClaude Opus 4.6 6e37be51a9 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>
2026-03-12 22:36:43 +10:00

194 lines
6.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Configuration loader — single source of truth for all parameters."""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
import yaml
CONFIG_PATH = Path(__file__).parent.parent.parent / "config.yaml"
DATA_DIR = Path(__file__).parent.parent.parent / "data"
@dataclass
class AssetConfig:
ticker: str
symbol: str # ccxt format, e.g. "BTC/USDT"
K: int = 2
corr_thresh: float = 0.5
trailing_stop: bool = True
timeframe: str = "" # per-asset override; empty = use global
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
class ModelConfig:
window_size: int = 64
n_steps: int = 20
total_time: float = 0.5
shift: int = 7
epochs: int = 200
finetune_epochs: int = 50
lr: float = 0.003
@dataclass
class RiskConfig:
per_trade: float = 0.05
max_position_pct: float = 0.50
max_open_positions: int = 2
leverage: int = 1 # 1 = no leverage, 2-10 = spot margin
stop_scale: float = 1.0 # multiplier on ATR stop distance (0.5 = tighter)
time_exit: bool = True # close after shift-K bars; False = hold until stop
safety_stop_pct: float = 0.10 # exchange hard stop: 10% below entry
min_confidence: float = 0.0 # confidence filter: |corr| × amplitude/ATR (0 = off, 1.5 = exp22)
@dataclass
class CircuitBreakerConfig:
atr_ratio_on: float = 3.0
atr_ratio_off: float = 2.0
max_drawdown: float = 0.20
dd_reset: float = 0.10
dd_cooldown_hours: int = 48
@dataclass
class ExchangeConfig:
name: str = "bybit"
data_source: str = "exchange" # "exchange" (ccxt) or "yfinance"
api_key: str = ""
api_secret: str = ""
testnet: bool = True
@dataclass
class WebConfig:
host: str = "0.0.0.0"
port: int = 8080
@dataclass
class LLMConfig:
enabled: bool = False
base_url: str = "https://api.z.ai/api/anthropic"
api_key: str = ""
model: str = "glm-4.5-air"
sentiment_threshold: float = -0.3
@dataclass
class TelegramConfig:
enabled: bool = False
bot_token: str = ""
chat_id: str = ""
@dataclass
class Config:
mode: str = "paper"
initial_capital: float = 100.0
total_capital: float = 0.0 # actual total deposited; 0 = auto-compute
currency: str = "USDT"
timeframe: str = "1d"
check_time: str = "22:00"
assets: list[AssetConfig] = field(default_factory=list)
model: ModelConfig = field(default_factory=ModelConfig)
risk: RiskConfig = field(default_factory=RiskConfig)
circuit_breaker: CircuitBreakerConfig = field(default_factory=CircuitBreakerConfig)
exchange: ExchangeConfig = field(default_factory=ExchangeConfig)
web: WebConfig = field(default_factory=WebConfig)
telegram: TelegramConfig = field(default_factory=TelegramConfig)
llm: LLMConfig = field(default_factory=LLMConfig)
def model_for(self, asset: AssetConfig) -> ModelConfig:
"""Get ModelConfig with per-asset overrides."""
ws = asset.window_size or 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=shift,
epochs=epochs,
finetune_epochs=self.model.finetune_epochs,
lr=lr,
)
def leverage_for(self, asset: AssetConfig) -> int:
"""Get leverage: per-asset override or global."""
return asset.leverage or self.risk.leverage
def load_config(path: Path | None = None) -> Config:
"""Load configuration from YAML file + environment variables."""
path = path or CONFIG_PATH
if not path.exists():
return Config()
with open(path) as f:
raw = yaml.safe_load(f) or {}
assets_raw = raw.get("assets", [])
for a in assets_raw:
# Backward compat: binance_symbol → symbol
if "binance_symbol" in a and "symbol" not in a:
a["symbol"] = a.pop("binance_symbol")
assets = [AssetConfig(**a) for a in assets_raw]
model_raw = raw.get("model", {})
risk_raw = raw.get("risk", {})
cb_raw = raw.get("circuit_breaker", {})
exchange_raw = raw.get("exchange", {})
web_raw = raw.get("web", {})
tg_raw = raw.get("telegram", {})
capital_raw = raw.get("capital", {})
schedule_raw = raw.get("schedule", {})
exchange = ExchangeConfig(**exchange_raw)
# Override with env vars (secrets should not be in config file)
exchange.api_key = os.environ.get("REMIZOV_API_KEY", exchange.api_key)
exchange.api_secret = os.environ.get("REMIZOV_API_SECRET", exchange.api_secret)
telegram = TelegramConfig(**tg_raw)
telegram.bot_token = os.environ.get("REMIZOV_TG_TOKEN", telegram.bot_token)
llm_raw = raw.get("llm", {})
llm = LLMConfig(**llm_raw)
llm.api_key = os.environ.get("REMIZOV_LLM_TOKEN", llm.api_key)
return Config(
mode=raw.get("mode", "paper"),
initial_capital=capital_raw.get("initial", 100.0),
total_capital=capital_raw.get("total", 0.0),
currency=capital_raw.get("currency", "USDT"),
timeframe=schedule_raw.get("timeframe", "1d"),
check_time=schedule_raw.get("check_time", "22:00"),
assets=assets or [AssetConfig(ticker="BTC-USD", symbol="BTC/USDT")],
model=ModelConfig(**model_raw),
risk=RiskConfig(**risk_raw),
circuit_breaker=CircuitBreakerConfig(**cb_raw),
exchange=exchange,
web=WebConfig(**web_raw),
telegram=telegram,
llm=llm,
)