timestral-backtest-lab / lab /baselines.py
Segizu's picture
Timestral Backtest Lab (ZeroGPU)
756aa06 verified
Raw History Blame Contribute Delete
1.58 kB
"""Simple forecasting baselines for honest backtests."""
from __future__ import annotations
import numpy as np
def holdout_split(values: np.ndarray, holdout: int) -> tuple[np.ndarray, np.ndarray]:
"""Single chronological split: train = prefix, holdout = last N (no shuffle)."""
values = np.asarray(values, dtype=np.float64)
holdout = int(holdout)
if holdout < 1 or holdout >= len(values):
raise ValueError("holdout must be in [1, n_points).")
return values[:-holdout].copy(), values[-holdout:].copy()
def last_value_forecast(train: np.ndarray, horizon: int) -> np.ndarray:
"""Repeat the last observed training value for `horizon` steps."""
train = np.asarray(train, dtype=np.float64)
if train.size < 1:
raise ValueError("train is empty")
horizon = int(horizon)
return np.full(horizon, float(train[-1]), dtype=np.float64)
def seasonal_naive_forecast(train: np.ndarray, horizon: int, seasonality: int) -> np.ndarray:
"""Seasonal naive: yhat[t+h] = y[t+h - k*m] from the last full season in train.
Uses only training values (no holdout leakage). Requires len(train) >= seasonality.
"""
train = np.asarray(train, dtype=np.float64)
seasonality = int(seasonality)
horizon = int(horizon)
if seasonality < 1:
raise ValueError("seasonality must be >= 1")
if len(train) < seasonality:
raise ValueError("train must cover at least one seasonal period")
season = train[-seasonality:]
idx = np.arange(horizon) % seasonality
return season[idx].astype(np.float64, copy=True)