File size: 12,188 Bytes
ff4becd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""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)