"""
Conversion utilities for reshaping PyArrow tables into the format expected
by the Brinson-Fachler Arrow attribution engine.
Every operation stays in PyArrow (no pandas round trip).
"""
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
from kaxanuk.attribution_analysis.entities.portfolio_weights_arrow import PortfolioWeights
from kaxanuk.attribution_analysis.entities.returns_table import ReturnsTable
from kaxanuk.attribution_analysis.exceptions import DataLoadingError
WIDE_DATE_FORMATS = ("%Y-%m-%d", "%d/%m/%Y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S")
"""Formats tried, in order, for the date headers of a wide table; one format must parse every header."""
[docs]
def column_to_float64(column: pa.ChunkedArray | pa.Array) -> pa.ChunkedArray | pa.Array:
"""
Cast a numeric column to float64, decimals exactly.
Decimal columns go through a string cast so each value equals
``float(Decimal)`` (the correctly rounded double); a direct
decimal-to-float cast differs by 1 ulp in some cells.
Parameters
----------
column : pyarrow.ChunkedArray or pyarrow.Array
Numeric column (decimal, integer or floating).
Returns
-------
pyarrow.ChunkedArray or pyarrow.Array
The ``float64`` column, nulls kept.
Raises
------
pyarrow.ArrowInvalid, pyarrow.ArrowNotImplementedError
If the column cannot be cast to float64.
"""
if pa.types.is_decimal(column.type):
column = pc.cast(column, pa.string())
return pc.cast(column, pa.float64())
def _wide_to_float(column: pa.ChunkedArray | pa.Array) -> tuple[np.ndarray, np.ndarray]:
"""
Convert one date column of a wide table to float values and a null mask.
Decimal columns convert exactly (see :func:`column_to_float64`).
Parameters
----------
column : pyarrow.ChunkedArray or pyarrow.Array
One date column, one value per ticker.
Returns
-------
tuple[numpy.ndarray, numpy.ndarray]
``float64`` values (NaN where null) and a boolean null mask.
"""
column = column_to_float64(column)
nulls = np.asarray(column.is_null().to_numpy(zero_copy_only=False), dtype=bool)
values = np.asarray(pc.fill_null(column, np.nan).to_numpy(zero_copy_only=False), dtype=np.float64)
return values, nulls
def _reject_same_day_headers(names: list[str], days: pa.Array) -> None:
"""
Raise when two date headers fall on the same day.
After truncation to the day, ``"2026-05-21 00:00:00"`` and
``"2026-05-21 15:00:00"`` would become one date and merge two columns of
weights silently downstream.
Parameters
----------
names : list[str]
Date headers, as written in the file.
days : pyarrow.Array
The headers parsed and truncated to the day, aligned with `names`.
Raises
------
DataLoadingError
Naming the first repeated day and every header that falls on it.
"""
if len(pc.unique(days)) == len(days):
return
headers_by_day: dict[object, list[str]] = {}
for name, day in zip(names, days.to_pylist(), strict=True):
headers_by_day.setdefault(day, []).append(name)
day, headers = next((d, h) for d, h in headers_by_day.items() if len(h) > 1)
listed = ", ".join(f"'{header}'" for header in headers)
raise DataLoadingError(
f"Date headers fall on the same day {day:%Y-%m-%d}: {listed}; keep one column per day."
)
def _parse_wide_date_headers(names: list[str]) -> pa.Array:
"""
Parse the date headers of a wide table.
Each format of ``WIDE_DATE_FORMATS`` is tried on all headers at once.
The datetime forms (``"2026-05-20 00:00:00"``, ISO ``"T"``) are what
Excel date cells become, and are truncated to the day, as the date-range
validation does.
Parameters
----------
names : list[str]
Date column names of the wide table.
Returns
-------
pyarrow.Array
``timestamp("ns")`` dates at midnight, in header order.
Raises
------
DataLoadingError
If no single format parses every header (names the first header no
format parses), or if two headers fall on the same day.
"""
headers = pa.array(names, type=pa.string())
for date_format in WIDE_DATE_FORMATS:
try:
parsed = pc.strptime(headers, format=date_format, unit="ns")
except (pa.ArrowInvalid, pa.ArrowNotImplementedError, ValueError):
continue
days = pc.floor_temporal(parsed, unit="day")
_reject_same_day_headers(names, days)
return days
def parses(name: str) -> bool:
single = pa.array([name], type=pa.string())
return any(
pc.strptime(single, format=date_format, unit="ns", error_is_null=True)[0].is_valid
for date_format in WIDE_DATE_FORMATS
)
bad = next((name for name in names if not parses(name)), None)
accepted = ", ".join(WIDE_DATE_FORMATS)
if bad is None:
raise DataLoadingError(f"Date headers mix formats; use one of: {accepted}.")
raise DataLoadingError(f"Date header '{bad}' is not a date; accepted formats: {accepted}.")
def _transpose_wide(table: pa.Table) -> tuple[pa.Array, list[str], dict[str, pa.Array]]:
"""
Transpose a wide ``[Ticker, date1, date2, ...]`` table into per-ticker arrays.
Parameters
----------
table : pyarrow.Table
Wide-format table, one row per ticker and one column per date. Date
column names are parsed with the first of ``WIDE_DATE_FORMATS`` that
parses them all.
Returns
-------
tuple[pyarrow.Array, list[str], dict[str, pyarrow.Array]]
Parsed ``timestamp("ns")`` dates, tickers in row order, and one
``float64`` array per ticker (nulls kept; for a duplicated ticker the
last row's values win).
"""
tickers = table.column("Ticker").to_pylist()
date_columns = [name for name in table.column_names if name != "Ticker"]
dates = _parse_wide_date_headers(date_columns)
n_dates, n_tickers = len(date_columns), len(tickers)
values = np.full((n_dates, n_tickers), np.nan)
nulls = np.ones((n_dates, n_tickers), dtype=bool)
for d, name in enumerate(date_columns):
values[d], nulls[d] = _wide_to_float(table.column(name))
asset_arrays: dict[str, pa.Array] = {}
for i, ticker in enumerate(tickers):
asset_arrays[ticker] = pa.array(values[:, i], type=pa.float64(), mask=nulls[:, i])
return dates, tickers, asset_arrays
[docs]
def portfolio_table_to_arrow(table: pa.Table) -> PortfolioWeights:
"""
Transpose a wide portfolio/benchmark weights table into attribution format.
This is the PyArrow equivalent of ``portfolio_table_to_pandas``, which
does ``set_index("Ticker").T``.
Parameters
----------
table : pyarrow.Table
Wide-format weights table with columns ``[Ticker, date1, date2,
...]``, one row per ticker and one column per date. Date column
names are parsed with the first of ``WIDE_DATE_FORMATS`` that
parses them all (``DataLoadingError`` otherwise).
Returns
-------
PortfolioWeights
Wrapper around a table with columns ``[date, asset1, asset2,
...]``, i.e. one row per date and one column per ticker.
"""
dates, tickers, asset_arrays = _transpose_wide(table)
return PortfolioWeights(
table=pa.table([dates, *(asset_arrays[t] for t in tickers)], names=["date", *tickers])
)
[docs]
def compute_returns_from_prices_arrow(
prices_table: pa.Table,
date_column: str,
) -> ReturnsTable:
"""
Compute percentage returns from a prices table.
Equivalent to ``prices_df.pct_change(fill_method=None)`` — the first
row is kept with null values so the date range stays aligned with the
original prices table (and therefore with the weights tables).
Parameters
----------
prices_table : pyarrow.Table
Prices table containing a date column and one or more numeric
asset price columns.
date_column : str
Name of the column in `prices_table` containing the dates. It's
passed through unchanged and always renamed to ``"date"`` in the
output, regardless of its original name.
Returns
-------
ReturnsTable
Wrapper around a table with the same columns and row count as
`prices_table`, where each asset column holds period-over-period
percentage returns and the first row is null.
"""
date_col = prices_table.column(date_column)
result_columns = [date_col]
result_names = ["date"]
for name in prices_table.column_names:
if name == date_column:
continue
col = prices_table.column(name)
previous = col.slice(0, len(col) - 1)
current = col.slice(1)
returns = pc.divide(
pc.subtract(current, previous),
previous
)
if isinstance(returns, pa.ChunkedArray):
returns = returns.combine_chunks()
first_null = pa.array([None], type=pa.float64())
returns_with_null = pa.concat_arrays([first_null, returns])
result_columns.append(returns_with_null)
result_names.append(name)
return ReturnsTable(table=pa.table(result_columns, names=result_names))
[docs]
def returns_table_to_arrow(table: pa.Table) -> ReturnsTable:
"""
Transpose a wide returns table into attribution format.
Same transpose logic as :func:`portfolio_table_to_arrow`, but wraps
the result in a :class:`ReturnsTable` (no weight constraints).
Parameters
----------
table : pyarrow.Table
Wide-format returns table with columns ``[Ticker, date1, date2,
...]``, one row per ticker and one column per date. Date column
names are parsed with the first of ``WIDE_DATE_FORMATS`` that
parses them all (``DataLoadingError`` otherwise).
Returns
-------
ReturnsTable
Wrapper around a table with columns ``[date, asset1, asset2,
...]``, i.e. one row per date and one column per ticker.
"""
dates, tickers, asset_arrays = _transpose_wide(table)
return ReturnsTable(
table=pa.table([dates, *(asset_arrays[t] for t in tickers)], names=["date", *tickers])
)
def _filter_arrow_table_by_date_range(
table: pa.Table,
start: pa.Scalar,
end: pa.Scalar,
date_col: str = "date",
) -> pa.Table:
"""
Filter a table to rows whose date column falls within an inclusive range.
Parameters
----------
table : pyarrow.Table
Table to filter. Must contain a column named `date_col`.
start : pyarrow.Scalar
Earliest date to include (inclusive). Must be comparable to the
`date_col` column's type (e.g. a ``timestamp("ns")`` scalar).
end : pyarrow.Scalar
Latest date to include (inclusive). Must be comparable to the
`date_col` column's type.
date_col : str, default "date"
Name of the date column to filter on.
Returns
-------
pyarrow.Table
A new table containing only the rows where `date_col` is between
`start` and `end`, inclusive.
"""
col = table.column(date_col)
mask = pc.and_(pc.greater_equal(col, start), pc.less_equal(col, end))
return table.filter(mask)