"""LightGBM tuning fairness probe (Phase 2.5). Reviewer R1 (W1.5 / Q1.3) and R2 (W2.3) ask whether the headline finding "classical models lead long-horizon T1 forecasting" survives if LightGBM is tuned rather than run at library defaults. The canonical Table 6 LightGBM row remains at library defaults per the project's no-tuning rule (every method in the benchmark panel uses library defaults; see project memory `feedback_use_library_defaults.md`). This probe is **outside the panel** -- it is a one-time secondary analysis whose only purpose is to answer the reviewers' fairness question: does a modest hyperparameter sweep change the leaderboard? Design: a small 3 x 3 x 2 = 18-cell grid n_estimators ∈ {100, 500, 1000} max_depth ∈ {6, 10, 20} learning_rate ∈ {0.01, 0.1} All other LightGBM settings are kept at library defaults. The grid is run on T1 at the panel's headline T1 horizon (read from ``experiments.panel``). For every cell we save predictions under a distinct tag (so the probe never overwrites the canonical run) and record the primary T1 metric with cluster-bootstrap CIs. The summary report names the best cell, the default-config cell, and the relative delta -- this is what the camera-ready text quotes back when explaining the LightGBM-vs-LLM contrast. Per-launch authorisation: this is CPU-only and 18 fits on T1's full panel (~5M rows). Wall-clock estimate is several hours on the shared host; the user must authorise the launch. """ from __future__ import annotations import argparse import itertools import json import logging import pickle import time from dataclasses import asdict, dataclass from pathlib import Path from typing import Any import numpy as np logger = logging.getLogger(__name__) # Grid as specified by the plan; deliberately modest so the wall-clock # stays under one human-day on the shared CPU host. _GRID_N_ESTIMATORS: tuple[int, ...] = (100, 500, 1000) _GRID_MAX_DEPTH: tuple[int, ...] = (6, 10, 20) _GRID_LEARNING_RATE: tuple[float, ...] = (0.01, 0.1) @dataclass class _GridCell: n_estimators: int max_depth: int learning_rate: float seed: int horizon: int n_train: int n_test: int primary_metric: str value: float ci_lo: float ci_hi: float fit_sec: float predict_sec: float is_default: bool def _build_config( *, n_estimators: int, max_depth: int, learning_rate: float, ) -> Any: """Construct a ``LightGBMConfig`` with all other fields at defaults.""" from projects.agent_builder.scripts.whatif_bench.methods._config import ( LightGBMConfig, ) cfg = LightGBMConfig() cfg.n_estimators = n_estimators cfg.max_depth = max_depth cfg.learning_rate = learning_rate return cfg def _is_default_cell(n_estimators: int, max_depth: int, learning_rate: float) -> bool: from projects.agent_builder.scripts.whatif_bench.methods._config import ( LightGBMConfig, ) d = LightGBMConfig() # max_depth default is -1 (unlimited); the grid uses positive depths # only, so the default cell is never exactly reproduced by the grid. # Flag the conventional "closest to default" cell instead, which is # n=100, lr=0.1, max_depth=the largest grid value (closest proxy to # the unlimited default). return ( n_estimators == d.n_estimators and learning_rate == d.learning_rate and max_depth == max(_GRID_MAX_DEPTH) ) def _save_predictions( *, pred_dir: Path, method_id: str, task: str, seed: int, cell_tag: str, granularity: str, y_pred: Any, y_test: Any, meta_test: Any, ) -> Path: pred_dir.mkdir(parents=True, exist_ok=True) tag = f"{method_id}_{task}_seed{seed}_{cell_tag}" out_path = pred_dir / f"{tag}.pkl" tmp = out_path.with_suffix(".pkl.tmp") with open(tmp, "wb") as f: pickle.dump({ "method_id": method_id, "task": task, "seed": seed, "granularity": granularity, "cell_tag": cell_tag, "y_pred": y_pred, "y_test": y_test, "meta_test": meta_test, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"), }, f) tmp.replace(out_path) return out_path def run_grid( *, horizon: int | None = None, seed: int | None = None, granularity: str = "daily", pred_dir: Path | None = None, ) -> dict[str, Any]: """Sweep the 18-cell grid on T1 at the headline horizon. Returns a dict with one record per cell plus a flagged best cell. """ import macrolens as ml from projects.agent_builder.scripts.whatif_bench.experiments import panel # Match DRAFT.md (Fig. 3 caption): T1 ablation horizon is 252, not the # panel.ABLATION_T1_HORIZON=21 used for the analyst-rebalancing view. horizon = horizon if horizon is not None else 252 seed = seed if seed is not None else panel.PRIMARY_SEED pred_dir = pred_dir or Path(__file__).resolve().parents[1] / "predictions" train = ml.load("T1", "train", granularity=granularity, horizon=horizon) test = ml.load("T1", "test", granularity=granularity, horizon=horizon) cells: list[_GridCell] = [] for n_est, max_d, lr in itertools.product( _GRID_N_ESTIMATORS, _GRID_MAX_DEPTH, _GRID_LEARNING_RATE, ): cell_tag = f"grid_n{n_est}_d{max_d}_lr{lr:.3g}".replace(".", "p") logger.info("grid cell: n=%d depth=%d lr=%.3g (tag=%s)", n_est, max_d, lr, cell_tag) cfg = _build_config( n_estimators=n_est, max_depth=max_d, learning_rate=lr, ) model = ml.methods.LightGBMRegressor(task="T1", config=cfg) t0 = time.perf_counter() model.fit(train.X, train.y, seed=seed) fit_sec = time.perf_counter() - t0 t1 = time.perf_counter() y_pred = model.predict(test.X) predict_sec = time.perf_counter() - t1 _save_predictions( pred_dir=pred_dir, method_id="lightgbm_tuned", task="T1", seed=seed, cell_tag=cell_tag, granularity=granularity, y_pred=y_pred, y_test=test.y, meta_test=test.meta, ) cluster_keys = None if hasattr(test.meta, "columns") and "ticker" in test.meta.columns: cluster_keys = test.meta["ticker"].values metrics = ml.score( "T1", test.y, y_pred, cluster_keys=cluster_keys, resample="cluster", n_boot="adaptive", seed=seed, ) mv = metrics["mse"] value = float("nan") if mv.value is None else float(mv.value) ci_lo = float("nan") if mv.ci_lo is None else float(mv.ci_lo) ci_hi = float("nan") if mv.ci_hi is None else float(mv.ci_hi) cells.append(_GridCell( n_estimators=n_est, max_depth=max_d, learning_rate=lr, seed=seed, horizon=horizon, n_train=int(len(train.y)) if hasattr(train.y, "__len__") else -1, n_test=int(len(test.y)) if hasattr(test.y, "__len__") else -1, primary_metric="mse", value=value, ci_lo=ci_lo, ci_hi=ci_hi, fit_sec=fit_sec, predict_sec=predict_sec, is_default=_is_default_cell(n_est, max_d, lr), )) logger.info(" -> mse=%.4g [%.4g, %.4g]", value, ci_lo, ci_hi) # Identify the best (minimum) cell by primary metric. finite = [c for c in cells if np.isfinite(c.value)] best = min(finite, key=lambda c: c.value) if finite else None default = next((c for c in cells if c.is_default), None) delta = ( (default.value - best.value) / abs(default.value) if (best is not None and default is not None and default.value != 0) else None ) return { "probe": "lightgbm_tuned", "method_id": "lightgbm_tuned", "task": "T1", "granularity": granularity, "horizon": horizon, "seed": seed, "grid": { "n_estimators": list(_GRID_N_ESTIMATORS), "max_depth": list(_GRID_MAX_DEPTH), "learning_rate": list(_GRID_LEARNING_RATE), }, "best_cell": asdict(best) if best is not None else None, "default_proxy_cell": asdict(default) if default is not None else None, "relative_improvement_over_default": delta, "cells": [asdict(c) for c in cells], } def _default_probe_dir() -> Path: # Probe outputs live under experiments/ (experiment artifacts), # never under data_small_caps/ (raw + derived benchmark data). return Path(__file__).resolve().parents[1] / "probes_output" def main() -> int: parser = argparse.ArgumentParser( description="LightGBM tuning fairness probe (fairness check; NOT in panel).", ) parser.add_argument("--granularity", default="daily") parser.add_argument("--horizon", type=int, default=None, help="T1 horizon (default: 252, matching DRAFT.md Fig. 3 caption).") parser.add_argument("--seed", type=int, default=None, help="Seed (default: panel.PRIMARY_SEED).") parser.add_argument("--pred-dir", type=Path, default=None, help="Override the per-cell predictions directory.") parser.add_argument("--output", type=Path, default=None, help="Path to the summary JSON report.") args = parser.parse_args() logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", ) report = run_grid( horizon=args.horizon, seed=args.seed, granularity=args.granularity, pred_dir=args.pred_dir, ) out_path = args.output or _default_probe_dir() / "lightgbm_tuned.json" out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(report, indent=2, default=str)) logger.info("tuned-grid report written to %s", out_path) return 0 if __name__ == "__main__": raise SystemExit(main())