Files
anorandClaude Opus 4.6 f66c13df84 feat: полный цикл тестирования RemizovNet + логирование
- data_v2.py: исправлен критический баг с лейблами (prices вместо returns)
- retest_all.py: ретест всех экспериментов с корректными данными
- retest_isolated.py: изолированные тесты астро/техн с временными лагами
- regime_analysis.py: анализ прибыльных/убыточных рыночных режимов
- shape_confirm_backtest.py: стратегия подтверждения формы + манименеджмент
- astro_trade_analysis.py: поиск астро-паттернов в прибыльных сделках
- final_backtest.py: финальный бэктест с астро-фильтрами + JSON логирование

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 03:30:48 +10:00

102 lines
3.1 KiB
Python

"""
Corrected data pipeline v2.
Key fix: direction labels ALWAYS computed from prices,
even when model inputs are log-returns.
"""
from __future__ import annotations
from datetime import date
import numpy as np
import yfinance as yf
def fetch_asset(ticker: str, period: str = "max") -> tuple[np.ndarray, list[date]]:
"""Fetch daily close prices and dates."""
hist = yf.Ticker(ticker).history(period=period)
prices = hist["Close"].dropna()
dates = [d.date() for d in prices.index]
vals = prices.values.astype(np.float64)
return vals, dates
def make_windows(
prices: np.ndarray,
dates: list[date],
window_size: int = 64,
shift: int = 7,
stride: int = 7,
use_returns: bool = False,
) -> dict:
"""Create windows with CORRECT direction labels.
Labels are ALWAYS based on price comparison:
label = 1 if prices[t-1+shift] > prices[t-1] else 0
Model inputs can be either raw prices or log-returns,
controlled by use_returns flag.
"""
n = len(prices)
W = window_size
# Compute log-returns if needed (for model input)
if use_returns:
values = np.diff(np.log(prices))
# Dates shift by 1 (returns[i] corresponds to dates[i+1])
val_dates = dates[1:]
# Need to map from value index back to price index:
# values[i] = log(prices[i+1]/prices[i]), so values index i
# corresponds to the transition from day i to day i+1.
# A window of values ending at index t covers transitions
# [t-W, t), meaning price days [t-W, t+1).
# The "current price" at decision point is prices[t] (in original indexing).
# Future price is prices[t + shift].
else:
values = prices
val_dates = dates
windows, targets, labels, win_dates = [], [], [], []
for t in range(W, len(values) - shift, stride):
w = values[t - W: t].copy()
s = values[t - W + shift: t + shift].copy()
# Normalize model input
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
# Direction label from PRICES (always correct)
if use_returns:
# values index t corresponds to price index t+1
# "now" = price at end of input window = prices[t]
# "future" = prices[t + shift]
price_idx_now = t # in original prices array
price_idx_future = t + shift
if price_idx_future >= len(prices):
continue
price_now = prices[price_idx_now]
price_future = prices[price_idx_future]
else:
price_now = prices[t - 1]
price_future = prices[t - 1 + shift]
if abs(price_future - price_now) < 1e-12:
continue
label = 1 if price_future > price_now else 0
windows.append((w - mu) / std)
targets.append((s - mu) / std)
labels.append(label)
win_dates.append(val_dates[t - 1])
return {
"windows": np.array(windows),
"targets": np.array(targets),
"labels": np.array(labels, dtype=np.int64),
"dates": win_dates,
}