Coverage for features/cross_sectional_norm.py: 100%
9 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Per-date cross-sectional rank normalisation (V6.4.3): a feature's level across assets is mostly asset identity, its
2rank on the day is the comparable part. Pure pandas, no I/O."""
4from __future__ import annotations
6from typing import TYPE_CHECKING
8import pandas as pd
10if TYPE_CHECKING:
11 from collections.abc import Sequence
14def cross_sectional_rank(frame: pd.DataFrame, columns: Sequence[str], *, date_column: str = "date", group_column: str | None = None) -> pd.DataFrame:
15 """Percentile rank of each of `columns` within its date (and `group_column`, e.g. the asset class, when given),
16 centred to [-0.5, 0.5]. NaN stays NaN; ties get the average rank. Same index as `frame`."""
17 columns = list(columns)
18 if frame.empty or not columns:
19 return pd.DataFrame(index=frame.index, columns=columns, dtype=float)
20 keys = [date_column] + ([group_column] if group_column else [])
21 return frame.groupby(keys, sort=False)[columns].rank(pct=True) - 0.5