"""
Aggregate asset-level weights and returns into Brinson-Fachler segments.
A segment's weight is the sum of its assets' weights; its return is the
weight-averaged return of those assets. Portfolio and benchmark are aggregated
separately, so a segment's return differs between the two when they hold
different names inside it, which is what the textbook selection effect needs.
Notes
-----
The segment map is static: a ticker keeps one segment for the whole window.
A held asset with a null return on a date contributes 0 to its segment that
day while its weight still counts (one warning per call reports how many).
A held asset with an infinite return is rejected, since it would silently
poison the segment return. A weights date with no row in `returns` has a null
segment return, never 0. A segment whose long and short weights net to ~0 but
whose P&L does not is rejected: its return is undefined, and a null would drop
that P&L from the attribution.
"""
import csv
import logging
from collections.abc import Mapping
from pathlib import Path
import numpy as np
import pyarrow as pa
from kaxanuk.attribution_analysis.entities.attribution_result import DiagnosticCode
from kaxanuk.attribution_analysis.exceptions import DataValidationError, MissingColumnError
from kaxanuk.attribution_analysis.modules.diagnostics import log_diagnostic
logger = logging.getLogger(__name__)
SEGMENT_MAP_COLUMNS = ("ticker", "segment")
NET_WEIGHT_TOLERANCE = 1e-12
NET_PNL_TOLERANCE = 1e-10
"""Max ``abs(P&L)`` of a net-zero segment on a date that is treated as float noise rather than lost P&L."""
[docs]
def load_segment_map(path: Path) -> dict[str, str]:
"""
Read a ``ticker,segment`` CSV into a mapping.
Parameters
----------
path : Path
CSV file with a header row containing ``ticker`` and ``segment``.
Returns
-------
dict[str, str]
Ticker to segment, both stripped.
Raises
------
MissingColumnError
If the header lacks ``ticker`` or ``segment``.
DataValidationError
If a row has an empty ticker or segment, or a ticker is assigned to
two different segments.
"""
with path.open(newline="", encoding="utf-8-sig") as handle:
reader = csv.DictReader(handle)
missing = [c for c in SEGMENT_MAP_COLUMNS if c not in (reader.fieldnames or [])]
if missing:
raise MissingColumnError(f"Segment map {path} is missing column(s): {', '.join(missing)}")
segment_map: dict[str, str] = {}
for line_number, row in enumerate(reader, start=2):
ticker = (row["ticker"] or "").strip()
segment = (row["segment"] or "").strip()
if not ticker or not segment:
raise DataValidationError(
f"Segment map {path} line {line_number}: ticker and segment are both required"
)
if ticker in segment_map and segment_map[ticker] != segment:
raise DataValidationError(
f"Segment map {path} assigns ticker '{ticker}' to both "
f"'{segment_map[ticker]}' and '{segment}'"
)
segment_map[ticker] = segment
logger.info(
"Loaded segment map %s: %d tickers, %d segments",
path,
len(segment_map),
len(set(segment_map.values())),
)
return segment_map
[docs]
def aggregate_to_segments(
weights: pa.Table,
returns: pa.Table,
segment_map: Mapping[str, str],
date_column: str = "date",
) -> tuple[pa.Table, pa.Table]:
"""
Aggregate one side's asset weights and returns into segments.
Parameters
----------
weights : pa.Table
Start-of-day weights: `date_column` plus one float64 column per ticker.
returns : pa.Table
Asset returns: `date_column` plus one float64 column per ticker. Must
contain every ticker in `weights`. Rows are matched to `weights` by date.
segment_map : Mapping[str, str]
Ticker to segment. Must cover every ticker in `weights`.
date_column : str, default ``"date"``
Date column name in both tables.
Returns
-------
tuple[pa.Table, pa.Table]
Segment weights and segment returns, both keyed by the dates of
`weights`, one float64 column per segment (sorted). A segment whose net
weight is zero (``abs(w) <= NET_WEIGHT_TOLERANCE``) on a date has a null
return that date, as does every segment on a date with no row in
`returns`. A net-zero segment is only accepted when its P&L
(sum of weight * return) is also ~0, so the null loses nothing.
Raises
------
DataValidationError
If a weighted ticker has no segment or no return column, the date
columns have different types, `returns` has duplicate dates, a weight
is NaN/null/infinite, a ticker has an infinite return on a date
where its weight is non-zero, or a segment's net weight is ~0 while
its P&L is not (``abs(P&L) > NET_PNL_TOLERANCE``; split its long
and short legs into separate segments). Null/NaN returns are allowed
and contribute 0; an infinite return on a date with zero weight is
ignored.
"""
tickers = [c for c in weights.column_names if c != date_column]
unmapped = sorted(t for t in tickers if t not in segment_map)
if unmapped:
raise DataValidationError(f"No segment for ticker(s): {', '.join(unmapped)}")
return_columns = set(returns.column_names)
unpriced = sorted(t for t in tickers if t not in return_columns)
if unpriced:
raise DataValidationError(f"No returns for weighted ticker(s): {', '.join(unpriced)}")
weights_date_type = weights.schema.field(date_column).type
returns_date_type = returns.schema.field(date_column).type
if weights_date_type != returns_date_type:
raise DataValidationError(
f"Date column types differ: weights {weights_date_type}, returns {returns_date_type}"
)
dates = weights.column(date_column)
date_values = dates.to_pylist()
return_row: dict = {}
for i, d in enumerate(returns.column(date_column).to_pylist()):
if d in return_row:
raise DataValidationError(f"Duplicate date in returns: {d}")
return_row[d] = i
rows = np.array([return_row.get(d, -1) for d in date_values], dtype=np.int64)
has_row = rows >= 0
n_dates = weights.num_rows
weight_matrix = np.zeros((n_dates, len(tickers)))
return_matrix = np.full((n_dates, len(tickers)), np.nan)
for j, ticker in enumerate(tickers):
weight_matrix[:, j] = np.asarray(weights.column(ticker).to_numpy(), dtype=np.float64)
column = np.asarray(returns.column(ticker).to_numpy(), dtype=np.float64)
return_matrix[has_row, j] = column[rows[has_row]]
non_finite_weight = ~np.isfinite(weight_matrix)
if non_finite_weight.any():
date_index, ticker_index = np.argwhere(non_finite_weight)[0]
raise DataValidationError(
f"Weight for '{tickers[ticker_index]}' on {date_values[date_index]} is not finite "
f"({weight_matrix[date_index, ticker_index]}); check the weights input."
)
# NaN means "no return" (contributes 0); +/-inf is a data error when the asset is held.
infinite = np.isinf(return_matrix)
bad_held = infinite & (weight_matrix != 0.0)
if bad_held.any():
date_index, ticker_index = np.argwhere(bad_held)[0]
bad_ticker = tickers[ticker_index]
bad_date = date_values[date_index]
bad_value = return_matrix[date_index, ticker_index]
raise DataValidationError(
f"Return for '{bad_ticker}' on {bad_date} is not finite ({'inf' if bad_value > 0 else '-inf'}); "
"check the price series for zeros or gaps."
)
# Held but unpriced on a date that does have a returns row: counts as 0, reported once.
unpriced_held = np.isnan(return_matrix) & (weight_matrix != 0.0) & has_row[:, None]
if unpriced_held.any():
date_index, ticker_index = np.argwhere(unpriced_held)[0]
log_diagnostic(
logger,
DiagnosticCode.SEGMENT_UNPRICED_HOLDINGS,
"Segment aggregation: %d weighted ticker-dates have no return and count as 0 (first: %s on %s).",
int(unpriced_held.sum()),
tickers[ticker_index],
date_values[date_index],
count=int(unpriced_held.sum()),
first_date=date_values[date_index],
details={"ticker": tickers[ticker_index]},
)
contributions = weight_matrix * np.where(np.isfinite(return_matrix), return_matrix, 0.0)
segment_columns: dict[str, list[int]] = {}
for j, ticker in enumerate(tickers):
segment_columns.setdefault(segment_map[ticker], []).append(j)
segment_weights = {date_column: dates}
segment_returns = {date_column: dates}
for segment in sorted(segment_columns):
idx = segment_columns[segment]
w_s = weight_matrix[:, idx].sum(axis=1)
c_s = contributions[:, idx].sum(axis=1)
net_zero = np.abs(w_s) <= NET_WEIGHT_TOLERANCE
lost_pnl = net_zero & (np.abs(c_s) > NET_PNL_TOLERANCE) & has_row
if lost_pnl.any():
i = int(np.flatnonzero(lost_pnl)[0])
raise DataValidationError(
f"Segment '{segment}' on {date_values[i]} has net weight ~0 but non-zero P&L ({c_s[i]:.6g}); "
"its return is undefined. Split long and short legs into separate segments."
)
defined = ~net_zero & has_row
with np.errstate(divide="ignore", invalid="ignore"):
r_s = np.where(defined, c_s / w_s, np.nan)
segment_weights[segment] = pa.array(w_s, type=pa.float64())
segment_returns[segment] = pa.array(r_s, type=pa.float64(), from_pandas=True)
return pa.table(segment_weights), pa.table(segment_returns)