Source code for kaxanuk.attribution_analysis.modules.weights_normalization
"""
Weight normalization for attribution inputs.
Brinson-Fachler needs each side's weights to sum to 1 on every date. Files
written with truncated decimals, or books that hold cash implicitly, sum
below 1; the remainder is cash. A book above 1 is leveraged, which F1 does
not attribute.
The over-allocation guard applies to NET weights (the plain sum per date).
Long/short books pass as long as the net sum is at most 1 (e.g. +1.3 / -0.5
nets to 0.8 and gets cash = 0.2); gross leverage is not checked.
"""
import logging
import numpy as np
import pyarrow as pa
from kaxanuk.attribution_analysis.entities.attribution_options import WEIGHT_SUM_TOLERANCE
from kaxanuk.attribution_analysis.entities.portfolio_weights_arrow import DATE_COLUMN, PortfolioWeights
from kaxanuk.attribution_analysis.entities.returns_table import ReturnsTable
from kaxanuk.attribution_analysis.exceptions import PortfolioValidationError
logger = logging.getLogger(__name__)
[docs]
def fill_implied_cash(weights: PortfolioWeights, cash_ticker: str) -> PortfolioWeights:
"""
Top up each date's weights to 1 with `cash_ticker`.
The over-allocation guard is on NET weights: negative (short) weights offset
long ones, so a long/short book such as +1.3 / -0.5 passes and receives
cash = 1 - net. Gross leverage is not checked.
Parameters
----------
weights : PortfolioWeights
Start-of-day weights.
cash_ticker : str
Column that receives the remainder. Created if absent, added to if present.
Returns
-------
PortfolioWeights
`weights` itself when every date already sums to 1 within
``WEIGHT_SUM_TOLERANCE``; otherwise a new entity with the cash column.
Raises
------
PortfolioValidationError
If any weight is NaN or infinite, or if any date's net weights sum above
``1 + WEIGHT_SUM_TOLERANCE``.
"""
table = weights.table
assets = weights.asset_names
if assets:
matrix = np.column_stack(
[np.asarray(table.column(a).to_numpy(), dtype=np.float64) for a in assets]
)
non_finite = np.argwhere(~np.isfinite(matrix))
if non_finite.size:
row, col = (int(v) for v in non_finite[0])
raise PortfolioValidationError(
f"Non-finite weight for '{assets[col]}' on {table.column(DATE_COLUMN)[row].as_py()} "
f"({len(non_finite)} non-finite weights in total)"
)
sums = matrix.sum(axis=1)
else:
sums = np.zeros(table.num_rows)
over = np.flatnonzero(sums > 1.0 + WEIGHT_SUM_TOLERANCE)
if over.size:
i = int(over[0])
raise PortfolioValidationError(
f"Weights on {table.column(DATE_COLUMN)[i].as_py()} sum to {sums[i]:.8f}, above 1 "
f"({over.size} dates in total); leveraged books are not supported"
)
remainder = 1.0 - sums
remainder[np.abs(remainder) <= WEIGHT_SUM_TOLERANCE] = 0.0
if not remainder.any():
return weights
logger.info(
"Adding implied cash to '%s' on %d of %d dates (largest %.6f)",
cash_ticker, int(np.count_nonzero(remainder)), table.num_rows, float(remainder.max()),
)
if cash_ticker in assets:
position = table.column_names.index(cash_ticker)
current = np.asarray(table.column(cash_ticker).to_numpy(), dtype=np.float64)
table = table.set_column(position, cash_ticker, pa.array(current + remainder, type=pa.float64()))
else:
table = table.append_column(cash_ticker, pa.array(remainder, type=pa.float64()))
return PortfolioWeights(table=table)
[docs]
def append_zero_return_column(returns: ReturnsTable, ticker: str) -> ReturnsTable:
"""
Add a column of zero returns for `ticker` unless it already exists.
A row on which every other asset return is null (the first price date,
where ``pct_change`` has no prior price) gets a null cash return too, so
that date stays without a portfolio return instead of looking flat.
Parameters
----------
returns : ReturnsTable
Asset returns.
ticker : str
Column to add (the cash ticker).
Returns
-------
ReturnsTable
`returns` itself if the column exists, otherwise a new entity.
"""
table = returns.table
if ticker in table.column_names:
return returns
assets = [name for name in table.column_names if name != DATE_COLUMN]
no_return = np.zeros(table.num_rows, dtype=bool)
if assets:
no_return = np.logical_and.reduce([table.column(a).is_null().to_numpy(zero_copy_only=False) for a in assets])
cash = pa.array(np.zeros(table.num_rows), type=pa.float64(), mask=no_return)
return ReturnsTable(table=table.append_column(ticker, cash))