| """Sequence-family methods for the MacroLens unified API. |
| |
| Three classes — :class:`DLinear`, :class:`ITransformer`, :class:`ModernTCN` |
| — each implementing the sklearn-style :class:`~methods.base.Method` |
| contract. Coverage per the plan §9 matrix: |
| |
| | Class | name | family | tasks | |
| |-------------|----------------|------------|------------------| |
| | DLinear | "dlinear" | "sequence" | {"T1", "T4"} | |
| | ITransformer| "itransformer" | "sequence" | {"T1", "T4"} | |
| | ModernTCN | "moderntcn" | "sequence" | {"T1", "T4"} | |
| |
| T2 / T5 are dropped from the sequence family (plan §9 footnote): they |
| are point-in-time fundamentals snapshots, not time-series, so a 1-step |
| "lookback" hack adds no signal. T2/T5 deep-learning representation is |
| delegated to LLMs. |
| |
| Per-task input / output: |
| |
| * **T1** — Time-series forecasting. |
| ``X`` is ``np.ndarray`` shape ``(N, lookback, F)`` float32. ``y`` is |
| ``np.ndarray`` shape ``(N, horizon)`` float32 (close-price |
| trajectory). ``predict(X)`` returns ``(N, horizon)`` float32 — the |
| model emits the full horizon-length trajectory directly. |
| * **T4** — Scenario-return regression. |
| ``X`` is a ``pd.DataFrame`` with three columns: ``lookback`` (object |
| dtype, each cell is a ``(L, F)`` ndarray), ``event_type`` (str), and |
| ``event_description`` (str). ``y`` is ``np.ndarray`` shape ``(N,)`` |
| float32 — the realised ``actual_return_pct``. ``predict(X)`` returns |
| ``(N,)`` float32. |
| |
| Hard rules (enforced by ``tests/test_layer_isolation.py`` and |
| ``tests/test_method_contract.py``): |
| |
| * Zero IO. Zero eval imports. Zero ``meta`` consumption. Zero |
| subsampling. |
| * Imports point at ``methods._vendored.{tslib,moderntcn}``. |
| * Respects ``MACROLENS_DETERMINISTIC`` env var |
| (``torch.use_deterministic_algorithms(True)`` if set). |
| * The ``seed`` arg to ``fit`` seeds Python, numpy, and torch (CUDA too |
| when available). |
| * Persists state via :class:`~methods.base._TorchSaveMixin` |
| (``state.pt`` + ``manifest.json``) with model-shape ``aux`` so |
| :meth:`load` can rebuild the architecture before reading the |
| ``state_dict``. |
| |
| T4 specifics for v1: sequence models do not consume the ``event_type`` |
| or ``event_description`` text columns (they're vector-only models). |
| Future work — fold an event-type one-hot into the lookback channel |
| axis — is tracked in `methods/_vendored/CHANGES.md` future-work notes, |
| not implemented here. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| import os |
| import pathlib |
| import random |
| from types import SimpleNamespace |
| from typing import Any, ClassVar |
|
|
| import numpy as np |
| import pandas as pd |
| import torch |
| import torch.nn as nn |
| from torch.utils.data import DataLoader, TensorDataset |
|
|
| from ._config import ( |
| DLinearConfig, |
| ITransformerConfig, |
| ModernTCNConfig, |
| SequenceConfig, |
| ) |
| from ._registry import register |
| from ._vendored.moderntcn.models.ModernTCN import Model as ModernTCNOfficial |
| from ._vendored.tslib.models.DLinear import Model as DLinearOfficial |
| from ._vendored.tslib.models.iTransformer import Model as ITransformerOfficial |
| from .base import Method, _TorchSaveMixin |
|
|
|
|
| _SEQUENCE_TASKS = frozenset({"T1", "T4"}) |
|
|
|
|
| |
|
|
|
|
| def _ffill_impute_panel(X: np.ndarray) -> np.ndarray: |
| """Forward-fill NaN along the lookback (time) axis, then 0-fill any |
| remaining (timesteps before the first valid observation). |
| |
| Sequence models (DLinear / iTransformer / ModernTCN) propagate NaN |
| through their forward pass — softmax(NaN) = NaN, attention scores |
| blow up, etc. We therefore impute BEFORE the forward pass at both |
| fit and predict time. Per-ticker forward-fill within the lookback |
| window preserves the most recent observed value as the best |
| causal estimate; remaining leading-NaN cells go to 0. |
| |
| Parameters |
| ---------- |
| X |
| ``(N, L, F)`` float32 panel; may contain NaN / +/-inf. |
| |
| Returns |
| ------- |
| np.ndarray |
| Same shape, NaN- and inf-free. |
| """ |
| if X.size == 0 or not np.isnan(X).any() and not np.isinf(X).any(): |
| return X |
| |
| out = np.where(np.isfinite(X), X, np.nan).astype(np.float32, copy=True) |
| n, L, F = out.shape |
| |
| |
| |
| valid = ~np.isnan(out) |
| |
| idx = np.where(valid, np.arange(L)[None, :, None], -1) |
| last_valid = np.maximum.accumulate(idx, axis=1) |
| have_any = last_valid >= 0 |
| |
| n_idx = np.arange(n)[:, None, None] |
| f_idx = np.arange(F)[None, None, :] |
| safe_last = np.where(have_any, last_valid, 0) |
| gathered = out[n_idx, safe_last, f_idx] |
| out_ff = np.where(have_any, gathered, 0.0).astype(np.float32) |
| return out_ff |
|
|
|
|
| def _ffill_impute_2d(X: np.ndarray) -> np.ndarray: |
| """``_ffill_impute_panel`` for a single ``(L, F)`` cell. |
| |
| Used by T4 lookback stacking where every cell must be imputed before |
| being concatenated into ``(N, L, F)``. The 3-D path is the hot loop |
| so we keep this thin wrapper. |
| """ |
| return _ffill_impute_panel(X[None, :, :])[0] |
|
|
|
|
| |
|
|
|
|
| def _apply_seed(seed: int) -> None: |
| """Seed Python, numpy and torch (CPU + CUDA). Idempotent.""" |
| random.seed(seed) |
| np.random.seed(seed) |
| torch.manual_seed(seed) |
| if torch.cuda.is_available(): |
| torch.cuda.manual_seed_all(seed) |
| |
| |
| |
| |
| if torch.cuda.is_available(): |
| torch.backends.cudnn.enabled = False |
| if os.environ.get("MACROLENS_DETERMINISTIC", "") == "1": |
| |
| |
| |
| torch.use_deterministic_algorithms(True, warn_only=True) |
| torch.backends.cudnn.deterministic = True |
| torch.backends.cudnn.benchmark = False |
|
|
|
|
| |
|
|
|
|
| class _TSLibWrapper(nn.Module): |
| """Thin :class:`nn.Module` wrapping the official TSLib ``Model`` classes. |
| |
| TSLib expects a ``configs`` namespace and a forward signature of |
| ``forward(x_enc, x_mark_enc, x_dec, x_mark_dec)``; it returns |
| ``[B, pred_len, D]``. We expose ``forward(x: (B, L, F)) -> (B, pred_len)`` |
| by selecting the target variate at ``self.target_idx``. |
| """ |
|
|
| def __init__( |
| self, |
| model_cls: Any, |
| n_features: int, |
| seq_len: int, |
| pred_len: int, |
| target_idx: int, |
| **model_kwargs: Any, |
| ) -> None: |
| super().__init__() |
| self.target_idx = int(target_idx) |
| self.pred_len = int(pred_len) |
| cfg = SimpleNamespace( |
| task_name="long_term_forecast", |
| seq_len=seq_len, |
| pred_len=pred_len, |
| enc_in=n_features, |
| d_model=model_kwargs.get("d_model", 128), |
| n_heads=model_kwargs.get("n_heads", 4), |
| e_layers=model_kwargs.get("e_layers", 3), |
| d_ff=model_kwargs.get("d_ff", 256), |
| dropout=model_kwargs.get("dropout", 0.1), |
| factor=model_kwargs.get("factor", 1), |
| embed="timeF", |
| freq="h", |
| activation=model_kwargs.get("activation", "gelu"), |
| moving_avg=model_kwargs.get("moving_avg", 25), |
| ) |
| self.model = model_cls(cfg) |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| |
| out = self.model(x, None, None, None) |
| return out[:, :, self.target_idx] |
|
|
|
|
| class _ModernTCNWrapper(nn.Module): |
| """Thin :class:`nn.Module` wrapping the official ModernTCN ``Model``. |
| |
| ModernTCN consumes ``[B, L, D]`` and emits ``[B, pred_len, D]``; we |
| take the target variate to produce ``(B, pred_len)``. |
| """ |
|
|
| def __init__( |
| self, |
| n_features: int, |
| seq_len: int, |
| pred_len: int, |
| target_idx: int, |
| **model_kwargs: Any, |
| ) -> None: |
| super().__init__() |
| self.target_idx = int(target_idx) |
| self.pred_len = int(pred_len) |
|
|
| d_model = int(model_kwargs.get("d_model", 64)) |
| |
| |
| |
| default_dims = [d_model, d_model, d_model, d_model] |
| cfg = SimpleNamespace( |
| patch_size=int(model_kwargs.get("patch_size", 16)), |
| patch_stride=int(model_kwargs.get("patch_stride", 8)), |
| kernel_size=int(model_kwargs.get("kernel_size", 25)), |
| stem_ratio=int(model_kwargs.get("stem_ratio", 1)), |
| downsample_ratio=int(model_kwargs.get("downsample_ratio", 2)), |
| ffn_ratio=int(model_kwargs.get("ffn_ratio", 2)), |
| num_blocks=list(model_kwargs.get("num_blocks", [1])), |
| large_size=list(model_kwargs.get("large_size", [51])), |
| small_size=list(model_kwargs.get("small_size", [5])), |
| dims=list(model_kwargs.get("dims", default_dims)), |
| dw_dims=list(model_kwargs.get("dw_dims", default_dims)), |
| enc_in=n_features, |
| small_kernel_merged=False, |
| dropout=float(model_kwargs.get("dropout", 0.1)), |
| head_dropout=float(model_kwargs.get("head_dropout", 0.1)), |
| use_multi_scale=bool(model_kwargs.get("use_multi_scale", False)), |
| revin=bool(model_kwargs.get("revin", True)), |
| affine=bool(model_kwargs.get("affine", True)), |
| subtract_last=False, |
| freq="h", |
| seq_len=seq_len, |
| individual=False, |
| pred_len=pred_len, |
| decomposition=bool(model_kwargs.get("decomposition", False)), |
| ) |
| self.model = ModernTCNOfficial(cfg) |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| |
| out = self.model(x) |
| return out[:, :, self.target_idx] |
|
|
|
|
| |
|
|
|
|
| def _train_torch( |
| model: nn.Module, |
| X_train: np.ndarray, |
| y_train: np.ndarray, |
| *, |
| epochs: int, |
| batch_size: int, |
| lr: float, |
| weight_decay: float, |
| grad_clip: float, |
| patience: int, |
| device: str, |
| ) -> nn.Module: |
| """Train a torch model with 10%-holdout early stopping. |
| |
| AMP is enabled on CUDA, disabled on CPU. |
| """ |
| use_amp = device.startswith("cuda") |
| model = model.to(device) |
| n = len(X_train) |
| if n < 2: |
| return model |
|
|
| n_val = max(1, int(n * 0.1)) |
| perm = np.random.permutation(n) |
| val_idx = perm[:n_val] |
| train_idx = perm[n_val:] |
|
|
| X_t = torch.tensor(X_train[train_idx], dtype=torch.float32) |
| y_t = torch.tensor(y_train[train_idx], dtype=torch.float32) |
| X_v = torch.tensor(X_train[val_idx], dtype=torch.float32).to(device) |
| y_v = torch.tensor(y_train[val_idx], dtype=torch.float32).to(device) |
|
|
| train_loader = DataLoader( |
| TensorDataset(X_t, y_t), |
| batch_size=batch_size, |
| shuffle=True, |
| pin_memory=use_amp, |
| num_workers=0, |
| ) |
|
|
| optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay) |
| scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs) |
| criterion = nn.MSELoss() |
| scaler = torch.amp.GradScaler(device) if use_amp else None |
|
|
| best_val = float("inf") |
| best_state: dict[str, torch.Tensor] | None = None |
| wait = 0 |
|
|
| for _epoch in range(epochs): |
| model.train() |
| for xb, yb in train_loader: |
| xb = xb.to(device, non_blocking=True) |
| yb = yb.to(device, non_blocking=True) |
| optimizer.zero_grad(set_to_none=True) |
| if use_amp: |
| with torch.amp.autocast(device): |
| pred = model(xb) |
| loss = criterion(pred, yb) |
| scaler.scale(loss).backward() |
| scaler.unscale_(optimizer) |
| torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip) |
| scaler.step(optimizer) |
| scaler.update() |
| else: |
| pred = model(xb) |
| loss = criterion(pred, yb) |
| loss.backward() |
| torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip) |
| optimizer.step() |
|
|
| scheduler.step() |
|
|
| model.eval() |
| with torch.no_grad(): |
| if use_amp: |
| with torch.amp.autocast(device): |
| val_loss = criterion(model(X_v), y_v).item() |
| else: |
| val_loss = criterion(model(X_v), y_v).item() |
|
|
| if val_loss < best_val: |
| best_val = val_loss |
| best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} |
| wait = 0 |
| else: |
| wait += 1 |
| if wait >= patience: |
| break |
|
|
| if best_state is not None: |
| model.load_state_dict(best_state) |
| return model |
|
|
|
|
| |
|
|
|
|
| class _SequenceMethodBase(_TorchSaveMixin, Method): |
| """Shared fit / predict / save / load implementation. |
| |
| Concrete subclasses set: |
| |
| * ``name`` — registry id (``dlinear`` / ``itransformer`` / ``moderntcn``). |
| * ``family`` — ``"sequence"``. |
| * ``tasks`` — ``frozenset({"T1", "T4"})``. |
| * ``_config_class`` (set by ``@register``) — the concrete Pydantic config. |
| * ``_build_model(n_features, seq_len, pred_len, target_idx, model_kwargs)`` |
| — returns a ready-to-train ``nn.Module``. |
| """ |
|
|
| name: ClassVar[str] = "" |
| family: ClassVar[str] = "sequence" |
| tasks: ClassVar[frozenset[str]] = _SEQUENCE_TASKS |
| schema_version: ClassVar[int] = 1 |
|
|
| |
|
|
| def __init__( |
| self, |
| *, |
| task: str, |
| config: SequenceConfig | None = None, |
| device: str | None = None, |
| **kwargs: Any, |
| ) -> None: |
| if task not in self.tasks: |
| raise ValueError( |
| f"{type(self).__name__} does not support task {task!r}; " |
| f"supported = {sorted(self.tasks)}" |
| ) |
| self.task: str = task |
| if config is None: |
| config = self.default_config() |
| if kwargs: |
| |
| config = config.__class__(**{**config.model_dump(), **kwargs}) |
| elif kwargs: |
| raise ValueError( |
| "pass either `config=` or extra kwargs, not both." |
| ) |
| self.config: SequenceConfig = config |
| self.device: str = device or ("cuda" if torch.cuda.is_available() else "cpu") |
|
|
| |
| |
| self._model: nn.Module | None = None |
| self._aux: dict[str, Any] = {} |
| self._scaler: dict[str, np.ndarray | float] | None = None |
|
|
| |
|
|
| def _build_model( |
| self, |
| *, |
| n_features: int, |
| seq_len: int, |
| pred_len: int, |
| target_idx: int, |
| ) -> nn.Module: |
| raise NotImplementedError |
|
|
| |
|
|
| def fit(self, X: Any, y: Any, *, seed: int = 42) -> "_SequenceMethodBase": |
| _apply_seed(seed) |
| if self.task == "T1": |
| self._fit_t1(X, y) |
| elif self.task == "T4": |
| self._fit_t4(X, y) |
| else: |
| raise RuntimeError(f"unhandled task {self.task!r}") |
| return self |
|
|
| def predict(self, X: Any) -> np.ndarray: |
| if self._model is None: |
| raise RuntimeError( |
| f"{type(self).__name__}.predict called before fit(); " |
| f"call .fit(X, y) first." |
| ) |
| if self.task == "T1": |
| return self._predict_t1(X) |
| if self.task == "T4": |
| return self._predict_t4(X) |
| raise RuntimeError(f"unhandled task {self.task!r}") |
|
|
| |
|
|
| def _fit_t1(self, X: Any, y: Any) -> None: |
| """Train the sequence model on per-window log-returns. |
| |
| Same blow-up rationale as ``methods/classical.py:_fit_t1``: T1 |
| close prices span $0.50 to $5,000 across the small-cap universe, |
| so a global y z-score is dominated by high-price tickers and the |
| de-normalised output is unbounded. We instead target the |
| log-return relative to each window's last close:: |
| |
| c_i = X_i[-1, target_idx] |
| y_log[i, h] = log(y[i, h] / c_i) |
| |
| The neural net learns a dimensionless O(1) target. At predict time |
| we exponentiate and rescale by the test window's last close. |
| """ |
| X_arr = np.asarray(X, dtype=np.float32) |
| y_arr = np.asarray(y, dtype=np.float32) |
| if X_arr.ndim != 3: |
| raise ValueError(f"T1 X must be (N, L, F); got {X_arr.shape}") |
| if y_arr.ndim != 2: |
| raise ValueError(f"T1 y must be (N, horizon); got {y_arr.shape}") |
| if X_arr.shape[0] != y_arr.shape[0]: |
| raise ValueError( |
| f"T1 X/y row mismatch: X={X_arr.shape[0]}, y={y_arr.shape[0]}" |
| ) |
|
|
| |
| |
| |
| X_arr = _ffill_impute_panel(X_arr) |
|
|
| n, lookback, n_features = X_arr.shape |
| horizon = int(y_arr.shape[1]) |
| target_idx = int(self.config.target_idx) |
| if not 0 <= target_idx < n_features: |
| raise ValueError( |
| f"target_idx={target_idx} out of range for F={n_features}" |
| ) |
|
|
| |
| c = X_arr[:, -1, target_idx].astype(np.float64) |
| y_f = y_arr.astype(np.float64) |
| keep = ( |
| np.isfinite(c) & (c > 0.0) & |
| np.isfinite(y_f).all(axis=1) & (y_f > 0.0).all(axis=1) |
| ) |
| n_total = int(n) |
| n_keep = int(keep.sum()) |
| if n_keep < 1: |
| raise RuntimeError( |
| f"T1 fit: only {n_keep}/{n_total} training windows have " |
| "positive finite close + horizon prices; cannot fit " |
| "log-return target." |
| ) |
| X_arr = X_arr[keep] |
| c = c[keep] |
| y_log = np.log(y_f[keep] / c[:, None]).astype(np.float32) |
|
|
| |
| |
| feat_mean = X_arr.reshape(-1, n_features).mean(axis=0).astype(np.float32) |
| feat_std = (X_arr.reshape(-1, n_features).std(axis=0) + 1e-8).astype(np.float32) |
| X_n = (X_arr - feat_mean) / feat_std |
|
|
| model = self._build_model( |
| n_features=n_features, seq_len=lookback, |
| pred_len=horizon, target_idx=target_idx, |
| ) |
| model = _train_torch( |
| model, X_n, y_log, |
| epochs=self.config.epochs, batch_size=self.config.batch_size, |
| lr=self.config.learning_rate, weight_decay=self.config.weight_decay, |
| grad_clip=self.config.grad_clip, patience=self.config.patience, |
| device=self.device, |
| ) |
| self._model = model |
| |
| |
| |
| self._scaler = { |
| "feat_mean": feat_mean, "feat_std": feat_std, |
| "y_mean": 0.0, "y_std": 1.0, |
| "log_clip": 2.0, |
| "target_for": "log_return", |
| } |
| self._aux = { |
| "task": self.task, |
| "n_features": int(n_features), |
| "seq_len": int(lookback), |
| "pred_len": int(horizon), |
| "target_idx": int(target_idx), |
| } |
|
|
| def _predict_t1(self, X: Any) -> np.ndarray: |
| arr = np.asarray(X, dtype=np.float32) |
| if arr.ndim != 3: |
| raise ValueError(f"T1 predict expects (N, L, F); got {arr.shape}") |
| assert self._scaler is not None and self._model is not None |
| target_idx = int(self._aux.get("target_idx", 0)) |
| |
| |
| c_test = arr[:, -1, target_idx].astype(np.float64) |
| c_safe = np.where(np.isfinite(c_test) & (c_test > 0.0), c_test, np.nan) |
|
|
| arr_imp = _ffill_impute_panel(arr) |
| arr_n = (arr_imp - self._scaler["feat_mean"]) / self._scaler["feat_std"] |
|
|
| self._model.eval() |
| device = self.device |
| use_amp = device.startswith("cuda") |
| out_chunks: list[np.ndarray] = [] |
| bs = 1024 |
| with torch.no_grad(): |
| for i in range(0, arr_n.shape[0], bs): |
| batch = torch.tensor(arr_n[i : i + bs], dtype=torch.float32).to(device) |
| if use_amp: |
| with torch.amp.autocast(device): |
| p = self._model(batch).float().cpu().numpy() |
| else: |
| p = self._model(batch).cpu().numpy() |
| out_chunks.append(p) |
| log_pred = np.concatenate(out_chunks, axis=0).astype(np.float64) |
| |
| |
| if self._scaler.get("target_for") != "log_return": |
| preds = ( |
| log_pred * float(self._scaler.get("y_std", 1.0)) |
| + float(self._scaler.get("y_mean", 0.0)) |
| ) |
| return preds.astype(np.float32) |
|
|
| clip = float(self._scaler.get("log_clip", 2.0)) |
| log_pred = np.clip(log_pred, -clip, clip) |
| out = c_safe[:, None] * np.exp(log_pred) |
| bad = ~np.isfinite(out) |
| if bad.any(): |
| tile = np.broadcast_to(c_test[:, None], out.shape).astype(np.float64) |
| out = np.where(bad, tile, out) |
| |
| |
| |
| out = np.nan_to_num(out, nan=0.0, posinf=0.0, neginf=0.0) |
| return out.astype(np.float32) |
|
|
| |
|
|
| @staticmethod |
| def _stack_t4_lookback(X: pd.DataFrame) -> np.ndarray: |
| """Stack the ``lookback`` object column into a contiguous |
| ``(N, L, F)`` ndarray. Validates that every cell shares one shape. |
| """ |
| if not isinstance(X, pd.DataFrame): |
| raise TypeError(f"T4 X must be a DataFrame; got {type(X).__name__}") |
| if "lookback" not in X.columns: |
| raise ValueError("T4 X is missing the required 'lookback' column.") |
| cells = X["lookback"].tolist() |
| if not cells: |
| raise ValueError("T4 X has zero rows.") |
| first = np.asarray(cells[0], dtype=np.float32) |
| if first.ndim != 2: |
| raise ValueError( |
| f"T4 lookback cells must be 2D (L, F); got shape {first.shape}" |
| ) |
| out = np.empty((len(cells), first.shape[0], first.shape[1]), dtype=np.float32) |
| for i, c in enumerate(cells): |
| arr = np.asarray(c, dtype=np.float32) |
| if arr.shape != first.shape: |
| raise ValueError( |
| f"T4 lookback cell {i} shape {arr.shape} != first cell shape " |
| f"{first.shape}; all rows must share lookback length and " |
| "feature count." |
| ) |
| out[i] = arr |
| return out |
|
|
| def _fit_t4(self, X: Any, y: Any) -> None: |
| lb = self._stack_t4_lookback(X) |
| |
| |
| |
| |
| lb = _ffill_impute_panel(lb) |
| y_arr = np.asarray(y, dtype=np.float32) |
| if y_arr.ndim != 1: |
| raise ValueError(f"T4 y must be (N,); got {y_arr.shape}") |
| if lb.shape[0] != y_arr.shape[0]: |
| raise ValueError( |
| f"T4 X/y row mismatch: X={lb.shape[0]}, y={y_arr.shape[0]}" |
| ) |
|
|
| n, lookback, n_features = lb.shape |
| |
| |
| |
| target_idx = 0 |
|
|
| feat_mean = lb.reshape(-1, n_features).mean(axis=0).astype(np.float32) |
| feat_std = (lb.reshape(-1, n_features).std(axis=0) + 1e-8).astype(np.float32) |
| X_n = (lb - feat_mean) / feat_std |
|
|
| y_mean = float(y_arr.mean()) |
| y_std = float(y_arr.std() + 1e-8) |
| y_n = ((y_arr - y_mean) / y_std).reshape(-1, 1) |
|
|
| model = self._build_model( |
| n_features=n_features, seq_len=lookback, pred_len=1, |
| target_idx=target_idx, |
| ) |
| model = _train_torch( |
| model, X_n, y_n, |
| epochs=self.config.epochs, batch_size=self.config.batch_size, |
| lr=self.config.learning_rate, weight_decay=self.config.weight_decay, |
| grad_clip=self.config.grad_clip, patience=self.config.patience, |
| device=self.device, |
| ) |
| self._model = model |
| self._scaler = { |
| "feat_mean": feat_mean, "feat_std": feat_std, |
| "y_mean": y_mean, "y_std": y_std, |
| } |
| self._aux = { |
| "task": self.task, |
| "n_features": int(n_features), |
| "seq_len": int(lookback), |
| "pred_len": 1, |
| "target_idx": target_idx, |
| } |
|
|
| def _predict_t4(self, X: Any) -> np.ndarray: |
| lb = self._stack_t4_lookback(X) |
| |
| lb = _ffill_impute_panel(lb) |
| assert self._scaler is not None and self._model is not None |
| if lb.shape[2] != self._aux.get("n_features"): |
| raise ValueError( |
| f"T4 predict feature count {lb.shape[2]} != train " |
| f"{self._aux.get('n_features')}; loader contract violation." |
| ) |
| X_n = (lb - self._scaler["feat_mean"]) / self._scaler["feat_std"] |
|
|
| self._model.eval() |
| device = self.device |
| use_amp = device.startswith("cuda") |
| out_chunks: list[np.ndarray] = [] |
| bs = 1024 |
| with torch.no_grad(): |
| for i in range(0, X_n.shape[0], bs): |
| batch = torch.tensor(X_n[i : i + bs], dtype=torch.float32).to(device) |
| if use_amp: |
| with torch.amp.autocast(device): |
| p = self._model(batch).float().cpu().numpy() |
| else: |
| p = self._model(batch).cpu().numpy() |
| out_chunks.append(p) |
| preds_n = np.concatenate(out_chunks, axis=0) |
| preds = preds_n.reshape(-1) * self._scaler["y_std"] + self._scaler["y_mean"] |
| |
| |
| |
| preds = np.where(np.isfinite(preds), preds, float(self._scaler["y_mean"])) |
| return preds.astype(np.float32) |
|
|
| |
|
|
| @classmethod |
| def default_config(cls) -> SequenceConfig: |
| |
| |
| |
| return SequenceConfig() |
|
|
| |
|
|
| @classmethod |
| def load(cls, path: pathlib.Path) -> "_SequenceMethodBase": |
| path = pathlib.Path(path) |
| manifest = Method._check_manifest(path, cls.name, cls.schema_version) |
| payload = torch.load(path / "state.pt", weights_only=False) |
|
|
| cfg_cls = cls._config_class |
| config = cfg_cls(**payload["config"]) |
| instance = cls(task=payload["task"], config=config) |
|
|
| aux = payload.get("aux", {}) or {} |
| if not aux: |
| |
| return instance |
|
|
| instance._aux = dict(aux) |
| instance._model = instance._build_model( |
| n_features=int(aux["n_features"]), |
| seq_len=int(aux["seq_len"]), |
| pred_len=int(aux["pred_len"]), |
| target_idx=int(aux["target_idx"]), |
| ) |
| instance._model.load_state_dict(payload["state_dict"]) |
| instance._model.to(instance.device) |
|
|
| scaler_path = path / "scaler.joblib" |
| if scaler_path.exists(): |
| import joblib |
| instance._scaler = joblib.load(scaler_path) |
| return instance |
|
|
|
|
| |
|
|
|
|
| @register( |
| name="dlinear", family="sequence", |
| tasks=_SEQUENCE_TASKS, config_class=DLinearConfig, |
| ) |
| class DLinear(_SequenceMethodBase): |
| """DLinear — Zeng et al., AAAI 2023 (TSLib official source). |
| |
| Predicts a horizon-length close-price trajectory for T1; a single |
| scalar return percentage for T4. |
| """ |
|
|
| @classmethod |
| def default_config(cls) -> DLinearConfig: |
| return DLinearConfig() |
|
|
| def _build_model( |
| self, |
| *, |
| n_features: int, |
| seq_len: int, |
| pred_len: int, |
| target_idx: int, |
| ) -> nn.Module: |
| cfg: DLinearConfig = self.config |
| return _TSLibWrapper( |
| DLinearOfficial, |
| n_features=n_features, |
| seq_len=seq_len, |
| pred_len=pred_len, |
| target_idx=target_idx, |
| moving_avg=cfg.moving_avg, |
| ) |
|
|
|
|
| @register( |
| name="itransformer", family="sequence", |
| tasks=_SEQUENCE_TASKS, config_class=ITransformerConfig, |
| ) |
| class ITransformer(_SequenceMethodBase): |
| """iTransformer — Liu et al., ICLR 2024 (TSLib official source). |
| |
| Predicts a horizon-length close-price trajectory for T1; a single |
| scalar return percentage for T4. |
| """ |
|
|
| @classmethod |
| def default_config(cls) -> ITransformerConfig: |
| return ITransformerConfig() |
|
|
| def _build_model( |
| self, |
| *, |
| n_features: int, |
| seq_len: int, |
| pred_len: int, |
| target_idx: int, |
| ) -> nn.Module: |
| cfg: ITransformerConfig = self.config |
| return _TSLibWrapper( |
| ITransformerOfficial, |
| n_features=n_features, |
| seq_len=seq_len, |
| pred_len=pred_len, |
| target_idx=target_idx, |
| d_model=cfg.d_model, |
| n_heads=cfg.n_heads, |
| e_layers=cfg.e_layers, |
| d_ff=cfg.d_ff, |
| dropout=cfg.dropout, |
| factor=cfg.factor, |
| activation=cfg.activation, |
| ) |
|
|
|
|
| @register( |
| name="moderntcn", family="sequence", |
| tasks=_SEQUENCE_TASKS, config_class=ModernTCNConfig, |
| ) |
| class ModernTCN(_SequenceMethodBase): |
| """ModernTCN — Luo & Wang, ICLR 2024 (ModernTCN official source). |
| |
| Predicts a horizon-length close-price trajectory for T1; a single |
| scalar return percentage for T4. |
| """ |
|
|
| @classmethod |
| def default_config(cls) -> ModernTCNConfig: |
| return ModernTCNConfig() |
|
|
| def _build_model( |
| self, |
| *, |
| n_features: int, |
| seq_len: int, |
| pred_len: int, |
| target_idx: int, |
| ) -> nn.Module: |
| cfg: ModernTCNConfig = self.config |
| return _ModernTCNWrapper( |
| n_features=n_features, |
| seq_len=seq_len, |
| pred_len=pred_len, |
| target_idx=target_idx, |
| patch_size=cfg.patch_size, |
| patch_stride=cfg.patch_stride, |
| d_model=cfg.d_model, |
| kernel_size=cfg.kernel_size, |
| stem_ratio=cfg.stem_ratio, |
| downsample_ratio=cfg.downsample_ratio, |
| ffn_ratio=cfg.ffn_ratio, |
| num_blocks=list(cfg.num_blocks), |
| large_size=list(cfg.large_size), |
| small_size=list(cfg.small_size), |
| dropout=cfg.dropout, |
| head_dropout=cfg.head_dropout, |
| revin=cfg.revin, |
| affine=cfg.affine, |
| ) |
|
|
|
|
| __all__ = ["DLinear", "ITransformer", "ModernTCN"] |
|
|