Files
remizov-trader/src/remizov_trader/core/signals.py
T
anorandClaude Opus 4.6 a474b3eb32 feat: confidence filter ≥ 1.5, убрать DOT, exp21-22 эксперименты
- Confidence filter |corr| × amplitude/ATR ≥ 1.5 (exp22: Sharpe 0.92→1.43, DD 20%→10.8%)
- Убран DOT (убыточен), 6→5 активов, веса перераспределены
- OHLCV в dataset (exp21), 4 фазы exp22 (стопы, фильтрация, таймфрейм, комбинации)
- OHLCV helper в signals.py, dataset.py поддерживает OHLCV

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 01:05:42 +10:00

205 lines
6.5 KiB
Python

"""Signal generation — shape confirmation, direction detection, data prep."""
from __future__ import annotations
import logging
from datetime import datetime, timedelta, timezone
import numpy as np
from ..config import AssetConfig, ExchangeConfig, ModelConfig
log = logging.getLogger(__name__)
# Singleton exchange instance
_exchange = None
def _get_exchange(exchange_cfg: ExchangeConfig | None = None):
"""Get or create ccxt exchange instance."""
global _exchange
if _exchange is not None:
return _exchange
import ccxt
name = exchange_cfg.name if exchange_cfg else "bybit"
exchange_class = getattr(ccxt, name)
_exchange = exchange_class({"enableRateLimit": True})
log.info(f"Initialized {name} exchange for market data")
return _exchange
def _fetch_raw_ohlcv(symbol, interval, period, exchange_cfg):
"""Fetch raw OHLCV list from exchange. Returns list of [ts, O, H, L, C, V]."""
exchange = _get_exchange(exchange_cfg)
if period == "max":
days = 1000
else:
days = int(period.rstrip("d"))
since = int((datetime.now(timezone.utc) - timedelta(days=days)).timestamp() * 1000)
all_ohlcv = []
batch_size = 1000
now_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
prev_since = None
while since < now_ms:
try:
ohlcv = exchange.fetch_ohlcv(symbol, interval, since=since, limit=batch_size)
except Exception as e:
log.error(f"Failed to fetch {symbol} from {exchange.id}: {e}")
return None
if not ohlcv:
break
all_ohlcv.extend(ohlcv)
since = ohlcv[-1][0] + 1
if since == prev_since:
break
prev_since = since
return all_ohlcv or None
def fetch_prices_ccxt(symbol: str, interval: str = "1d", period: str = "max",
exchange_cfg: ExchangeConfig | None = None):
"""Fetch close prices and dates from exchange via ccxt (Bybit etc)."""
all_ohlcv = _fetch_raw_ohlcv(symbol, interval, period, exchange_cfg)
if not all_ohlcv:
return None, None
closes = np.array([c[4] for c in all_ohlcv], dtype=np.float64)
dates = [datetime.fromtimestamp(c[0] / 1000, tz=timezone.utc).date()
for c in all_ohlcv]
return closes, dates
def fetch_ohlcv_ccxt(symbol: str, interval: str = "1d", period: str = "max",
exchange_cfg: ExchangeConfig | None = None):
"""Fetch full OHLCV and dates. Returns (ohlcv_2d, dates).
ohlcv_2d shape: (N, 4) columns: [open, high, low, close]
"""
all_ohlcv = _fetch_raw_ohlcv(symbol, interval, period, exchange_cfg)
if not all_ohlcv:
return None, None
ohlcv = np.array([[c[1], c[2], c[3], c[4]] for c in all_ohlcv], dtype=np.float64)
dates = [datetime.fromtimestamp(c[0] / 1000, tz=timezone.utc).date()
for c in all_ohlcv]
return ohlcv, dates
def fetch_prices_yfinance(ticker: str, interval: str = "1d", period: str = "max"):
"""Fetch close prices and dates from yfinance.
Args:
ticker: yfinance ticker format, e.g. "BTC-USD"
interval: timeframe, e.g. "4h", "1d"
period: "max" or "730d" etc.
"""
import yfinance as yf
hist = yf.Ticker(ticker).history(period=period, interval=interval)
if hist.empty:
return None, None
close = hist["Close"].dropna().values.astype(np.float64)
dates = [d.date() if hasattr(d, "date") else d for d in hist["Close"].dropna().index]
return close, dates
def fetch_prices(symbol: str, interval: str = "1d", period: str = "max",
exchange_cfg: ExchangeConfig | None = None,
source: str = "exchange"):
"""Fetch close prices and dates.
Args:
symbol: ticker/symbol (format depends on source)
interval: timeframe
period: data period
exchange_cfg: exchange config (for ccxt source)
source: "exchange" (ccxt/Bybit) or "yfinance"
"""
if source == "yfinance":
return fetch_prices_yfinance(symbol, interval, period)
return fetch_prices_ccxt(symbol, interval, period, exchange_cfg)
def prepare_windows(prices: np.ndarray, window_size: int, shift: int) -> list[dict]:
"""Create normalized windows from price array."""
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({
"norm_input": (w - mu) / std,
"norm_target": (s - mu) / std,
"future_prices": future,
"mu": float(mu),
"std": float(std),
"price_idx": t,
})
return data
def check_shape_confirmation(pred_new: np.ndarray, confirm_prices: np.ndarray,
mu: float, std: float, K: int,
corr_thresh: float) -> tuple[float, bool]:
"""Check if predicted shape matches actual first K bars.
Returns (correlation, is_confirmed).
"""
pred_confirm = pred_new[:K]
if len(pred_confirm) < 2:
return 0.0, False
actual_norm = (confirm_prices[:K] - mu) / std
with np.errstate(invalid="ignore"):
corr = np.corrcoef(pred_confirm, actual_norm)[0, 1]
if np.isnan(corr):
return 0.0, False
return float(corr), corr >= corr_thresh
def get_direction(pred_new: np.ndarray, K: int) -> int | None:
"""Get predicted direction from the prediction array.
Returns 1 (long), -1 (short), or None if indeterminate.
"""
pred_direction = pred_new[-1] - pred_new[K - 1]
if abs(pred_direction) < 1e-10:
return None
return 1 if pred_direction > 0 else -1
def get_latest_signal_window(prices: np.ndarray, window_size: int, K: int):
"""Get window for checking current signal (ends K bars ago for confirmation).
Returns (norm_input, confirm_prices, mu, std, price_idx) or None.
"""
if len(prices) < window_size + K:
return None
w = prices[-(window_size + K):-K].copy()
confirm_prices = prices[-K:].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
return None
norm_input = (w - mu) / std
return {
"norm_input": norm_input,
"confirm_prices": confirm_prices,
"mu": float(mu),
"std": float(std),
"price_idx": len(prices) - 1,
"last_price": float(prices[-1]),
}