Coverage for evaluation/research_probes.py: 100%

43 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Research probes (V6.4.3): small cross-sectional models fitted in-process to measure what the dataset supports. They 

2are evaluation tools, never installed (no artifact is written to ml/). 

3 

4`load_research_frame` reads only the needed columns in chunks as float32 (the 254-column dataset is ~0.5 GB resident on 

5the 4 GB dev PC otherwise); `fit_ridge_rank` is a closed-form ridge on per-date ranked features; `fit_hgb_rank` wraps 

6sklearn's HistGradientBoostingRegressor (imported only when called). 

7""" 

8 

9from __future__ import annotations 

10 

11from pathlib import Path 

12from typing import TYPE_CHECKING, Any 

13 

14import numpy as np 

15import pandas as pd 

16 

17if TYPE_CHECKING: 

18 from collections.abc import Sequence 

19 

20KEY_COLUMNS = ("date", "ticker", "split") 

21 

22 

23def load_research_frame(dataset_path: str | Path, *, columns: Sequence[str], splits: Sequence[str] | None=None, chunksize: int = 40_000) -> pd.DataFrame: 

24 """The dataset's KEY_COLUMNS plus `columns` (numeric ones as float32), optionally only some splits.""" 

25 wanted = list(dict.fromkeys([*KEY_COLUMNS, *columns])) 

26 header = pd.read_csv(Path(dataset_path), nrows=0).columns 

27 usecols = [column for column in wanted if column in header] 

28 parts = [] 

29 for chunk in pd.read_csv(Path(dataset_path), usecols=usecols, chunksize=chunksize, low_memory=False): 

30 if splits is not None: 

31 chunk = chunk[chunk["split"].isin(list(splits))] 

32 numeric = [c for c in chunk.columns if c not in KEY_COLUMNS and pd.api.types.is_numeric_dtype(chunk[c])] 

33 chunk[numeric] = chunk[numeric].astype(np.float32) 

34 parts.append(chunk) 

35 frame = pd.concat(parts, ignore_index=True) if parts else pd.DataFrame(columns=usecols) 

36 frame["date"] = frame["date"].astype(str).str[:10] 

37 return frame 

38 

39 

40def fit_ridge_rank(x_train: np.ndarray, y_train: np.ndarray, *, alpha: float = 10.0, features: Sequence[str] | None=None) -> dict[str, Any]: 

41 """Ridge on centred targets: coef = (X'X + alpha I)^-1 X'(y - mean y). Rows with any NaN are dropped.""" 

42 x = np.asarray(x_train, dtype=np.float64) 

43 y = np.asarray(y_train, dtype=np.float64) 

44 keep = np.isfinite(x).all(axis=1) & np.isfinite(y) 

45 x, y = x[keep], y[keep] 

46 intercept = float(y.mean()) if len(y) else 0.0 

47 gram = x.T @ x + alpha * np.eye(x.shape[1]) 

48 coef = np.linalg.solve(gram, x.T @ (y - intercept)) if len(y) else np.zeros(x.shape[1]) 

49 return {"kind": "ridge", "coef": coef, "intercept": intercept, "alpha": float(alpha), "features": list(features or []), 

50 "rows": int(len(y))} 

51 

52 

53def fit_hgb_rank(x_train: np.ndarray, y_train: np.ndarray, **params: Any) -> Any: 

54 """Fit a histogram gradient-boosted regressor to the finite targets (sklearn, imported on call).""" 

55 from sklearn.ensemble import HistGradientBoostingRegressor 

56 

57 y = np.asarray(y_train, dtype=np.float64) 

58 keep = np.isfinite(y) 

59 model = HistGradientBoostingRegressor(**params) 

60 model.fit(np.asarray(x_train, dtype=np.float32)[keep], y[keep]) 

61 return model 

62 

63 

64def predict_scores(model: Any, x: np.ndarray) -> np.ndarray: 

65 """Scores for every row; a ridge row with a NaN feature scores NaN (the model has no view on it).""" 

66 x = np.asarray(x, dtype=np.float64) 

67 if isinstance(model, dict) and model.get("kind") == "ridge": 

68 scores = x @ model["coef"] + model["intercept"] 

69 scores[~np.isfinite(x).all(axis=1)] = np.nan 

70 return scores 

71 return np.asarray(model.predict(x.astype(np.float32)), dtype=np.float64)