"""Shrunk mean-variance and residual books from a network, tree and ridge ensemble on
characteristics and daily-return path features. JKP Common Task Framework submission.

Interface: main(chars, features, daily_ret) -> DataFrame with columns id, eom, w.

METHOD (every quantity used for month t is available at the month-end t)

  Risk      Each month a statistical factor model is estimated from trailing daily returns
            (252 days, and 756 days with Ledoit-Wolf shrinkage); factors are the principal
            components of the correlation matrix above the Marchenko-Pastur edge.
  Target    Next month's excess return divided by the stock's volatility (average of the 21-, 63-
            and 252-day variances), residualised by GLS on a constraint set, standardised and
            clipped at 4. Five constraint sets give five targets: return factors plus two-digit
            SIC industries (252 and 756 day models), return factors plus the principal components
            of the ranked characteristics, both together, and industries only. The network
            learns all five jointly; the portfolio uses the 756-day one.
  Features  Within-month ranks of the supplied characteristics, and features generated on a
            fixed grid from the daily return file: cumulative raw and factor-residual returns
            over nine horizons up to a month, older residual legs, extremes, volatility term
            structure and persistence, and leave-one-out averages of the same signals over
            five peer sets (SIC2, SIC3, SIC4, nearest neighbours in characteristic space,
            nearest neighbours in residual-return correlation) with own-minus-peer spreads.
            A third group measures how recently each stock's slow-moving characteristics
            changed.
  Learners  A multi-task feed-forward network (one output per target) written in NumPy, an
            ensemble over seeds; LightGBM on the raw characteristics plus the daily features;
            ridge regression with exponential forgetting refit monthly. All are refit on an
            expanding window, the network and the trees annually. Epochs and boosting rounds
            are chosen on the most recent months of each window, which are then returned to
            the training set. The scores are averaged as within-month z-scores with weights
            2 : 2 : 1 (network : trees : ridge).
  Books     A Ledoit-Wolf mean-variance book and a factor-neutral residual book of the ensemble
            score, each at unit predicted risk with positions capped at twice the median. The
            two are blended monthly with long-only shrunk maximum-Sharpe coefficients from their
            own realised returns, and scaled by a leverage rule based on the realised daily
            volatility of the books held before.

All choices were fixed on the pre-1990 sample (walk-forward 1965-1989); the test period was
not used to choose features, hyper-parameters, portfolio rules or blend weights. Runs on CPU.

ATTRIBUTION

  The residual target and the unit-risk residual book follow "Residual Books (LightGBM)"
  by Felix Gehling (2026), published on the CTF leaderboard. The Ledoit-Wolf mean-variance
  book with a ridge, the 756-day shrunk risk model and the leverage rule based on the
  realised daily volatility of held books follow "Residual Signal, Diversified Books" by
  Abhinav Keshri (2026). The short-horizon daily path features, characteristic-space peers
  and the idea of bounding individual positions follow the "Topology-Informed Decomposition
  Ensemble" by Hema Srikar Ankem (2026). References: Gu, Kelly and Xiu (2020); Marchenko and
  Pastur (1967); Ledoit and Wolf (2004); Corsi (2009); Moreira and Muir (2017).
"""
from __future__ import annotations

import os
import time
import warnings

import numpy as np
import pandas as pd


# ==================================================================================================
# ctf_core
# Core building blocks for the CTF model: panel preparation, daily return matrix,
# statistical risk models, residual targets, daily-path features and residual books.
#
# Everything here is strictly causal: any quantity attached to month t uses daily
# returns dated on or before the month-end t and characteristics observed at t. The
# only forward-looking array is the label (built from ret_exc_lead1m), and learners
# may only train on labels of months strictly before the month being predicted.
# ==================================================================================================

TARGET = "ret_exc_lead1m"
DAYS_PER_MONTH = 21.0
PSI_FLOOR = 0.05
LABEL_CLIP = 4.0
MIN_INDUSTRY = 10

_T0 = time.perf_counter()


def log(msg: str) -> None:
    print(f"[{(time.perf_counter() - _T0) / 60.0:7.1f}m] {msg}", flush=True)


# --------------------------------------------------------------------------------------
# Input normalisation
# --------------------------------------------------------------------------------------

def to_days(values) -> np.ndarray:
    """Dates of any common representation -> int64 days since 1970-01-01."""
    arr = values.to_numpy() if hasattr(values, "to_numpy") else np.asarray(values)
    if np.issubdtype(arr.dtype, np.datetime64):
        return arr.astype("datetime64[D]").astype(np.int64)
    if np.issubdtype(arr.dtype, np.integer):
        return arr.astype(np.int64)
    return pd.to_datetime(pd.Series(arr)).to_numpy().astype("datetime64[D]").astype(np.int64)


def to_int_ids(values) -> np.ndarray:
    arr = values.to_numpy() if hasattr(values, "to_numpy") else np.asarray(values)
    if np.issubdtype(arr.dtype, np.integer):
        return arr.astype(np.int64)
    f = pd.to_numeric(pd.Series(arr), errors="coerce").to_numpy(np.float64)
    if not np.isfinite(f).all():
        raise ValueError("non-numeric security identifiers")
    return np.rint(f).astype(np.int64)


def to_bool(values) -> np.ndarray:
    """ctff_test may arrive as bool, 0/1 numbers or '0'/'1'/'true'/'false' strings."""
    arr = values.to_numpy() if hasattr(values, "to_numpy") else np.asarray(values)
    if arr.dtype == np.bool_:
        return arr.copy()
    if np.issubdtype(arr.dtype, np.number):
        return np.nan_to_num(arr.astype(np.float64), nan=0.0) != 0.0
    s = pd.Series(arr).astype(str).str.strip().str.lower()
    return s.isin(["1", "1.0", "true", "t", "yes", "y"]).to_numpy()


def to_float(values, dtype=np.float64) -> np.ndarray:
    arr = values.to_numpy() if hasattr(values, "to_numpy") else np.asarray(values)
    if np.issubdtype(arr.dtype, np.floating) or np.issubdtype(arr.dtype, np.integer):
        return arr.astype(dtype)
    return pd.to_numeric(pd.Series(arr), errors="coerce").to_numpy(dtype)


# --------------------------------------------------------------------------------------
# Panel
# --------------------------------------------------------------------------------------

def prepare_panel(chars, features) -> dict:
    """Sort the panel by (month, id) and expose it as flat arrays.

    `chars` only needs `.columns` and `chars[name]` returning a 1-d array-like, so the
    same code serves a pandas DataFrame and a lazily loaded column store.
    """
    cols = set(str(c) for c in chars.columns)
    feat_col = features["features"] if "features" in getattr(features, "columns", []) else features.iloc[:, 0]
    feats = sorted({str(f) for f in list(feat_col)} & cols)      # canonical order: input order must not matter
    if not feats:
        raise ValueError("no feature named in `features` is present in `chars`")

    day = to_days(chars["eom"])
    ids = to_int_ids(chars["id"])
    order = np.lexsort((ids, day))
    day, ids = day[order], ids[order]
    n = len(day)

    months, mon = np.unique(day, return_inverse=True)
    starts = np.searchsorted(mon, np.arange(len(months) + 1))

    ret = to_float(chars[TARGET])[order] if TARGET in cols else np.full(n, np.nan)
    test = to_bool(chars["ctff_test"])[order] if "ctff_test" in cols else np.zeros(n, bool)
    if "sic" in cols:
        sic = to_float(chars["sic"])[order]
        sic = np.where(np.isfinite(sic), sic, -1.0)
    else:
        sic = np.full(n, -1.0)
    sic = sic.astype(np.int64)

    X = np.empty((n, len(feats)), np.float32)
    for j, f in enumerate(feats):
        X[:, j] = to_float(chars[f], np.float32)[order]
    X[~np.isfinite(X)] = np.nan

    return dict(
        feats=feats, X=X, day=day, mon=mon.astype(np.int32), months=months, starts=starts,
        ids=ids, ret=ret, test=test, order=order, n=n,
        sic2=np.where(sic >= 0, sic // 100, -1), sic3=np.where(sic >= 0, sic // 10, -1),
        sic4=sic,
    )


def rank_panel(X: np.ndarray, mon: np.ndarray, block: int = 40) -> np.ndarray:
    """Within-month average percentile rank, centred on zero; missing -> 0."""
    out = np.empty(X.shape, np.float32)
    key = pd.Series(mon)
    for i in range(0, X.shape[1], block):
        blk = pd.DataFrame(X[:, i:i + block].astype(np.float64))
        r = blk.groupby(key.to_numpy(), sort=False).rank(method="average", pct=True) - 0.5
        out[:, i:i + block] = np.nan_to_num(r.to_numpy(np.float32), nan=0.0)
    return out


def rank_columns(V: np.ndarray, mon: np.ndarray) -> np.ndarray:
    """Same transform for a (rows, k) block of derived features (float64 in, float32 out)."""
    r = pd.DataFrame(V).groupby(mon, sort=False).rank(method="average", pct=True) - 0.5
    return np.nan_to_num(r.to_numpy(np.float32), nan=0.0)


# --------------------------------------------------------------------------------------
# Daily returns
# --------------------------------------------------------------------------------------

def daily_arrays(daily_ret) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    low = {str(c).lower(): c for c in daily_ret.columns}
    return (to_int_ids(daily_ret[low["id"]]), to_days(daily_ret[low["date"]]),
            to_float(daily_ret[low["ret_exc"]], np.float32))


def build_daily(did: np.ndarray, dday: np.ndarray, dret: np.ndarray, uid: np.ndarray,
                min_day: int) -> tuple[np.ndarray, np.ndarray]:
    """Dense (trading days x ids) float32 matrix of daily excess returns, NaN = missing."""
    col = np.minimum(np.searchsorted(uid, did), len(uid) - 1)
    keep = (uid[col] == did) & (dday >= min_day) & np.isfinite(dret)
    col, dd, rr = col[keep], dday[keep], dret[keep]
    days, row = np.unique(dd, return_inverse=True)
    M = np.full((len(days), len(uid)), np.nan, np.float32)
    M[row, col] = rr
    return days, M


# --------------------------------------------------------------------------------------
# Linear algebra helpers
# --------------------------------------------------------------------------------------

def mp_edge(p: int, n: int) -> float:
    """Upper Marchenko-Pastur edge for a p-variable correlation matrix from n observations."""
    return (1.0 + np.sqrt(p / n)) ** 2


def gls_basis(G: np.ndarray, psi: np.ndarray) -> np.ndarray:
    """Orthonormal basis U of the column space of Psi^{-1/2} G (rank-revealing)."""
    U, s, _ = np.linalg.svd(G / np.sqrt(psi)[:, None], full_matrices=False)
    return U[:, s > 1e-10 * s.max()] if s.size else U


def industry_dummies(codes: np.ndarray, min_count: int = MIN_INDUSTRY) -> np.ndarray:
    """Indicator columns; industries with fewer than `min_count` names and missing codes pool."""
    uniq, inv, cnt = np.unique(codes, return_inverse=True, return_counts=True)
    keep = (cnt >= min_count) & (uniq >= 0)
    group = np.where(keep[inv], inv, -1)
    labels = np.unique(group)
    return (group[:, None] == labels[None, :]).astype(np.float64)


def group_mean(values: np.ndarray, codes: np.ndarray, min_count: int = 3) -> np.ndarray:
    """Mean of `values` (n, k) within each code, NaN-aware; small groups -> NaN."""
    _, inv = np.unique(codes, return_inverse=True)
    ng = inv.max() + 1 if inv.size else 0
    fin = np.isfinite(values)
    out = np.full(values.shape, np.nan)
    for j in range(values.shape[1]):
        f = fin[:, j]
        s = np.bincount(inv[f], weights=values[f, j], minlength=ng)
        c = np.bincount(inv[f], minlength=ng)
        m = np.where(c >= min_count, s / np.maximum(c, 1), np.nan)
        out[:, j] = m[inv]
    out[codes < 0] = np.nan
    return out


# --------------------------------------------------------------------------------------
# Statistical risk model
# --------------------------------------------------------------------------------------

def pca_risk(R: np.ndarray, min_obs: int, shrink: bool = False):
    """Marchenko-Pastur PCA factor model of a (T, n) window of daily returns (NaN = missing).

    Returns
      ok     (n,) eligibility mask
      B      (n_ok, k) loadings in correlation units
      psi    (n_ok,) specific variance share, floored
      sigma  (n_ok,) monthly volatility
      Xn     (T, n_ok) demeaned unit-norm returns (missing = 0)
      V      (T, k) factor realisations (orthonormal)
    """
    obs = np.isfinite(R)
    n_obs = obs.sum(axis=0)
    X = np.where(obs, R, 0.0)
    mean = X.sum(axis=0) / np.maximum(n_obs, 1)
    X = np.where(obs, X - mean, 0.0)
    ss = np.square(X).sum(axis=0)
    ok = (n_obs >= min_obs) & (ss > 0)
    X, ss, n_obs = X[:, ok], ss[ok], n_obs[ok]
    T, n = X.shape
    if n < 2:
        return ok, np.zeros((n, 0)), np.ones(n), np.ones(n), X, np.zeros((T, 0))
    sigma = np.sqrt(ss / (n_obs - 1) * DAYS_PER_MONTH)
    Xn = X / np.sqrt(ss)
    Gm = Xn @ Xn.T
    ev, V = np.linalg.eigh(Gm)
    k = int(np.sum(ev > mp_edge(n, T)))
    V = V[:, ::-1][:, :k].copy()
    B = Xn.T @ V
    if shrink:
        # Ledoit-Wolf intensity toward the identity for the correlation matrix, applied to the
        # systematic part (same statistic as shrinking the full sample correlation).
        s2 = float(np.square(Gm).sum())
        d2 = s2 - n
        b2 = float(np.square(np.square(Xn).sum(axis=1)).sum()) - s2 / T
        delta = min(max(b2, 0.0), d2) / d2 if d2 > 0 else 1.0
        B = B * np.sqrt(1.0 - delta)
    psi = np.maximum(1.0 - np.square(B).sum(axis=1), PSI_FLOOR)
    return ok, B, psi, sigma, Xn, V


def residual_label(x: np.ndarray, G: np.ndarray, psi: np.ndarray) -> np.ndarray:
    """Standardised GLS residual z of x on G with weights 1/psi; NaN-safe on x."""
    f = np.isfinite(x)
    z = np.full(len(x), np.nan)
    if f.sum() <= G.shape[1] + 5:
        return z
    xw = x[f] / np.sqrt(psi[f])
    U = gls_basis(G[f], psi[f])
    z[f] = xw - U @ (U.T @ xw)
    return z


def clip_label(z: np.ndarray) -> np.ndarray:
    sd = np.nanstd(z)
    if not np.isfinite(sd) or sd <= 0:
        return np.full(len(z), np.nan)
    return np.clip(z / sd, -LABEL_CLIP, LABEL_CLIP)


def residual_book(s: np.ndarray, G: np.ndarray, psi: np.ndarray, sigma: np.ndarray) -> np.ndarray:
    """Dollar weights of the factor-neutral book for scores s, scaled to unit predicted risk.

    In risk units the holdings are v = Psi^{-1/2} (I - U U') s with U the GLS basis of G, so
    G'v = 0 and the predicted variance is sum(v^2 psi). The book earns s'z up to scale.
    """
    U = gls_basis(G, psi)
    p = s - U @ (U.T @ s)
    nrm = np.sqrt(np.square(p).sum())
    if not np.isfinite(nrm) or nrm < 1e-14:
        return np.zeros(len(s))
    return p / nrm / np.sqrt(psi) / sigma


# ==================================================================================================
# ctf_risk
# Monthly risk pass: statistical risk models, residual targets, constraint bases and
# features built from the daily return file.
#
# For month t everything except the label uses daily returns up to the month-end t and
# the characteristics observed at t. The label uses ret_exc_lead1m (the return of month
# t+1) and is only ever consumed by refits that happen after month t+1 has been realised.
#
# Daily features are generated on a grid rather than picked one by one:
#   path     cumulative return over the last h days, h in CUM_H, raw and factor-residual
#   legs     older legs (days -63..-22, -126..-22, -252..-22)
#   shape    extremes, volatility term structure, asymmetry, persistence of the last month
#   peers    leave-one-out averages of a fixed set of base signals over five peer sets
#            (SIC2, SIC3, SIC4, nearest neighbours in characteristic space, nearest
#            neighbours in residual-return correlation), and own-minus-peer spreads
# ==================================================================================================

VOL_MODE = os.environ.get("CTF_VOL_MODE", "252")     # "252": one-year volatility; "har": mean of 21/63/252-day variances
WIN_SHORT, MIN_OBS_SHORT = 252, 200
WIN_LONG, MIN_OBS_LONG = 756, 250
MIN_NAMES = 60
KNN_K = 20
CUM_H = (1, 2, 3, 4, 5, 7, 10, 15, 21)
RES_LEGS = ((63, 21), (126, 21), (252, 21))
PEER_SETS = ("s2", "s3", "s4", "ck", "rk")
PEER_BASE = ("r1", "r5", "r21", "l63_22", "e5", "e21")
PEER_SPREAD = ("r5", "r21", "e5", "e21")

RAW_NAMES = [f"d_r{h}" for h in CUM_H] + ["d_l63_22"]
RES_NAMES = [f"d_e{h}" for h in CUM_H] + [f"d_e{a}_{b + 1}" for a, b in RES_LEGS]
SHAPE_NAMES = [
    "d_max5", "d_min5", "d_min21", "d_vol5", "d_vol21", "d_vr5_21", "d_vr21_252", "d_vr63_252",
    "d_semi21", "d_ppos21", "d_eff21", "d_eff63", "d_ac21", "d_ac63", "d_zr1", "d_zr5", "d_zr21",
    "d_emax21", "d_emin21", "d_evol21", "d_evol5", "d_eac21", "d_eac63", "d_psi",
]
PEER_NAMES = ([f"d_{p}_{b}" for p in PEER_SETS for b in PEER_BASE]
              + [f"d_x{p}_{b}" for p in PEER_SETS for b in PEER_SPREAD])
DAILY_NAMES = RAW_NAMES + RES_NAMES + SHAPE_NAMES + PEER_NAMES


def _acf1(A: np.ndarray, O: np.ndarray) -> np.ndarray:
    """Lag-1 autocorrelation of each column of A over rows where both days are observed."""
    both = O[1:] & O[:-1]
    cnt = both.sum(axis=0)
    a, b = np.where(both, A[1:], 0.0), np.where(both, A[:-1], 0.0)
    ma, mb = a.sum(0) / np.maximum(cnt, 1), b.sum(0) / np.maximum(cnt, 1)
    a, b = np.where(both, a - ma, 0.0), np.where(both, b - mb, 0.0)
    den = np.sqrt(np.square(a).sum(0) * np.square(b).sum(0))
    out = np.where(den > 0, (a * b).sum(0) / np.where(den > 0, den, 1.0), np.nan)
    return np.where(cnt >= 8, out, np.nan)


def raw_features(R: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """(T, n) raw daily window -> path block (n, len(RAW_NAMES)) and raw shape block (n, 17)."""
    T, n = R.shape
    O = np.isfinite(R)
    R0 = np.where(O, R, 0.0)

    def leg(a: int, b: int) -> np.ndarray:
        """Sum over days -a .. -(b+1); NaN unless at least 60% of the leg is observed."""
        if T < a:
            return np.full(n, np.nan)
        sl = slice(T - a, T - b)
        c = O[sl].sum(0)
        return np.where(c >= max(1, int(np.ceil(0.6 * (a - b)))), R0[sl].sum(0), np.nan)

    def std(a: int) -> np.ndarray:
        if T < a:
            return np.full(n, np.nan)
        sl = slice(T - a, T)
        c = O[sl].sum(0)
        m = R0[sl].sum(0) / np.maximum(c, 1)
        v = np.where(O[sl], np.square(R0[sl] - m), 0.0).sum(0) / np.maximum(c - 1, 1)
        return np.where(c >= max(3, int(np.ceil(0.6 * a))), np.sqrt(v), np.nan)

    path = np.column_stack([leg(h, 0) for h in CUM_H] + [leg(63, 21)])
    r1, r5, r21 = path[:, CUM_H.index(1)], path[:, CUM_H.index(5)], path[:, CUM_H.index(21)]

    sh = np.full((n, 17), np.nan)
    if T >= 5:
        any5 = O[-5:].sum(0) >= 3
        sh[:, 0] = np.where(any5, np.max(np.where(O[-5:], R[-5:], -np.inf), 0), np.nan)
        sh[:, 1] = np.where(any5, np.min(np.where(O[-5:], R[-5:], np.inf), 0), np.nan)
    if T >= 21:
        any21 = O[-21:].sum(0) >= 13
        sh[:, 2] = np.where(any21, np.min(np.where(O[-21:], R[-21:], np.inf), 0), np.nan)
    v5, v21, v63, v252 = std(5), std(21), std(63), std(min(T, 252))
    sh[:, 3], sh[:, 4] = v5, v21
    with np.errstate(divide="ignore", invalid="ignore"):
        sh[:, 5] = np.where(v21 > 0, v5 / v21, np.nan)
        sh[:, 6] = np.where(v252 > 0, v21 / v252, np.nan)
        sh[:, 7] = np.where(v252 > 0, v63 / v252, np.nan)
        if T >= 21:
            a, o = R0[-21:], O[-21:]
            tot = np.square(a).sum(0)
            ok21 = o.sum(0) >= 13
            sh[:, 8] = np.where(ok21 & (tot > 0), np.square(np.minimum(a, 0.0)).sum(0) / np.where(tot > 0, tot, 1.0),
                                np.nan)
            sh[:, 9] = np.where(ok21, (a > 0).sum(0) / np.maximum(o.sum(0), 1), np.nan)
            ab = np.abs(a).sum(0)
            sh[:, 10] = np.where(ok21 & (ab > 0), a.sum(0) / np.where(ab > 0, ab, 1.0), np.nan)
            sh[:, 12] = _acf1(a, o)
        if T >= 63:
            a, o = R0[-63:], O[-63:]
            ab = np.abs(a).sum(0)
            ok63 = o.sum(0) >= 38
            sh[:, 11] = np.where(ok63 & (ab > 0), a.sum(0) / np.where(ab > 0, ab, 1.0), np.nan)
            sh[:, 13] = _acf1(a, o)
        sh[:, 14] = np.where(v252 > 0, r1 / v252, np.nan)
        sh[:, 15] = np.where(v252 > 0, r5 / (v252 * np.sqrt(5.0)), np.nan)
        sh[:, 16] = np.where(v252 > 0, r21 / (v252 * np.sqrt(21.0)), np.nan)
    return path, sh


def residual_features(E: np.ndarray, psi: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Standardised factor-residual shocks E (T, n) -> path block and residual shape block (n, 7)."""
    T, n = E.shape

    def leg(a: int, b: int) -> np.ndarray:
        if T < a:
            return np.full(n, np.nan)
        return E[T - a:T - b].sum(0) / np.sqrt(a - b)

    path = np.column_stack([leg(h, 0) for h in CUM_H] + [leg(a, b) for a, b in RES_LEGS])
    sh = np.full((n, 7), np.nan)
    if T >= 21:
        srt = np.sort(E[-21:], axis=0)
        sh[:, 0], sh[:, 1] = srt[-3:].mean(0), srt[:3].mean(0)
        sh[:, 2], sh[:, 3] = E[-21:].std(0), E[-5:].std(0)
        sh[:, 4] = _acf1(E[-21:], np.ones((21, n), bool))
    if T >= 63:
        sh[:, 5] = _acf1(E[-63:], np.ones((63, n), bool))
    sh[:, 6] = psi
    return path, sh


def knn_from_distance(d2: np.ndarray, k: int) -> np.ndarray:
    """Indices (n, k) of the k smallest entries of each row, the diagonal excluded."""
    n = d2.shape[0]
    k = min(k, n - 1)
    if k <= 0:
        return np.zeros((n, 0), np.int64)
    d2[np.arange(n), np.arange(n)] = np.inf
    return np.sort(np.argpartition(d2, k - 1, axis=1)[:, :k], axis=1)


def knn_index(Z: np.ndarray, k: int) -> np.ndarray:
    Zd = Z.astype(np.float64)
    sq = np.square(Zd).sum(1)
    return knn_from_distance(sq[:, None] + sq[None, :] - 2.0 * (Zd @ Zd.T), k)


def peer_mean(v: np.ndarray, idx: np.ndarray) -> np.ndarray:
    """NaN-aware mean of each column of v (n, c) over the peers of each row."""
    n, k = idx.shape
    if k == 0:
        return np.full(v.shape, np.nan)
    pv = v[idx]                                   # (n, k, c)
    f = np.isfinite(pv)
    cnt = f.sum(1)
    s = np.where(f, pv, 0.0).sum(1)
    return np.where(cnt >= max(1, k // 4), s / np.maximum(cnt, 1), np.nan)


def loo_group_mean(v: np.ndarray, codes: np.ndarray, min_others: int = 2) -> np.ndarray:
    """Mean of each column of v over the other members of the row's group (NaN-aware)."""
    _, inv = np.unique(codes, return_inverse=True)
    ng = int(inv.max()) + 1 if inv.size else 0
    out = np.full(v.shape, np.nan)
    for j in range(v.shape[1]):
        x = v[:, j]
        f = np.isfinite(x)
        s = np.bincount(inv[f], weights=x[f], minlength=ng)[inv]
        c = np.bincount(inv[f], minlength=ng)[inv].astype(np.float64)
        s_o = s - np.where(f, x, 0.0)
        c_o = c - f
        out[:, j] = np.where(c_o >= min_others, s_o / np.maximum(c_o, 1.0), np.nan)
    out[codes < 0] = np.nan
    return out


def har_sigma(R: np.ndarray, sigma_long: np.ndarray) -> np.ndarray:
    """Monthly volatility from the average of the 21-, 63- and full-window daily variances.

    R is the (T, n) daily window of the eligible names; a short leg with fewer than 60% of
    its days observed falls back to the full-window estimate.
    """
    T = R.shape[0]
    var = [np.square(sigma_long)]
    for h in (21, 63):
        if T < h:
            var.append(np.square(sigma_long))
            continue
        blk = R[-h:]
        obs = np.isfinite(blk)
        c = obs.sum(axis=0)
        x = np.where(obs, blk, 0.0)
        mu = x.sum(axis=0) / np.maximum(c, 1)
        v = np.where(obs, np.square(x - mu), 0.0).sum(axis=0) / np.maximum(c - 1, 1) * 21.0
        var.append(np.where((c >= int(np.ceil(0.6 * h))) & (v > 0), v, np.square(sigma_long)))
    return np.sqrt(np.mean(var, axis=0))


def char_factors(Zr: np.ndarray) -> np.ndarray:
    """Principal components of one month's centred ranks above the Marchenko-Pastur edge."""
    Z = Zr.astype(np.float64)
    Z = Z - Z.mean(axis=0)
    sd = Z.std(axis=0)
    keep = sd > 1e-12
    Z = Z[:, keep] / sd[keep]
    n, p = Z.shape
    if n < 3 or p < 1:
        return np.zeros((n, 0))
    U, s, _ = np.linalg.svd(Z / np.sqrt(n), full_matrices=False)
    k = int(np.sum(np.square(s) > mp_edge(p, n)))
    return U[:, :k] * s[:k]


def risk_month(t: int, lo: int, hi: int, end: int, M: np.ndarray, cols: np.ndarray, Xr_m: np.ndarray,
               ret: np.ndarray, s2: np.ndarray, s3: np.ndarray, s4: np.ndarray, want_long: bool = True,
               vol_mode: str = "252") -> dict:
    """Everything the model needs for one month: risk models, labels, bases, daily features.

    Inputs are restricted to the month's own rows (Xr_m, ret, sic codes) and to daily
    returns up to the month-end (rows [end - WIN_LONG, end) of M), so the result cannot
    depend on any other month or on later data.
    """
    m = hi - lo
    out = dict(t=t, lo=lo, hi=hi, D=np.full((m, len(DAILY_NAMES)), np.nan, np.float32), books={}, z={}, label={},
               sig=np.full(m, np.nan, np.float32), psi=np.full(m, np.nan, np.float32), nfac=-1, n_ok=0)
    if end < 30 or m < 3:
        return out
    n_res = len(RES_NAMES)
    i_r = {h: CUM_H.index(h) for h in CUM_H}
    Rl = np.asarray(M[max(0, end - WIN_LONG):end])[:, cols].astype(np.float64)
    Rs = Rl[-WIN_SHORT:]
    T = Rs.shape[0]

    raw_path, raw_shape = raw_features(Rs)
    res_path = np.full((m, n_res), np.nan)
    res_shape = np.full((m, 7), np.nan)
    rk_idx = np.zeros((m, 0), np.int64)

    ok, B, psi, sigma, Xn, V = pca_risk(Rs, min(MIN_OBS_SHORT, max(20, T * 4 // 5)))
    out["n_ok"] = int(ok.sum())
    sig_fast = np.full(m, np.nan)
    if vol_mode == "har" and ok.any():
        sigma = har_sigma(Rs[:, ok], sigma)
        sig_fast[ok] = sigma
    if ok.sum() >= min(MIN_NAMES, max(10, m // 3)):
        E = (Xn - V @ B.T) * (np.sqrt(T) / np.sqrt(psi))          # ~ unit variance per day
        res_path[ok], res_shape[ok] = residual_features(E, psi)
        # peers by residual-return correlation, estimated before the last month so the
        # peer set is not selected on the very moves it is used to summarise
        Ec = E[:T - 21] if T > 60 else E
        Ec = Ec - Ec.mean(0)
        nrm = np.sqrt(np.square(Ec).sum(0))
        Ec = Ec / np.where(nrm > 0, nrm, 1.0)
        loc = np.flatnonzero(ok)
        kk = knn_from_distance(-(Ec.T @ Ec), KNN_K)
        if kk.shape[1] > 0:
            rk_idx = np.full((m, kk.shape[1]), -1, np.int64)
            rk_idx[loc] = loc[kk]

        out["sig"][loc], out["psi"][loc] = sigma, psi
        out["nfac"] = B.shape[1]
        inv_s = 1.0 / sigma
        x = ret[ok] / sigma
        Gb = np.column_stack([B, inv_s])
        Gi = industry_dummies(s2[ok])
        Gc = char_factors(Xr_m[ok])
        for name, G in (("o252", np.column_stack([Gb, Gi])),
                        ("n252", np.column_stack([Gb, Gc])),
                        ("f252", np.column_stack([Gb, Gi, Gc]))):
            U = gls_basis(G, psi)
            out["books"][name] = (lo + loc, psi, sigma, U)
            if np.isfinite(x).all():
                xw = x / np.sqrt(psi)
                zz = xw - U @ (U.T @ xw)
            else:
                zz = residual_label(x, G, psi)
            out["z"][name] = (loc, zz.astype(np.float32))
            out["label"][name] = (loc, clip_label(zz).astype(np.float32))
        zz = residual_label(x, Gi, np.ones(len(x)))
        out["z"]["x2"] = (loc, zz.astype(np.float32))
        out["label"]["x2"] = (loc, clip_label(zz).astype(np.float32))

    if want_long:
        okl, Bl, psil, sigl, _, _ = pca_risk(Rl, min(MIN_OBS_LONG, max(20, Rl.shape[0] // 2)), shrink=True)
        if okl.sum() >= min(MIN_NAMES, max(10, m // 3)):
            locl = np.flatnonzero(okl)
            if vol_mode == "har":
                sigl = np.where(np.isfinite(sig_fast[okl]), sig_fast[okl], sigl)
            inv_s = 1.0 / sigl
            G = np.column_stack([Bl, inv_s, industry_dummies(s2[okl]) * inv_s[:, None]])
            U = gls_basis(G, psil)
            out["books"]["o756"] = (lo + locl, psil, sigl, U)
            zz = residual_label(ret[okl] / sigl, G, psil)
            out["z"]["o756"] = (locl, zz.astype(np.float32))
            out["label"]["o756"] = (locl, clip_label(zz).astype(np.float32))

    # peer aggregates of the base signals
    base = {
        "r1": raw_path[:, i_r[1]], "r5": raw_path[:, i_r[5]], "r21": raw_path[:, i_r[21]],
        "l63_22": raw_path[:, len(CUM_H)],
        "e5": res_path[:, i_r[5]], "e21": res_path[:, i_r[21]],
    }
    Vb = np.column_stack([base[b] for b in PEER_BASE])
    ck_idx = knn_index(Xr_m, KNN_K)
    means = {"s2": loo_group_mean(Vb, s2), "s3": loo_group_mean(Vb, s3), "s4": loo_group_mean(Vb, s4),
             "ck": peer_mean(Vb, ck_idx)}
    if rk_idx.shape[1] > 0:
        mk = peer_mean(Vb, np.where(rk_idx >= 0, rk_idx, 0))
        mk[rk_idx[:, 0] < 0] = np.nan
        means["rk"] = mk
    else:
        means["rk"] = np.full(Vb.shape, np.nan)
    sp = [PEER_BASE.index(b) for b in PEER_SPREAD]
    peer = np.column_stack([means[p] for p in PEER_SETS] + [Vb[:, sp] - means[p][:, sp] for p in PEER_SETS])
    out["D"] = np.column_stack([raw_path, res_path, raw_shape, res_shape, peer]).astype(np.float32)
    return out


BOOK_NAMES = ("o252", "n252", "f252", "o756")


def _risk_chunk(ts, starts, months, days, M, col_all, Xr, ret, sic2, sic3, sic4, want_long, vol_mode="252"):
    res = []
    for t in ts:
        lo, hi = int(starts[t]), int(starts[t + 1])
        end = int(np.searchsorted(days, months[t], side="right"))
        res.append(risk_month(t, lo, hi, end, M, col_all[lo:hi], np.asarray(Xr[lo:hi]), ret[lo:hi],
                              sic2[lo:hi], sic3[lo:hi], sic4[lo:hi], want_long, vol_mode))
    return res


def risk_pass(P: dict, days: np.ndarray, M: np.ndarray, Xr: np.ndarray, uid: np.ndarray,
              want_long: bool = True, verbose: bool = True, n_jobs: int = 1, vol_mode: str | None = None) -> dict:
    """Sweep the months (optionally in parallel processes) and assemble per-row arrays.

    books[name][t] = (rows, psi, sigma, U) with rows the global row indices of the
    eligible names and U the GLS basis of the constraint matrix.
    """
    n, months, starts = P["n"], P["months"], P["starts"]
    col_all = np.searchsorted(uid, P["ids"])
    vol_mode = VOL_MODE if vol_mode is None else vol_mode
    names = [b for b in BOOK_NAMES if want_long or b != "o756"]
    z = {b: np.full(n, np.nan, np.float32) for b in names + ["x2"]}
    label = {b: np.full(n, np.nan, np.float32) for b in names + ["x2"]}
    books = {b: [None] * len(months) for b in names}
    D = np.full((n, len(DAILY_NAMES)), np.nan, np.float32)
    sig = np.full(n, np.nan, np.float32)
    psi_all = np.full(n, np.nan, np.float32)
    nfac = []
    T = len(months)
    args = (starts, months, days, M, col_all, Xr, P["ret"], P["sic2"], P["sic3"], P["sic4"], want_long, vol_mode)
    if n_jobs > 1 and T > 8:
        from joblib import Parallel, delayed

        size = max(1, min(12, T // (4 * n_jobs) + 1))
        chunks = [list(range(a, min(T, a + size))) for a in range(0, T, size)]
        parts = Parallel(n_jobs=n_jobs)(delayed(_risk_chunk)(c, *args) for c in chunks)
        results = [r for part in parts for r in part]
    else:
        results = []
        for t in range(T):
            results.extend(_risk_chunk([t], *args))
            if verbose and (t % 120 == 0 or t == T - 1):
                r = results[-1]
                log(f"risk pass month {t + 1}/{T}: {r['hi'] - r['lo']} names, {r['n_ok']} eligible, "
                    f"{max(r['nfac'], 0)} return factors")
    for r in results:
        t, lo, hi = r["t"], r["lo"], r["hi"]
        D[lo:hi], sig[lo:hi], psi_all[lo:hi] = r["D"], r["sig"], r["psi"]
        if r["nfac"] >= 0:
            nfac.append(r["nfac"])
        for b, bk in r["books"].items():
            books[b][t] = bk
        for b, (loc, zz) in r["z"].items():
            z[b][lo + loc] = zz
        for b, (loc, ll) in r["label"].items():
            label[b][lo + loc] = ll
    if verbose and nfac:
        log(f"risk pass done: return factors median {int(np.median(nfac))} (range {min(nfac)}-{max(nfac)})")
    return dict(z=z, label=label, books=books, D=D, sig=sig, psi=psi_all, names=names,
                daily_names=list(DAILY_NAMES))


# ==================================================================================================
# ctf_extra
# Features built from each stock's own history in the characteristics panel.
#
# All of them are causal: a value at month t uses rows of months <= t only.
#
#   update recency   how much of a stock's slow-moving (accounting) information changed in
#                    each of the last 12 months; fresh fundamentals behave differently from
#                    stale ones, and the timing of past updates locates the next one
#   rank changes     one-month change in every characteristic's cross-sectional rank
#   calendar         month of the year of the return being predicted
#   missingness      which characteristics are unavailable for the stock
# ==================================================================================================

N_LAGS = 12


def prev_rows(P: dict) -> np.ndarray:
    """Row index of the same security in the previous calendar month, -1 if absent.

    Months are consecutive month-ends in the panel; a gap in the month sequence (more
    than 35 days) breaks the link so that a stale row is never treated as last month's.
    """
    st, ids, months = P["starts"], P["ids"], P["months"]
    prev = np.full(P["n"], -1, np.int64)
    for t in range(1, len(months)):
        if months[t] - months[t - 1] > 35:
            continue
        a_lo, a_hi, b_lo, b_hi = int(st[t - 1]), int(st[t]), int(st[t]), int(st[t + 1])
        ia, ib = ids[a_lo:a_hi], ids[b_lo:b_hi]
        if len(ia) == 0:
            continue
        pos = np.minimum(np.searchsorted(ia, ib), len(ia) - 1)
        hit = ia[pos] == ib
        prev[b_lo:b_hi][hit] = a_lo + pos[hit]
    return prev


def slow_columns(X: np.ndarray, prev: np.ndarray, n_rows_anchor: int, max_change: float = 0.5,
                 sample: int = 400_000) -> np.ndarray:
    """Columns whose raw value usually stays put from one month to the next.

    Decided once from rows before the anchor (the first scored month), so the choice is
    the same whatever later data the run is given.
    """
    rows = np.flatnonzero(prev[:n_rows_anchor] >= 0)
    if len(rows) > sample:
        rows = rows[np.linspace(0, len(rows) - 1, sample).astype(np.int64)]
    if len(rows) == 0:
        return np.zeros(X.shape[1], bool)
    a, b = np.asarray(X[rows]), np.asarray(X[prev[rows]])
    both = np.isfinite(a) & np.isfinite(b)
    changed = both & (a != b)
    frac = changed.sum(0) / np.maximum(both.sum(0), 1)
    return (frac < max_change) & (both.sum(0) > 100)


def update_features(X: np.ndarray, prev: np.ndarray, slow: np.ndarray, chunk: int = 200_000) -> np.ndarray:
    """(rows, N_LAGS + 1): share of slow columns that changed at lags 0..11, then months since
    the last month in which at least a quarter of them changed (capped at N_LAGS)."""
    n = X.shape[0]
    u0 = np.full(n, np.nan, np.float32)
    cols = np.flatnonzero(slow)
    if len(cols):
        for lo in range(0, n, chunk):
            hi = min(n, lo + chunk)
            p = prev[lo:hi]
            ok = p >= 0
            if not ok.any():
                continue
            a = np.asarray(X[lo:hi])[ok][:, cols]
            b = np.asarray(X[p[ok]])[:, cols]
            both = np.isfinite(a) & np.isfinite(b)
            appeared = np.isfinite(a) & ~np.isfinite(b)
            ch = (both & (a != b)) | appeared
            den = np.isfinite(a).sum(1)
            val = np.where(den > 0, ch.sum(1) / np.maximum(den, 1), np.nan)
            tmp = np.full(hi - lo, np.nan, np.float32)
            tmp[ok] = val
            u0[lo:hi] = tmp
    out = np.full((n, N_LAGS + 1), np.nan, np.float32)
    out[:, 0] = u0
    cur = prev.copy()
    for k in range(1, N_LAGS):
        has = cur >= 0
        out[has, k] = u0[cur[has]]
        nxt = np.full(n, -1, np.int64)
        nxt[has] = prev[cur[has]]
        cur = nxt
    since = np.full(n, float(N_LAGS), np.float32)
    for k in range(N_LAGS - 1, -1, -1):
        hit = out[:, k] >= 0.25
        since[hit] = k
    known = np.isfinite(out[:, :N_LAGS]).any(axis=1)
    out[:, N_LAGS] = np.where(known, since, np.nan)
    return out


def rank_changes(Xr: np.ndarray, prev: np.ndarray, chunk: int = 200_000) -> np.ndarray:
    """One-month change in each centred rank; 0 where the stock has no row last month."""
    n, p = Xr.shape
    out = np.zeros((n, p), np.float16)
    for lo in range(0, n, chunk):
        hi = min(n, lo + chunk)
        pr = prev[lo:hi]
        ok = pr >= 0
        if ok.any():
            d = np.asarray(Xr[lo:hi])[ok] - np.asarray(Xr[pr[ok]])
            blk = np.zeros((hi - lo, p), np.float16)
            blk[ok] = d.astype(np.float16)
            out[lo:hi] = blk
    return out


def calendar_features(P: dict) -> np.ndarray:
    """One-hot month of the year of the return month (the month after the formation date)."""
    m = (P["months"].astype("datetime64[D]").astype("datetime64[M]").astype(np.int64) + 1) % 12
    onehot = np.zeros((len(m), 12), np.float32)
    onehot[np.arange(len(m)), m] = 1.0
    return (onehot[P["mon"]] - 1.0 / 12.0).astype(np.float32)


def missing_indicators(X: np.ndarray) -> np.ndarray:
    return ((~np.isfinite(np.asarray(X))).astype(np.float32) - 0.5) / np.float32(np.sqrt(3.0))


# ==================================================================================================
# ctf_learn
# Walk-forward learners. A learner maps (features, label) to out-of-sample scores.
#
# Causality contract shared by every learner here: the model used to score month t is
# fitted on rows of months strictly before the refit month r <= t, and a row of month m
# carries the label built from the return of month m + 1, which is realised by the end of
# month m + 1 <= r. Nothing dated after r enters the fit, including binning, scaling,
# early stopping and hyper-parameter choices.
# ==================================================================================================

def refit_schedule(P: dict, pred_months: np.ndarray, every: int) -> list[tuple[int, np.ndarray]]:
    """[(refit_month_index, months_scored_by_that_fit)], anchored on the first scored month."""
    pm = np.sort(np.asarray(pred_months, dtype=np.int64))
    out = []
    if len(pm) == 0:
        return out
    first = int(pm[0])
    block = (pm - first) // every
    for b in np.unique(block):
        ms = pm[block == b]
        out.append((int(first + b * every), ms))
    return out


def rows_of(P: dict, months: np.ndarray) -> np.ndarray:
    st = P["starts"]
    if len(months) == 0:
        return np.zeros(0, np.int64)
    return np.concatenate([np.arange(st[m], st[m + 1]) for m in months])


# --------------------------------------------------------------------------------------
# Ridge family (sufficient statistics, optional exponential forgetting)
# --------------------------------------------------------------------------------------

def ridge_walk_forward(F, y: np.ndarray, P: dict, pred_months: np.ndarray, lams: list[float],
                       every: int = 1, halflife: float | None = None, mix: float = 0.0,
                       verbose: bool = False) -> np.ndarray:
    """Ridge regression of y on F, refit every `every` months from accumulated F'F and F'y.

    With `halflife` (months) a second set of exponentially weighted statistics is kept and
    the two normal equations are blended with weight `mix` on the weighted one, each first
    normalised by its own number of effective rows so the penalty means the same for both.
    Returns scores of shape (rows, len(lams)); NaN where no model was available.
    """
    st, n_m = P["starts"], len(P["months"])
    p = F.shape[1]
    A, b, cnt = np.zeros((p, p)), np.zeros(p), 0.0
    Aw, bw, cw = np.zeros((p, p)), np.zeros(p), 0.0
    g = 0.5 ** (1.0 / halflife) if halflife else 1.0
    pred = np.full((P["n"], len(lams)), np.nan)
    sched = refit_schedule(P, pred_months, every)
    nxt = 0                                   # next month whose statistics are not yet absorbed
    for r, ms in sched:
        while nxt < r:
            lo, hi = int(st[nxt]), int(st[nxt + 1])
            yy = y[lo:hi].astype(np.float64)
            f = np.isfinite(yy)
            if halflife:
                Aw *= g
                bw *= g
                cw *= g
            if f.any():
                Ft = np.asarray(F[lo:hi], dtype=np.float64)[f]
                AtA, Aty = Ft.T @ Ft, Ft.T @ yy[f]
                A += AtA
                b += Aty
                cnt += f.sum()
                if halflife:
                    Aw += AtA
                    bw += Aty
                    cw += f.sum()
            nxt += 1
        if cnt <= p:
            continue
        if halflife and mix > 0 and cw > 0:
            An = (1 - mix) * A / cnt + mix * Aw / cw
            bn = (1 - mix) * b / cnt + mix * bw / cw
        else:
            An, bn = A / cnt, b / cnt
        ev, Q = np.linalg.eigh(An)
        Qb = Q.T @ bn
        rows = rows_of(P, ms)
        Fq = np.asarray(F[rows], dtype=np.float64) @ Q
        for j, lam in enumerate(lams):
            pred[rows, j] = Fq @ (Qb / (ev + lam))
        if verbose:
            log(f"ridge refit at month {r}: {int(cnt):,} rows, {p} columns")
    return pred


# --------------------------------------------------------------------------------------
# Gradient boosting
# --------------------------------------------------------------------------------------

def _book_metric(month_codes: np.ndarray, z: np.ndarray, n_months: int):
    """Early-stopping metric: Sharpe ratio of the monthly book returns s'z / |s|."""
    def feval(preds, _data):
        num = np.bincount(month_codes, weights=preds * z, minlength=n_months)
        den = np.sqrt(np.bincount(month_codes, weights=preds * preds, minlength=n_months))
        r = np.where(den > 0, num / np.where(den > 0, den, 1.0), 0.0)
        sd = r.std(ddof=1)
        return "book_sharpe", (r.mean() / sd if sd > 0 else 0.0), True
    return feval


def lgb_fit_predict(Xtr, ytr, ztr, mtr, Xpr, params: dict, valid_months: int, max_rounds: int,
                    patience: int, threads: int, seed: int) -> tuple[np.ndarray, int, float]:
    """Pick the number of rounds on the most recent months, refit on everything, score Xpr."""
    import lightgbm as lgb

    months = np.unique(mtr)
    n_valid = max(1, min(valid_months, len(months) // 3))
    cut = months[-n_valid]
    tr, va = mtr < cut, mtr >= cut
    per_month = np.bincount(mtr - months[0])
    per_month = per_month[per_month > 0]
    base = dict(objective="regression", verbose=-1, seed=seed, num_threads=threads, deterministic=True,
                force_row_wise=True, metric="None")
    base.update(params)
    if "min_data_in_leaf" not in base:
        base["min_data_in_leaf"] = int(np.median(per_month))
    dtr = lgb.Dataset(Xtr[tr], label=ytr[tr], free_raw_data=False)
    dva = lgb.Dataset(Xtr[va], label=ytr[va], reference=dtr, free_raw_data=False)
    booster = lgb.train(base, dtr, num_boost_round=max_rounds, valid_sets=[dva],
                        feval=_book_metric((mtr[va] - cut).astype(np.int64), ztr[va].astype(np.float64), n_valid),
                        callbacks=[lgb.early_stopping(patience, first_metric_only=True, verbose=False)])
    rounds = max(int(booster.best_iteration), 1)
    val = float(booster.best_score["valid_0"]["book_sharpe"])
    final = lgb.train(base, lgb.Dataset(Xtr, label=ytr), num_boost_round=rounds)
    return final.predict(Xpr, num_threads=threads), rounds, val


def lgb_walk_forward(X, y: np.ndarray, z: np.ndarray, P: dict, pred_months: np.ndarray, params: dict,
                     every: int = 12, valid_months: int = 60, max_rounds: int = 2000, patience: int = 200,
                     threads: int = 8, seed: int = 42, window: int | None = None,
                     verbose: bool = True, tag: str = "lgb") -> np.ndarray:
    pred = np.full(P["n"], np.nan, np.float32)
    st, mon = P["starts"], P["mon"]
    for r, ms in refit_schedule(P, pred_months, every):
        lo_m = 0 if window is None else max(0, r - window)
        lo, hi = int(st[lo_m]), int(st[r])
        yy = y[lo:hi]
        f = np.isfinite(yy)
        if f.sum() < 5000:
            continue
        rows = rows_of(P, ms)
        p, rounds, val = lgb_fit_predict(np.asarray(X[lo:hi])[f], yy[f].astype(np.float32), z[lo:hi][f],
                                         mon[lo:hi][f].astype(np.int64), np.asarray(X[rows]), params,
                                         valid_months, max_rounds, patience, threads, seed)
        pred[rows] = p
        if verbose:
            log(f"{tag} refit at month {r}: {int(f.sum()):,} rows, rounds {rounds}, valid book SR {val:.2f}")
    return pred


# --------------------------------------------------------------------------------------
# Feed-forward network in NumPy (multi-task: one output head per residual label)
# --------------------------------------------------------------------------------------

def _monthly_ic(p: np.ndarray, y: np.ndarray, m: np.ndarray, n_m: int) -> float:
    """Mean over months of the cross-sectional correlation of p and y (rows with y finite)."""
    f = np.isfinite(y)
    if f.sum() < 10:
        return 0.0
    p, y, m = p[f].astype(np.float64), y[f].astype(np.float64), m[f]
    cnt = np.bincount(m, minlength=n_m).astype(np.float64)
    ok = cnt > 2
    mp_ = np.bincount(m, weights=p, minlength=n_m) / np.maximum(cnt, 1)
    my_ = np.bincount(m, weights=y, minlength=n_m) / np.maximum(cnt, 1)
    dp, dy = p - mp_[m], y - my_[m]
    num = np.bincount(m, weights=dp * dy, minlength=n_m)
    den = np.sqrt(np.bincount(m, weights=dp * dp, minlength=n_m) * np.bincount(m, weights=dy * dy, minlength=n_m))
    ic = np.where(den > 0, num / np.where(den > 0, den, 1.0), 0.0)
    return float(ic[ok].mean()) if ok.any() else 0.0


class Network:
    """Fully connected network with SiLU units, inverted dropout and AdamW.

    Initialisation, loss and update rule follow the usual deep-learning defaults: uniform
    weights and biases in +-1/sqrt(fan_in), masked mean squared error over the available
    labels, Adam moments (0.9, 0.999) with decoupled weight decay. All arithmetic is in
    double precision so that rounding differences between processors stay far below the
    tolerance at which weights are compared.
    """

    def __init__(self, d_in: int, hidden: tuple, n_out: int, rng: np.random.Generator):
        sizes = [d_in, *hidden, n_out]
        self.W, self.b = [], []
        for a, c in zip(sizes[:-1], sizes[1:]):
            bound = 1.0 / np.sqrt(a)
            self.W.append(rng.uniform(-bound, bound, size=(a, c)))
            self.b.append(rng.uniform(-bound, bound, size=c))
        self.m = [np.zeros_like(q) for q in self.W + self.b]
        self.v = [np.zeros_like(q) for q in self.W + self.b]
        self.t = 0

    def forward(self, X: np.ndarray, rng: np.random.Generator | None = None, p_drop: float = 0.0):
        h, cache = X, []
        for i in range(len(self.W) - 1):
            a = h @ self.W[i] + self.b[i]
            s = 1.0 / (1.0 + np.exp(-np.clip(a, -30.0, 30.0)))
            act = a * s
            mask = None
            if rng is not None and p_drop > 0:
                mask = (rng.random(act.shape) >= p_drop) / (1.0 - p_drop)
                act = act * mask
            cache.append((h, a, s, mask))
            h = act
        cache.append((h,))
        return h @ self.W[-1] + self.b[-1], cache

    def backward(self, g_out: np.ndarray, cache: list):
        L = len(self.W)
        gW, gb = [None] * L, [None] * L
        gW[-1], gb[-1] = cache[-1][0].T @ g_out, g_out.sum(axis=0)
        g = g_out @ self.W[-1].T
        for i in range(L - 2, -1, -1):
            h_in, a, s, mask = cache[i]
            if mask is not None:
                g = g * mask
            g = g * (s * (1.0 + a * (1.0 - s)))
            gW[i], gb[i] = h_in.T @ g, g.sum(axis=0)
            if i > 0:
                g = g @ self.W[i].T
        return gW, gb

    def step(self, gW: list, gb: list, lr: float, wd: float, b1: float = 0.9, b2: float = 0.999, eps: float = 1e-8):
        self.t += 1
        c1, c2 = 1.0 - b1 ** self.t, 1.0 - b2 ** self.t
        for k, (q, g) in enumerate(zip(self.W + self.b, gW + gb)):
            self.m[k] = b1 * self.m[k] + (1.0 - b1) * g
            self.v[k] = b2 * self.v[k] + (1.0 - b2) * (g * g)
            q *= 1.0 - lr * wd
            q -= lr * (self.m[k] / c1) / (np.sqrt(self.v[k] / c2) + eps)

    def predict(self, F, lo: int, hi: int, scale: float, chunk: int = 65536) -> np.ndarray:
        out = []
        for i in range(lo, hi, chunk):
            out.append(self.forward(np.asarray(F[i:min(hi, i + chunk)], dtype=np.float64) * scale)[0])
        return np.concatenate(out, axis=0) if out else np.zeros((0, self.b[-1].shape[0]))

    def predict_groups(self, F, rows: np.ndarray, group: np.ndarray, scale: float) -> np.ndarray:
        """Scores for `rows`, one forward pass per group (month).

        Each month is its own batch, so a month's scores never depend on which other
        months happen to be scored by the same fit.
        """
        if len(rows) == 0:
            return np.zeros((0, self.b[-1].shape[0]))
        cuts = np.flatnonzero(np.diff(group)) + 1
        return np.concatenate([self.forward(np.asarray(F[r], dtype=np.float64) * scale)[0]
                               for r in np.split(rows, cuts)], axis=0)


def train_epochs(net: Network, F, Y: np.ndarray, n_train: int, cfg: dict, rng: np.random.Generator,
                 n_epochs: int, scale: float, on_epoch=None, first: int = 0) -> None:
    """Mini-batch training on rows [first, n_train) of F (rows, d) and Y (rows, heads), NaN = no label."""
    batch, lr, wd, p_drop = cfg["batch"], cfg["lr"], cfg["weight_decay"], cfg["dropout"]
    n_rows = n_train - first
    for ep in range(n_epochs):
        perm = rng.permutation(n_rows)
        for i in range(0, n_rows, batch):
            idx = np.sort(perm[i:i + batch]) + first
            xb = np.asarray(F[idx], dtype=np.float64) * scale
            yb = np.asarray(Y[idx], dtype=np.float64)
            fin = np.isfinite(yb)
            out, cache = net.forward(xb, rng, p_drop)
            err = np.where(fin, out - np.where(fin, yb, 0.0), 0.0)
            gW, gb = net.backward(err * (2.0 / max(float(fin.sum()), 1.0)), cache)
            net.step(gW, gb, lr, wd)
        if on_epoch is not None and on_epoch(ep):
            break


def network_member(F, Y, mon, n_fit: int, pr_rows, cfg: dict, seed: int, epochs, first: int = 0):
    """Train one network on rows [first, n_fit).

    epochs is None -> early-stopping run: hold out the last `valid_months` months of the
                      window, return the epoch count with the best mean monthly IC
    epochs is int  -> train on the whole window for that many epochs, return scores of pr_rows
    """
    scale = float(np.sqrt(12.0))
    hidden = tuple(cfg["hidden"])
    k = Y.shape[1]
    rng = np.random.default_rng(seed)
    net = Network(F.shape[1], hidden, k, rng)
    if epochs is None:
        mtr = np.asarray(mon[:n_fit]).astype(np.int64)
        months = np.unique(mtr[first:])
        n_valid = max(1, min(cfg["valid_months"], len(months) // 3))
        cut = months[-n_valid]
        n_tr = int(np.searchsorted(mtr, cut))
        yva, mva = np.asarray(Y[n_tr:n_fit], dtype=np.float64), (mtr[n_tr:] - cut).astype(np.int64)
        state = {"best": -np.inf, "epochs": 1, "since": 0}

        def on_epoch(ep: int) -> bool:
            pv = net.predict(F, n_tr, n_fit, scale)
            ic = float(np.mean([_monthly_ic(pv[:, j], yva[:, j], mva, n_valid) for j in range(k)]))
            if ic > state["best"] + 1e-5:
                state.update(best=ic, epochs=ep + 1, since=0)
            else:
                state["since"] += 1
            return state["since"] >= cfg["patience"]

        train_epochs(net, F, Y, n_tr, cfg, rng, cfg["max_epochs"], scale, on_epoch, first)
        return int(state["epochs"])
    train_epochs(net, F, Y, n_fit, cfg, rng, int(epochs), scale, None, first)
    pr_rows = np.asarray(pr_rows)
    return net.predict_groups(F, pr_rows, np.asarray(mon)[pr_rows], scale)


# ==================================================================================================
# ctf_books
# Portfolio construction: residual books from scores, book blending and risk overlays.
# ==================================================================================================

def cap_positions(v: np.ndarray, cap: float | None) -> np.ndarray:
    """Limit each position (in risk units) to `cap` times the median absolute position.

    The book is deliberately not re-levered afterwards: when a few names dominate, the cap
    removes risk, so months with concentrated scores are held at lower leverage.
    """
    if cap is None or len(v) == 0:
        return v
    live = v != 0
    if live.sum() < 10:
        return v
    lim = cap * float(np.median(np.abs(v[live])))
    return np.clip(v, -lim, lim)


def book_from_basis(s: np.ndarray, U: np.ndarray, psi: np.ndarray, sigma: np.ndarray,
                    cap: float | None = None) -> np.ndarray:
    """Dollar weights of the constraint-neutral book for scores s: unit predicted risk, then capped."""
    U = U.astype(np.float64)
    p = s - U @ (U.T @ s)
    nrm = np.sqrt(np.square(p).sum())
    if not np.isfinite(nrm) or nrm < 1e-14:
        return np.zeros(len(s))
    return cap_positions(p / nrm / np.sqrt(psi), cap) / sigma


def residual_book_weights(s: np.ndarray, book: list, n: int, months: np.ndarray | None = None) -> np.ndarray:
    """Stack the monthly books of one constraint set for per-row scores s (NaN = no view)."""
    w = np.zeros(n)
    it = range(len(book)) if months is None else months
    for t in it:
        bk = book[t]
        if bk is None:
            continue
        rows, psi, sigma, U = bk
        st = s[rows]
        f = np.isfinite(st)
        if f.sum() < 10:
            continue
        st = np.where(f, st, 0.0).astype(np.float64)
        w[rows] = book_from_basis(st, U, psi.astype(np.float64), sigma.astype(np.float64))
    return w


def blend_coefficients(past: np.ndarray, halflife: float = 60.0, min_months: int = 36,
                       shrink: float = 0.5) -> np.ndarray:
    """Long-only shrunk max-Sharpe weights on books from their realised past returns."""
    k = past.shape[1]
    if len(past) < min_months:
        return np.full(k, 1.0 / k)
    age = np.arange(len(past))[::-1]
    om = 0.5 ** (age / halflife)
    om /= om.sum()
    mu = om @ past
    dev = past - mu
    cov = (dev * om[:, None]).T @ dev / (1.0 - np.square(om).sum())
    vol = np.sqrt(np.diag(cov))
    if not np.all(vol > 0):
        return np.full(k, 1.0 / k)
    corr = cov / np.outer(vol, vol)
    x = np.linalg.solve((1.0 - shrink) * corr + shrink * np.eye(k), mu / vol)
    x = np.clip(x, 0.0, None)
    if x.sum() <= 0:
        x = np.ones(k)
    return x / x.sum() / vol


def lw_book(R: np.ndarray, s: np.ndarray, kappa: float = 1.0, min_obs: int = 250,
            sigma_hint: np.ndarray | None = None, neutral: np.ndarray | None = None,
            cap: float | None = None) -> np.ndarray:
    """Dollar-neutral mean-variance book under a Ledoit-Wolf shrunk correlation matrix.

    R is the (T, n) window of daily returns of the month's names (NaN = missing) and s the
    scores (NaN = no view). The correlation matrix of the names with enough history is
    shrunk toward the identity with the Ledoit-Wolf intensity and ridged by `kappa`; the
    system is solved through the T x T Gram matrix. Weights are scaled to unit predicted
    risk and returned in dollars (zero for names without a view or history). `sigma_hint`
    optionally replaces the window volatility used to convert risk units into dollars,
    `neutral` (names x k, in risk units) lists extra exposures the book must not carry, and
    `cap` limits each position to that multiple of the median absolute position.
    """
    T, n_all = R.shape
    out = np.zeros(n_all)
    obs = np.isfinite(R)
    n_obs = obs.sum(axis=0)
    X = np.where(obs, R, 0.0)
    X = np.where(obs, X - X.sum(axis=0) / np.maximum(n_obs, 1), 0.0)
    ss = np.square(X).sum(axis=0)
    ok = (n_obs >= min(min_obs, max(20, T // 2))) & (ss > 0) & np.isfinite(s)
    if ok.sum() < 20:
        return out
    X, ss, n_obs = X[:, ok], ss[ok], n_obs[ok]
    n = X.shape[1]
    sigma = np.sqrt(ss / (n_obs - 1) * 21.0)
    if sigma_hint is not None:                       # volatility forecast of the risk pass, where it exists
        h = np.asarray(sigma_hint, dtype=np.float64)[ok]
        sigma = np.where(np.isfinite(h) & (h > 0), h, sigma)
    Xn = X / np.sqrt(ss)
    G = Xn @ Xn.T
    s2 = float(np.square(G).sum())
    d2 = s2 - n
    b2 = float(np.square(np.square(Xn).sum(axis=1)).sum()) - s2 / T
    delta = min(max(b2, 0.0), d2) / d2 if d2 > 0 else 1.0
    c = delta + kappa
    inv_s = 1.0 / sigma
    cons = inv_s[:, None]                              # dollar neutrality in risk units
    if neutral is not None:                            # further exposures to hold at zero (rows of all names)
        Cn = np.asarray(neutral, dtype=np.float64)[ok]
        Cn = Cn[:, np.abs(Cn).sum(axis=0) > 0]
        if Cn.shape[1]:
            cons = np.column_stack([cons, Cn])
    V = np.column_stack([s[ok], cons])
    if 1.0 - delta > 1e-8:
        AV = (V - Xn.T @ np.linalg.solve(G + (c / (1.0 - delta)) * np.eye(T), Xn @ V)) / c
    else:
        AV = V / c
    a, Bc = AV[:, 0], AV[:, 1:]
    H = cons.T @ Bc
    try:
        wx = a - Bc @ np.linalg.lstsq(H, cons.T @ a, rcond=1e-10)[0]
    except np.linalg.LinAlgError:
        wx = a
    var = (1.0 - delta) * float(np.square(Xn @ wx).sum()) + delta * float(np.square(wx).sum())
    if not np.isfinite(var) or var <= 0:
        return out
    out[ok] = cap_positions(wx / np.sqrt(var), cap) / sigma
    return out


def volatility_leverage(daily_pnl: list, halflife: float = 63.0, clip: tuple = (0.75, 1.5), min_days: int = 21,
                        min_history: int = 12, keep_days: int = 756) -> np.ndarray:
    """Leverage of each month's book from the realised daily volatility of the books held before it.

    daily_pnl[i] holds the daily returns earned by the (unlevered) book of scored month i
    during the month it was held; it becomes known only at the next month-end. The estimate
    for month i is the exponentially weighted volatility of all daily returns of books
    0..i-1, and the leverage is the mean of the estimates so far divided by the current one,
    clipped. Returns ones until enough history exists.
    """
    n = len(daily_pnl)
    est = np.full(n, np.nan)
    hist = np.zeros(0)
    for i in range(n):
        if len(hist) >= min_days:
            decay = 0.5 ** (np.arange(len(hist))[::-1] / halflife)
            est[i] = np.sqrt(float((decay * np.square(hist)).sum() / decay.sum()))
        hist = np.concatenate([hist, np.asarray(daily_pnl[i], dtype=np.float64)])[-keep_days:]
    lev = np.ones(n)
    for i in range(n):
        past = est[:i + 1]
        past = past[np.isfinite(past) & (past > 0)]
        if np.isfinite(est[i]) and est[i] > 0 and len(past) >= min_history:
            lev[i] = float(np.clip(past.mean() / est[i], clip[0], clip[1]))
    return lev


# ==================================================================================================
# ctf_pipeline
# End-to-end model: characteristics, daily returns -> monthly portfolio weights.
#
# Stages (each strictly causal, see the module notes of the pieces they call):
#   1. panel, within-month ranks, dense daily return matrix
#   2. monthly risk pass: Marchenko-Pastur PCA risk models, residual labels, constraint
#      bases for four books, features from the daily file
#   3. features from each stock's own history
#   4. walk-forward learners (expanding window, annual refits anchored on the first scored
#      month): multi-task network, gradient boosted trees, ridge
#   5. one unit-risk residual book per (learner, constraint set); books are blended with
#      long-only shrunk maximum-Sharpe coefficients estimated from their own past returns
#   6. weights are reported for the rows flagged ctff_test
#
# Determinism: every numerical kernel runs single-threaded inside a worker process and
# work is spread over processes, so results do not depend on the number of cores.
# ==================================================================================================

CFG = dict(
    seed=42,
    burn_in=120,                 # months scored before the first test month to seed the blend
    min_train=120,               # months of history required before the first fit
    refit_every=12,
    extras=("upd",),             # history features appended to ranks and daily features
    risk=dict(vol="har"),        # stock volatility: mean of 21-, 63- and 252-day variances
    mlp=dict(hidden=(128, 64, 32), dropout=0.1, act="silu", lr=1e-3, weight_decay=1e-4, batch=4096,
             max_epochs=30, patience=4, valid_months=36, seeds=5),
    lgb=dict(labels=("o756",),
             params=dict(learning_rate=0.02, num_leaves=63, feature_fraction=0.5, bagging_fraction=0.8,
                         bagging_freq=1, lambda_l2=10.0),
             valid_months=60, max_rounds=4000, patience=300, threads=8),
    ridge=dict(lam=1e-3, halflife=120.0, mix=0.5),
    learners=("mlp", "lgb", "ridge"),
    ensemble=dict(mlp=2.0, lgb=2.0, ridge=1.0),   # weights of the within-month z-scores in the ensemble
    mlp_views=("all",),          # extra networks on feature subsets: "c" characteristics, "d" daily features
    windows=(),                  # extra network and tree fits restricted to the most recent N months
    # Ledoit-Wolf mean-variance book; its score is taken relative to the two-digit industry mean
    lw=dict(head="o756", kappa=1.0, window=504, industry_relative=True),
    # books reported: (learner, book) with book "lw" or a residual constraint set; "all" builds every pair
    candidates=(("ens", "lw"), ("ens", "n252")),
    cap=2.0,                     # each position is capped at this multiple of the book's median |position|
    blend=dict(halflife=60.0, min_months=36, shrink=0.5),
    leverage=dict(halflife=63.0, clip=(0.75, 1.5)),   # from realised daily volatility; None switches it off
    weight_scale=0.01,           # constant, only keeps the reported numbers small
)


MAX_WORKERS = 32                 # the competition's allocation; more workers would only cost memory


def n_cpu() -> int:
    """Usable cores: the scheduler's affinity mask and any container quota, at most MAX_WORKERS.

    The results do not depend on this number; it only sets how many worker processes run.
    """
    try:
        n = len(os.sched_getaffinity(0))
    except AttributeError:
        n = os.cpu_count() or 1
    try:
        from joblib import cpu_count                            # also honours container CPU quotas

        n = min(n, int(cpu_count()))
    except Exception:
        pass
    return max(1, min(n, MAX_WORKERS))


def single_thread() -> None:
    """Pin every numerical library of this process to one thread."""
    for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS",
              "VECLIB_MAXIMUM_THREADS"):
        os.environ[k] = "1"
    try:
        from threadpoolctl import threadpool_limits

        threadpool_limits(1)
    except Exception:
        pass


def portable_workers() -> None:
    """Ship this module's functions to worker processes by value.

    Workers are separate interpreters; if the file was loaded under a name they cannot
    import, functions pickled by reference would not be found there.
    """
    import sys

    mod = sys.modules.get(__name__)
    if mod is None or __name__ == "__main__":
        return
    try:                                                        # newer joblib uses the cloudpickle package
        import cloudpickle

        cloudpickle.register_pickle_by_value(mod)
    except Exception:
        pass
    try:                                                        # older joblib carries its own copy
        from joblib.externals import cloudpickle as bundled

        bundled.register_pickle_by_value(mod)
    except Exception:
        pass


def fresh_workers() -> None:
    """Retire the worker pool so the next stage starts in clean processes.

    LightGBM brings its own OpenMP runtime; it is only ever loaded in worker processes
    that are created for the tree stage and retired after it.
    """
    try:
        from joblib.externals.loky import get_reusable_executor

        get_reusable_executor().shutdown(wait=True)
    except Exception:
        pass


# --------------------------------------------------------------------------------------
# Schedule
# --------------------------------------------------------------------------------------

def scoring_plan(P: dict, cfg: dict) -> tuple[np.ndarray, int]:
    """Months to score and the index of the first test month.

    Scoring starts `burn_in` months before the first test month (never before `min_train`
    months of history exist) so that book returns are available to the blend from the
    first test month on. Both anchors are fixed by the start of the sample and the first
    test month, hence unaffected by how far the data extends.
    """
    T = len(P["months"])
    has_test = np.array([P["test"][P["starts"][t]:P["starts"][t + 1]].any() for t in range(T)])
    first_test = int(np.flatnonzero(has_test)[0]) if has_test.any() else T
    min_train = min(cfg["min_train"], max(24, first_test // 2))
    start = max(min_train, first_test - cfg["burn_in"])
    start = min(start, max(first_test, 1)) if first_test < T else min(start, T - 1)
    return np.arange(start, T), first_test


# --------------------------------------------------------------------------------------
# Network learner, parallel over (refit, member)
# --------------------------------------------------------------------------------------

def _mlp_member(F, Y, mon, n_fit, pr_rows, cfg, seed, epochs, first=0):
    single_thread()
    return network_member(F, Y, mon, n_fit, pr_rows, cfg, seed, epochs, first)


def mlp_parallel(F, Y, P: dict, pred_months: np.ndarray, cfg: dict, every: int, seed: int, n_jobs: int,
                 window: int | None = None) -> np.ndarray:
    """Walk-forward network scores; `window` (months) limits each fit to the most recent months."""
    from joblib import Parallel, delayed

    st, mon = P["starts"], P["mon"]
    pred = np.full((P["n"], Y.shape[1]), np.nan)
    plan = []
    for r, ms in refit_schedule(P, pred_months, every):
        hi = int(st[r])
        lo = 0 if window is None else int(st[max(0, r - window)])
        if np.isfinite(Y[lo:hi]).any(axis=1).sum() < 2000 or len(np.unique(mon[lo:hi])) < 12:
            continue
        plan.append((r, hi, rows_of(P, ms), lo))
    if not plan:
        return pred
    order = sorted(range(len(plan)), key=lambda i: -(plan[i][1] - plan[i][3]))       # largest fits first
    ep = Parallel(n_jobs=n_jobs)(delayed(_mlp_member)(F, Y, mon, plan[i][1], None, cfg, seed + plan[i][0], None,
                                                      plan[i][3]) for i in order)
    epochs = {plan[i][0]: e for i, e in zip(order, ep)}
    log("network epochs per refit: " + " ".join(f"{p_[0]}:{epochs[p_[0]]}" for p_ in plan))
    tasks = [(i, s) for i in order for s in range(cfg["seeds"])]
    out = Parallel(n_jobs=n_jobs)(
        delayed(_mlp_member)(F, Y, mon, plan[i][1], plan[i][2], cfg, seed + plan[i][0] + 1000 * (s + 1),
                             epochs[plan[i][0]], plan[i][3]) for i, s in tasks)
    acc = {i: np.zeros((len(plan[i][2]), Y.shape[1]), np.float64) for i in range(len(plan))}
    for (i, s), p in zip(tasks, out):
        acc[i] += p
    for i, p_ in enumerate(plan):
        pred[p_[2]] = acc[i] / cfg["seeds"]
    return pred


# --------------------------------------------------------------------------------------
# Boosted trees, parallel over (refit, label)
# --------------------------------------------------------------------------------------

def _lgb_member(X, y, z, mon, lo, hi, pr_rows, cfg, seed):
    single_thread()
    # Several fits share the cores, so idle tree threads must sleep rather than spin; otherwise the
    # stage can stall when there are fewer cores than threads. Set before LightGBM is first loaded.
    os.environ["OMP_WAIT_POLICY"] = "PASSIVE"
    yy = np.asarray(y[lo:hi])
    f = np.isfinite(yy)
    p, rounds, val = lgb_fit_predict(np.asarray(X[lo:hi])[f], yy[f].astype(np.float32), np.asarray(z[lo:hi])[f],
                                     np.asarray(mon[lo:hi])[f].astype(np.int64), np.asarray(X[pr_rows]),
                                     cfg["params"], cfg["valid_months"], cfg["max_rounds"], cfg["patience"],
                                     cfg["threads"], seed)
    return np.asarray(p, dtype=np.float64), rounds, val


def lgb_parallel(X, labels: dict, zs: dict, P: dict, pred_months: np.ndarray, cfg: dict, every: int, seed: int,
                 n_jobs: int, window: int | None = None) -> dict:
    """Walk-forward tree scores; `window` (months) limits each fit to the most recent months."""
    from joblib import Parallel, delayed

    st, mon = P["starts"], P["mon"]
    pred = {b: np.full(P["n"], np.nan) for b in cfg["labels"]}
    tasks = []
    for r, ms in refit_schedule(P, pred_months, every):
        hi = int(st[r])
        lo = 0 if window is None else int(st[max(0, r - window)])
        for b in cfg["labels"]:
            if np.isfinite(labels[b][lo:hi]).sum() >= 5000 and len(np.unique(mon[lo:hi])) >= 24:
                tasks.append((b, r, hi, rows_of(P, ms), lo))
    if not tasks:
        return pred
    tasks.sort(key=lambda t: -(t[2] - t[4]))
    par = max(2, n_jobs // cfg["threads"])                      # >= 2 so the fits never run in the parent
    out = Parallel(n_jobs=par)(delayed(_lgb_member)(X, labels[b], zs[b], mon, lo, hi, rows, cfg, seed)
                               for b, r, hi, rows, lo in tasks)
    for (b, r, hi, rows, lo), (p, rounds, val) in zip(tasks, out):
        pred[b][rows] = p
        log(f"trees {b}{'' if window is None else f' ({window}m window)'} refit at month {r}: rounds {rounds}, "
            f"valid book SR {val:.2f}")
    return pred


# --------------------------------------------------------------------------------------
# Books and blend
# --------------------------------------------------------------------------------------

def month_z(s: np.ndarray, mon: np.ndarray, n_m: int) -> np.ndarray:
    """Within-month z-score of a score vector, NaN preserved."""
    f = np.isfinite(s)
    cnt = np.bincount(mon[f], minlength=n_m).astype(np.float64)
    mu = np.bincount(mon[f], weights=s[f], minlength=n_m) / np.maximum(cnt, 1)
    d = np.where(f, s - mu[mon], np.nan)
    sd = np.sqrt(np.bincount(mon[f], weights=np.square(d[f]), minlength=n_m) / np.maximum(cnt - 1, 1))
    return d / np.where(sd[mon] > 0, sd[mon], 1.0)


def _lw_chunk(ts, starts, months, days, M, col_all, S, kappa, window, sig, cap=None):
    single_thread()
    res = []
    for t in ts:
        lo, hi = int(starts[t]), int(starts[t + 1])
        end = int(np.searchsorted(days, months[t], side="right"))
        Rw = np.asarray(M[max(0, end - window):end])[:, col_all[lo:hi]].astype(np.float64)
        hint = None if sig is None else np.asarray(sig[lo:hi], dtype=np.float64)
        res.append((lo, hi, np.column_stack([lw_book(Rw, np.asarray(S[lo:hi, j], dtype=np.float64), kappa,
                                                     sigma_hint=hint, cap=cap) for j in range(S.shape[1])])))
    return res


def lw_books(S: np.ndarray, P: dict, days: np.ndarray, M: np.ndarray, uid: np.ndarray, pred_months: np.ndarray,
             kappa: float, window: int, n_jobs: int, sig: np.ndarray | None = None,
             cap: float | None = None) -> np.ndarray:
    """Ledoit-Wolf mean-variance books for each column of scores S (rows, k)."""
    from joblib import Parallel, delayed

    col_all = np.searchsorted(uid, P["ids"])
    W = np.zeros(S.shape)
    ts = [int(t) for t in pred_months]
    size = max(1, min(8, len(ts) // (4 * max(n_jobs, 1)) + 1))
    chunks = [ts[a:a + size] for a in range(0, len(ts), size)]
    parts = Parallel(n_jobs=max(2, n_jobs))(delayed(_lw_chunk)(c, P["starts"], P["months"], days, M, col_all, S, kappa,
                                                               window, sig, cap) for c in chunks)
    for part in parts:
        for lo, hi, w in part:
            W[lo:hi] = w
    return W


def candidate_books(scores: dict, R: dict, P: dict, pred_months: np.ndarray,
                    cap: float | None = None) -> tuple[list, np.ndarray]:
    """One unit-risk book per (learner, constraint set). Returns names and weights (rows, K)."""
    names = [(lrn, b) for lrn in scores for b in R["names"]]
    W = np.zeros((P["n"], len(names)))
    for t in pred_months:
        for j, (lrn, b) in enumerate(names):
            bk = R["books"][b][t]
            if bk is None:
                continue
            rows, psi, sigma, U = bk
            s = scores[lrn][b][rows].astype(np.float64)
            f = np.isfinite(s)
            if f.sum() < 10:
                continue
            W[rows, j] = book_from_basis(np.where(f, s, 0.0), U, psi.astype(np.float64), sigma.astype(np.float64), cap)
    return names, W


def industry_relative(s: np.ndarray, P: dict) -> np.ndarray:
    """Score minus its mean within the month's two-digit SIC industry (NaN preserved)."""
    key = P["mon"].astype(np.int64) * 1000 + (P["sic2"].astype(np.int64) + 1)
    _, inv = np.unique(key, return_inverse=True)
    f = np.isfinite(s)
    tot = np.bincount(inv[f], weights=s[f], minlength=inv.max() + 1)
    cnt = np.bincount(inv[f], minlength=inv.max() + 1)
    mean = tot / np.maximum(cnt, 1)
    return np.where(f, s - mean[inv], np.nan)


def held_daily_returns(w: np.ndarray, P: dict, days: np.ndarray, M: np.ndarray, uid: np.ndarray,
                       pred_months: np.ndarray) -> list:
    """Daily returns of each scored month's book over the following month (missing returns count as zero).

    Element i covers the trading days after month-end i up to and including month-end i+1, so
    it is known at the next portfolio date. The last scored month has no later month-end in
    the data and gets an empty block.
    """
    st = P["starts"]
    col_all = np.searchsorted(uid, P["ids"])
    ends = np.searchsorted(days, P["months"], side="right")
    out = []
    for t in pred_months:
        lo, hi = int(st[t]), int(st[t + 1])
        x = w[lo:hi]
        live = x != 0
        if t + 1 >= len(P["months"]) or live.sum() < 10 or ends[t + 1] <= ends[t]:
            out.append(np.zeros(0))
            continue
        block = np.asarray(M[ends[t]:ends[t + 1]])[:, col_all[lo:hi][live]].astype(np.float64)
        out.append(np.nan_to_num(block) @ x[live])
    return out


def online_blend(W: np.ndarray, P: dict, pred_months: np.ndarray, cfg: dict) -> tuple[np.ndarray, np.ndarray]:
    """Blend the books month by month using only their already realised returns."""
    st, ret = P["starts"], P["ret"]
    K = W.shape[1]
    w = np.zeros(P["n"])
    past, lam_hist = [], []
    for t in pred_months:
        lo, hi = int(st[t]), int(st[t + 1])
        live = np.abs(W[lo:hi]).sum(axis=0) > 0
        lam = np.zeros(K)
        if live.any():
            hist = np.array(past) if past else np.empty((0, K))
            lam = blend_coefficients(hist, cfg["halflife"], cfg["min_months"], cfg["shrink"]) if len(hist) else \
                np.full(K, 1.0 / K)
            lam = np.where(live, lam, 0.0)
            if lam.sum() <= 0:
                lam = live / live.sum()
            w[lo:hi] = W[lo:hi] @ lam
        lam_hist.append(lam)
        r = ret[lo:hi]
        if np.isfinite(r).all() and live.all():
            past.append(W[lo:hi].T @ r)                       # realised at the end of month t + 1
    return w, np.array(lam_hist)


# --------------------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------------------

def build(chars, features, daily_ret, cfg: dict | None = None, hooks: dict | None = None) -> dict:
    """Run the model and return every intermediate needed for inspection."""
    cfg = dict(CFG if cfg is None else cfg)
    hooks = hooks or {}
    t0 = time.perf_counter()
    single_thread()
    portable_workers()
    np.random.seed(cfg["seed"])
    jobs = n_cpu()
    log(f"start: {jobs} cores")

    P = prepare_panel(chars, features)
    uid = np.unique(P["ids"])
    n_m = len(P["months"])
    log(f"panel {P['X'].shape}, {n_m} months, {len(uid)} securities")
    Xr = rank_panel(P["X"], P["mon"])
    did, dday, dret = daily_arrays(daily_ret)
    days, M = build_daily(did, dday, dret, uid, int(P["months"][0]) - 1300)
    del did, dday, dret
    log(f"daily matrix {M.shape}")

    R = risk_pass(P, days, M, Xr, uid, n_jobs=jobs, verbose=False, vol_mode=cfg["risk"]["vol"])
    log(f"risk pass done; labelled rows " + ", ".join(f"{b} {int(np.isfinite(R['label'][b]).sum()):,}" for b in R["names"]))

    pred_months, first_test = scoring_plan(P, cfg)
    log(f"scoring months {pred_months[0]}..{pred_months[-1]} (first test month index {first_test})")
    n_anchor = int(P["starts"][pred_months[0]])

    blocks = [Xr, rank_columns(R["D"].astype(np.float64), P["mon"])]
    if cfg["extras"]:
        prev = prev_rows(P)
        if "upd" in cfg["extras"]:
            slow = slow_columns(P["X"], prev, n_anchor)
            blocks.append(rank_columns(update_features(P["X"], prev, slow).astype(np.float64), P["mon"]))
        if "dx1" in cfg["extras"]:
            blocks.append((rank_changes(Xr, prev).astype(np.float32) * 3.0))
        if "cal" in cfg["extras"]:
            blocks.append(calendar_features(P))
        if "miss" in cfg["extras"]:
            blocks.append(missing_indicators(P["X"]))
    F = np.ascontiguousarray(np.hstack(blocks), dtype=np.float32)
    n_dense = Xr.shape[1] + R["D"].shape[1]
    log(f"features {F.shape}")

    heads = list(R["label"].keys())                          # one network output per label
    Y = np.column_stack([R["label"][h] for h in heads]).astype(np.float32)
    all_pairs = cfg["candidates"] == "all"
    lw_head = cfg["lw"]["head"]
    need = set(heads) if all_pairs else ({lw_head} | {b for _, b in cfg["candidates"] if b != "lw"})
    scores = {}
    n_rank, n_daily = Xr.shape[1], R["D"].shape[1]
    view_cols = {"all": np.arange(F.shape[1]),
                 "c": np.r_[np.arange(n_rank), np.arange(n_dense, F.shape[1])],
                 "d": np.arange(n_rank, n_dense)}
    if "mlp" in cfg["learners"]:
        for v in cfg["mlp_views"]:
            Fv = F if v == "all" else np.ascontiguousarray(F[:, view_cols[v]])
            pm = mlp_parallel(Fv, Y, P, pred_months, cfg["mlp"], cfg["refit_every"], cfg["seed"], jobs)
            scores["mlp" if v == "all" else "mlp" + v] = {h: pm[:, j] for j, h in enumerate(heads)}
            log(f"network scores done (view {v}, {Fv.shape[1]} inputs)")
            del Fv
        for wdw in cfg["windows"]:
            pm = mlp_parallel(F, Y, P, pred_months, cfg["mlp"], cfg["refit_every"], cfg["seed"] + 7, jobs, int(wdw))
            scores[f"mlp{int(wdw)}"] = {h: pm[:, j] for j, h in enumerate(heads)}
            log(f"network scores done ({int(wdw)}-month window)")
        fresh_workers()
    if "ridge" in cfg["learners"]:
        rc = cfg["ridge"]
        scores["ridge"] = {}
        for j, h in enumerate(heads):
            if h in need:
                scores["ridge"][h] = ridge_walk_forward(F[:, :n_dense], Y[:, j], P, pred_months, [rc["lam"]], every=1,
                                                        halflife=rc["halflife"], mix=rc["mix"])[:, 0]
        log("ridge scores done")
    if "lgb" in cfg["learners"]:
        Xg = np.ascontiguousarray(np.hstack([P["X"], F[:, Xr.shape[1]:]]), dtype=np.float32)
        base = cfg["lgb"]["labels"][0]
        pl = lgb_parallel(Xg, R["label"], R["z"], P, pred_months, cfg["lgb"], cfg["refit_every"], cfg["seed"], jobs)
        scores["lgb"] = {h: pl.get(h, pl[base]) for h in heads}
        for wdw in cfg["windows"]:
            pw = lgb_parallel(Xg, R["label"], R["z"], P, pred_months, cfg["lgb"], cfg["refit_every"],
                              cfg["seed"] + 7, jobs, int(wdw))
            scores[f"lgb{int(wdw)}"] = {h: pw.get(h, pw[base]) for h in heads}
        del Xg
        fresh_workers()
        log("tree scores done")
    members = [(l, float(wt)) for l, wt in cfg["ensemble"].items() if l in scores and wt > 0]
    if len(members) > 1:
        scores["ens"] = {}
        wts = np.array([wt for _, wt in members])
        for h in heads:
            if all(h in scores[l] for l, _ in members):
                zs = np.column_stack([month_z(scores[l][h].astype(np.float64), P["mon"], n_m) for l, _ in members])
                ok = np.isfinite(zs).all(axis=1)
                scores["ens"][h] = np.where(ok, np.nan_to_num(zs) @ wts / wts.sum(), np.nan)

    if all_pairs:
        pairs = [(l, b) for l in scores for b in R["names"] if b in scores[l]]
        pairs += [(l, "lw") for l in scores if lw_head in scores[l]]
    else:
        pairs = [(l if l in scores else next(iter(scores)), b) for l, b in cfg["candidates"]]
    names, cols = [], []
    lw_learners = [l for l, b in pairs if b == "lw"]
    if lw_learners:
        S = np.column_stack([scores[l][lw_head] for l in lw_learners]).astype(np.float64)
        if cfg["lw"].get("industry_relative"):
            S = np.column_stack([industry_relative(S[:, j], P) for j in range(S.shape[1])])
        Wl = lw_books(S, P, days, M, uid, pred_months, cfg["lw"]["kappa"], cfg["lw"]["window"], jobs, R["sig"],
                      cfg["cap"])
        fresh_workers()
        log(f"Ledoit-Wolf books done for {lw_learners}")
    for l, b in pairs:
        if b == "lw":
            cols.append(Wl[:, lw_learners.index(l)])
        else:                                                # residual book; scores of its own head if present
            src = scores[l][b] if (all_pairs and b in scores[l]) else scores[l][lw_head]
            _, Wr = candidate_books({l: {b: src}}, dict(R, names=[b]), P, pred_months, cfg["cap"])
            cols.append(Wr[:, 0])
        names.append((l, b))
    W = np.column_stack(cols)
    if W.shape[1] == 1:
        w, lam = W[:, 0].copy(), np.ones((len(pred_months), 1))
    else:
        w, lam = online_blend(W, P, pred_months, cfg["blend"])
    lev = np.ones(len(pred_months))
    if cfg["leverage"]:
        lev = volatility_leverage(held_daily_returns(w, P, days, M, uid, pred_months), cfg["leverage"]["halflife"],
                                  tuple(cfg["leverage"]["clip"]))
        for i, t in enumerate(pred_months):
            w[int(P["starts"][t]):int(P["starts"][t + 1])] *= lev[i]
        log(f"leverage from realised volatility: mean {lev.mean():.3f}, range {lev.min():.2f}-{lev.max():.2f}")
    del M
    log("books done: mean blend coefficients " + ", ".join(
        f"{l}/{b} {v:.2f}" for (l, b), v in zip(names, (lam / np.maximum(lam.sum(1, keepdims=True), 1e-12)).mean(0))))
    w = w * cfg["weight_scale"]
    log(f"finished in {(time.perf_counter() - t0) / 60:.1f} min")
    return dict(P=P, R=R, w=w, W=W, names=names, lam=lam, lev=lev, scores=scores, pred_months=pred_months,
                first_test=first_test, uid=uid, days=days)


def to_frame(out: dict, chars) -> pd.DataFrame:
    """Weights of the rows flagged as test, keyed exactly as the input rows are."""
    P, w = out["P"], out["w"]
    w = np.where(np.isfinite(w), w, 0.0)
    keep = P["test"] if P["test"].any() else np.ones(P["n"], bool)
    src = P["order"][keep]                                   # original row positions
    res = pd.DataFrame({
        "id": np.asarray(chars["id"])[src],
        "eom": np.asarray(chars["eom"])[src],
        "w": np.round(w[keep], 12),
    })
    return res.sort_values(["id", "eom"], kind="stable").reset_index(drop=True)


def main(chars: pd.DataFrame, features: pd.DataFrame, daily_ret: pd.DataFrame) -> pd.DataFrame:
    return to_frame(build(chars, features, daily_ret), chars)
