Download code/macrolens/_fast.py from DeepAuto-AI/MacroLens: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/macrolens/_fast.py
- Command line
-
hf download hf://datasets/DeepAuto-AI/MacroLens/code/macrolens/_fast.py
-
curl -L -o _fast.py https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/macrolens/_fast.py
12.2 kB
| """Fast array-based data access for model training. | |
| Provides pre-materialized numpy arrays and PyTorch-compatible datasets | |
| that bypass the slow per-sample DataFrame slicing of WhatIfTSFDataset. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from typing import Any | |
| import numpy as np | |
| import pandas as pd | |
| from ._compat import config | |
| logger = logging.getLogger(__name__) | |
| # ── Feature catalogue ──────────────────────────────────────────────────── | |
| _FEATURE_GROUPS: dict[str, list[str]] = {} # lazily built | |
| def _build_feature_groups(granularity: str = "daily") -> dict[str, list[str]]: | |
| """Build feature group catalogue from the panel columns.""" | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| panel_path = bench_dir / "panel_train.parquet" | |
| if not panel_path.exists(): | |
| return {} | |
| # Read just the column names (no data) | |
| cols = pd.read_parquet(panel_path, columns=None).columns.tolist() # type: ignore[arg-type] | |
| groups: dict[str, list[str]] = { | |
| "price": [], | |
| "fundamentals": [], | |
| "macro": [], | |
| "derived": [], | |
| "other": [], | |
| } | |
| for c in cols: | |
| if c in ("ticker", "date", "label", "split", "sector", "industry", | |
| "nearest_filing_type", "nearest_filing_date", "nearest_filing_path"): | |
| continue | |
| if c in ("open", "high", "low", "close", "volume", "adj_close"): | |
| groups["price"].append(c) | |
| elif c.startswith("stmt_"): | |
| groups["fundamentals"].append(c) | |
| elif c.startswith(("fred_", "eia_")): | |
| groups["macro"].append(c) | |
| elif c.startswith("derived_"): | |
| groups["derived"].append(c) | |
| else: | |
| groups["other"].append(c) | |
| return {k: sorted(v) for k, v in groups.items() if v} | |
| def features(granularity: str = "daily", verbose: bool = True) -> dict[str, list[str]]: | |
| """List available features grouped by category. | |
| Parameters | |
| ---------- | |
| granularity : str | |
| ``"daily"`` (default). | |
| verbose : bool | |
| If True, print a summary table. | |
| Returns | |
| ------- | |
| dict[str, list[str]] | |
| Mapping of group name to feature column names. | |
| Example | |
| ------- | |
| >>> groups = macrolens.features() | |
| Feature groups (daily): | |
| price : 6 features [open, high, low, close, volume, adj_close] | |
| fundamentals : 22 features [stmt_revenue, stmt_net_income, ...] | |
| macro : 80 features [fred_DFF, fred_DGS10, ...] | |
| derived : 15 features [derived_market_cap, derived_pe, ...] | |
| Total: 123 features | |
| """ | |
| groups = _build_feature_groups(granularity) | |
| if verbose: | |
| total = sum(len(v) for v in groups.values()) | |
| print(f"\nFeature groups ({granularity}):") | |
| for name, cols in groups.items(): | |
| preview = cols[:3] | |
| more = f", ... +{len(cols)-3}" if len(cols) > 3 else "" | |
| print(f" {name:<16}: {len(cols):>3} features [{', '.join(preview)}{more}]") | |
| print(f" Total: {total} features\n") | |
| return groups | |
| # ── Fast numpy array materializer ───────────────────────────────────────── | |
| def to_arrays( | |
| split: str = "train", | |
| horizon: int = 21, | |
| lookback: int | None = None, | |
| granularity: str = "daily", | |
| target_col: str = "close", | |
| max_instances: int | None = None, | |
| feature_cols: list[str] | None = None, | |
| seed: int = 42, | |
| ) -> tuple[np.ndarray, np.ndarray, list[str]]: | |
| """Materialize benchmark data as numpy arrays for fast training. | |
| Pre-builds all sliding windows into contiguous arrays. Much faster | |
| than iterating ``WhatIfTSFDataset`` for model training. | |
| Parameters | |
| ---------- | |
| split : str | |
| ``"train"`` or ``"test"``. | |
| horizon : int | |
| Forecast horizon (default: 21). | |
| lookback : int, optional | |
| Lookback window (default: 63 for daily). | |
| granularity : str | |
| ``"daily"`` (default). | |
| target_col : str | |
| Target column (default: ``"close"``). | |
| max_instances : int, optional | |
| Subsample to this many instances (random). Default: all. | |
| feature_cols : list[str], optional | |
| Subset of feature columns. Default: all numeric columns. | |
| seed : int | |
| Random seed for subsampling. | |
| Returns | |
| ------- | |
| X : np.ndarray | |
| Shape ``(N, lookback, n_features)`` float32. | |
| y : np.ndarray | |
| Shape ``(N, horizon)`` float32. | |
| feature_names : list[str] | |
| Column names corresponding to X's last axis. | |
| Example | |
| ------- | |
| >>> X_train, y_train, features = macrolens.to_arrays("train", horizon=21) | |
| >>> X_train.shape | |
| (50000, 63, 103) | |
| >>> y_train.shape | |
| (50000, 21) | |
| >>> # For sklearn: | |
| >>> X_flat = X_train.reshape(len(X_train), -1) | |
| >>> model.fit(X_flat, y_train[:, -1]) | |
| """ | |
| if lookback is None: | |
| lookback = config.get_lookback_windows(granularity)[0] | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| panel_path = bench_dir / f"panel_{split}.parquet" | |
| if not panel_path.exists(): | |
| raise FileNotFoundError(f"Panel not found at {panel_path}.") | |
| logger.info("Loading panel %s...", panel_path) | |
| panel = pd.read_parquet(panel_path) | |
| panel["date"] = pd.to_datetime(panel["date"]) | |
| panel = panel.sort_values(["ticker", "date"]).reset_index(drop=True) | |
| # Determine feature columns | |
| exclude = {"ticker", "date", "label", "split", "sector", "industry", | |
| "nearest_filing_type", "nearest_filing_date", "nearest_filing_path"} | |
| if feature_cols is None: | |
| feature_cols = [ | |
| c for c in panel.columns | |
| if c not in exclude and panel[c].dtype.kind in "fiub" | |
| ] | |
| feat_names = sorted(feature_cols) | |
| if target_col not in panel.columns: | |
| raise ValueError(f"target_col={target_col!r} not in panel columns.") | |
| # Get target column index for extraction | |
| target_idx = panel.columns.get_loc(target_col) | |
| required_len = lookback + horizon | |
| feat_idx = [panel.columns.get_loc(c) for c in feat_names] | |
| n_features = len(feat_names) | |
| # ── Pass 1: count available windows per ticker ── | |
| ticker_info: list[tuple[str, int, int]] = [] # (ticker, group_start, n_windows) | |
| total_windows = 0 | |
| for ticker, grp in panel.groupby("ticker", sort=False): | |
| n = len(grp) | |
| if n < required_len: | |
| continue | |
| n_windows = n - required_len + 1 | |
| ticker_info.append((ticker, grp.index[0], n_windows)) | |
| total_windows += n_windows | |
| logger.info("Total available windows: %d across %d tickers", | |
| total_windows, len(ticker_info)) | |
| # ── Decide how many windows to take per ticker ── | |
| rng = np.random.RandomState(seed) | |
| budget = max_instances if max_instances is not None else total_windows | |
| if budget >= total_windows: | |
| # Take all windows | |
| per_ticker_take = {t: nw for t, _, nw in ticker_info} | |
| else: | |
| # Proportional sampling per ticker (at least 1 if selected) | |
| per_ticker_take: dict[str, int] = {} | |
| remaining = budget | |
| for t, _, nw in ticker_info: | |
| alloc = max(1, int(round(nw / total_windows * budget))) | |
| alloc = min(alloc, nw, remaining) | |
| if alloc > 0: | |
| per_ticker_take[t] = alloc | |
| remaining -= alloc | |
| if remaining <= 0: | |
| break | |
| # Distribute leftover budget | |
| if remaining > 0: | |
| for t, _, nw in ticker_info: | |
| if t not in per_ticker_take: | |
| continue | |
| extra = min(remaining, nw - per_ticker_take[t]) | |
| if extra > 0: | |
| per_ticker_take[t] += extra | |
| remaining -= extra | |
| if remaining <= 0: | |
| break | |
| actual_n = sum(per_ticker_take.values()) | |
| # ── Pass 2: pre-allocate and fill ── | |
| X = np.empty((actual_n, lookback, n_features), dtype=np.float32) | |
| y = np.empty((actual_n, horizon), dtype=np.float32) | |
| offset = 0 | |
| panel_vals = panel.values | |
| for ticker, grp_start, n_windows in ticker_info: | |
| take = per_ticker_take.get(ticker, 0) | |
| if take <= 0: | |
| continue | |
| # Slice this ticker's data from the panel (index is 0-based after reset_index) | |
| grp_len = n_windows + required_len - 1 | |
| vals = panel_vals[grp_start : grp_start + grp_len] | |
| feats = vals[:, feat_idx].astype(np.float32) | |
| targets = vals[:, target_idx].astype(np.float32) | |
| # Select which windows to extract | |
| if take >= n_windows: | |
| chosen = np.arange(n_windows) | |
| else: | |
| chosen = rng.choice(n_windows, take, replace=False) | |
| chosen.sort() | |
| # Extract windows for chosen starts | |
| for i, start in enumerate(chosen): | |
| X[offset + i] = feats[start : start + lookback] | |
| y[offset + i] = targets[start + lookback : start + required_len] | |
| offset += len(chosen) | |
| # Trim in case of rounding | |
| X = X[:offset] | |
| y = y[:offset] | |
| # Handle NaN | |
| np.nan_to_num(X, copy=False, nan=0.0) | |
| np.nan_to_num(y, copy=False, nan=0.0) | |
| logger.info("Built %d instances: X=%s, y=%s", len(X), X.shape, y.shape) | |
| return X, y, feat_names | |
| # ── PyTorch Dataset wrapper ─────────────────────────────────────────────── | |
| class TSFTorchDataset: | |
| """PyTorch-compatible dataset backed by pre-materialized numpy arrays. | |
| Works directly with ``torch.utils.data.DataLoader`` — no custom | |
| collate function needed. | |
| Parameters | |
| ---------- | |
| X : np.ndarray | |
| Shape ``(N, lookback, n_features)`` float32. | |
| y : np.ndarray | |
| Shape ``(N, horizon)`` float32. | |
| Example | |
| ------- | |
| >>> X, y, _ = macrolens.to_arrays("train", horizon=21, max_instances=50000) | |
| >>> ds = macrolens.TSFTorchDataset(X, y) | |
| >>> dl = DataLoader(ds, batch_size=256, shuffle=True, num_workers=4) | |
| >>> for x_batch, y_batch in dl: | |
| ... pred = model(x_batch) # (256, 63, 103) -> (256, 21) | |
| """ | |
| def __init__(self, X: np.ndarray, y: np.ndarray) -> None: | |
| self.X = X | |
| self.y = y | |
| def __len__(self) -> int: | |
| return len(self.X) | |
| def __getitem__(self, idx: int) -> tuple: | |
| import torch | |
| return ( | |
| torch.from_numpy(self.X[idx]), | |
| torch.from_numpy(self.y[idx]), | |
| ) | |
| def load_torch( | |
| split: str = "train", | |
| horizon: int = 21, | |
| lookback: int | None = None, | |
| granularity: str = "daily", | |
| target_col: str = "close", | |
| max_instances: int | None = None, | |
| **kwargs: Any, | |
| ) -> TSFTorchDataset: | |
| """Load a PyTorch-compatible TSF dataset for fast training. | |
| This materializes the data as numpy arrays, then wraps them in a | |
| ``TSFTorchDataset`` that returns ``(x_tensor, y_tensor)`` tuples | |
| compatible with ``torch.utils.data.DataLoader``. | |
| Parameters | |
| ---------- | |
| split : str | |
| ``"train"`` or ``"test"``. | |
| horizon : int | |
| Forecast horizon (default: 21). | |
| lookback : int, optional | |
| Lookback window (default: 63). | |
| max_instances : int, optional | |
| Subsample to this many instances. Recommended for prototyping. | |
| **kwargs | |
| Passed to :func:`to_arrays`. | |
| Returns | |
| ------- | |
| TSFTorchDataset | |
| PyTorch-compatible dataset. | |
| Example | |
| ------- | |
| >>> from torch.utils.data import DataLoader | |
| >>> ds = macrolens.load_torch("train", horizon=21, max_instances=50000) | |
| >>> dl = DataLoader(ds, batch_size=256, shuffle=True, num_workers=4) | |
| >>> for x, y in dl: | |
| ... print(x.shape, y.shape) # (256, 63, 103) (256, 21) | |
| ... break | |
| """ | |
| X, y, _ = to_arrays( | |
| split=split, | |
| horizon=horizon, | |
| lookback=lookback, | |
| granularity=granularity, | |
| target_col=target_col, | |
| max_instances=max_instances, | |
| **kwargs, | |
| ) | |
| return TSFTorchDataset(X, y) | |