""" Fetch BTC daily prices and prepare sliding-window datasets for RemizovNet. Window framing: g(x) = normalized price window [t, t+W) y(x) = normalized price window [t+shift, t+W+shift) RemizovNet learns the operator that maps g -> y, i.e. how a price pattern evolves over `shift` days. """ from __future__ import annotations import numpy as np import torch import yfinance as yf from torch import Tensor def fetch_btc_daily(period: str = "5y") -> np.ndarray: """Fetch BTC-USD daily close prices. Args: period: yfinance period string (e.g. "5y", "max"). Returns: 1D array of daily close prices. """ ticker = yf.Ticker("BTC-USD") hist = ticker.history(period=period) prices = hist["Close"].dropna().values.astype(np.float64) print(f"Fetched {len(prices)} daily BTC prices") return prices def make_windows( prices: np.ndarray, window_size: int = 64, shift: int = 7, stride: int = 7, normalize: str = "zscore", ) -> tuple[np.ndarray, np.ndarray]: """Create sliding-window input/output pairs. Args: prices: 1D array of prices. window_size: Number of points in each window. shift: How many days ahead the target window starts. stride: Step between consecutive windows (reduces overlap). normalize: "zscore" (zero-mean, unit-var per window) or "minmax". Returns: (g_windows, y_windows) — each shape (n_samples, window_size). """ n = len(prices) max_start = n - window_size - shift if max_start <= 0: raise ValueError(f"Not enough data: {n} prices, need > {window_size + shift}") g_list = [] y_list = [] for t in range(0, max_start, stride): g_raw = prices[t : t + window_size].copy() y_raw = prices[t + shift : t + shift + window_size].copy() if normalize == "zscore": # Normalize both windows using g's statistics (same reference frame) mu = g_raw.mean() std = g_raw.std() if std < 1e-10: continue g_norm = (g_raw - mu) / std y_norm = (y_raw - mu) / std elif normalize == "minmax": lo, hi = g_raw.min(), g_raw.max() if hi - lo < 1e-10: continue g_norm = (g_raw - lo) / (hi - lo) y_norm = (y_raw - lo) / (hi - lo) else: g_norm = g_raw y_norm = y_raw g_list.append(g_norm) y_list.append(y_norm) g_windows = np.array(g_list, dtype=np.float64) y_windows = np.array(y_list, dtype=np.float64) print(f"Created {len(g_windows)} window pairs (W={window_size}, shift={shift}, stride={stride})") return g_windows, y_windows def prepare_dataset( prices: np.ndarray, window_size: int = 64, shift: int = 7, train_ratio: float = 0.8, ) -> dict[str, Tensor]: """Full pipeline: windows -> train/test tensors. Returns: Dict with keys: g_train, y_train, g_test, y_test. """ g, y = make_windows(prices, window_size=window_size, shift=shift, stride=shift) # Chronological split (no data leakage) split_idx = int(len(g) * train_ratio) dataset = { "g_train": torch.tensor(g[:split_idx], dtype=torch.float32), "y_train": torch.tensor(y[:split_idx], dtype=torch.float32), "g_test": torch.tensor(g[split_idx:], dtype=torch.float32), "y_test": torch.tensor(y[split_idx:], dtype=torch.float32), } print(f"Train: {split_idx} samples, Test: {len(g) - split_idx} samples") return dataset