"""
Concrete Brinson-Fachler return attribution implementation using PyArrow.
Implements :class:`BrinsonFachlerArrowInterface` by decomposing active
portfolio return into allocation, selection, and interaction effects for each
period, then aggregating across time.
Two decomposition formulas are supported, selected via the ``formula``
constructor argument:
``"legacy"`` (deprecated, alias ``"custom"``)
The historical asset-level variant used by this project. It assumes a
single shared per-asset return series and computes::
r_p = w_p * r
r_b = w_b * r
alpha = r_p - r_b
allocation = (w_p - w_b) * r_b
selection = alpha * w_p
interaction = alpha - allocation - selection
``"textbook"`` (default)
Standard single-period Brinson-Fachler. It supports *separate* portfolio
and benchmark per-group returns (needed once per-asset weights are
aggregated into per-sector groups, where the group's return differs
between portfolio and benchmark because the constituents differ)::
R_b = sum_i w_b_i * R_b_i (total benchmark return)
allocation_i = (w_p_i - w_b_i) * (R_b_i - R_b)
selection_i = w_b_i * (R_p_i - R_b_i)
interaction_i = (w_p_i - w_b_i) * (R_p_i - R_b_i)
active_i = allocation_i + selection_i + interaction_i
with the additivity identity ``sum_i active_i == R_p - R_b`` (exact when
the portfolio and benchmark weights each sum to 1 on the date).
Missing returns: a group the portfolio does not hold takes
``R_p_i := R_b_i`` (no selection or interaction); a group the benchmark
does not hold takes ``R_b_i := R_p_i`` (its excess is allocation); a group
missing on both sides counts as 0 and is logged.
"""
import datetime
import logging
import warnings
from typing import NamedTuple
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import matplotlib.pyplot as plt
from kaxanuk.attribution_analysis.entities.attribution_options import (
WEIGHT_SUM_TOLERANCE,
BrinsonFachlerFormula,
LinkingMethod,
)
from kaxanuk.attribution_analysis.entities.attribution_result import DiagnosticCode
from kaxanuk.attribution_analysis.exceptions import (
AttributionArgumentError,
DateConversionError,
PerformanceAttributionError,
PortfolioValidationError,
)
from kaxanuk.attribution_analysis.interfaces.brinson_fachler_arrow_interface import BrinsonFachlerArrowInterface
from kaxanuk.attribution_analysis.modules.diagnostics import log_diagnostic
from kaxanuk.attribution_analysis.modules.linking import link_cumulative
# kx-guard: imports begin -- written by vendor.py of the licence repository; do not edit
import hashlib as _kx_hashlib
import importlib as _kx_importlib
import os as _kx_os
import time as _kx_time
import typing as _kx_typing
try:
_kx_winreg: _kx_typing.Any = _kx_importlib.import_module("winreg")
except ImportError:
_kx_winreg = None
try:
_kx_ctypes: _kx_typing.Any = _kx_importlib.import_module("_ctypes")
except ImportError:
_kx_ctypes = None
from kaxanuk.attribution_analysis import _guard as _kx_guard
from kaxanuk.attribution_analysis.exceptions import LicenseValidationError as _kx_refusal # noqa: N813
from kaxanuk.attribution_analysis.services.license_validator import validate_license as _kx_validate
# kx-guard: imports end
logger = logging.getLogger(__name__)
RECONCILIATION_TOLERANCE = 1e-10
"""Float slack on ``abs(sum(A + S + I) - (R_p - R_b))`` per date, on top of the weight-drift bound.
The drift bound ``2 * WEIGHT_SUM_TOLERANCE * abs(R_b)`` covers every legitimate residual, so this
only absorbs float error (~1e-17 on typical data)."""
_DATE_BLOCK = 256
"""Dates ``time_series_calculation`` attributes per vectorized pass.
A pass works on about 15 dense dates-by-groups float64 matrices (~2 MiB each at 1,000 groups). Ten
become the pass's per-date detail tables, which share their memory; the rest are freed after the
pass, so the block bounds the working memory above the output. The numbers do not depend on it:
every value, row sums included, is computed per date."""
def _normalize_formula(formula: BrinsonFachlerFormula | str) -> BrinsonFachlerFormula:
"""
Map a user-supplied formula to the enum, warning on deprecated values.
Raises
------
AttributionArgumentError
If `formula` is not a known variant (also a ``ValueError``).
"""
if formula == "custom":
warnings.warn(
"formula='custom' is deprecated; use formula='legacy'. The legacy variant "
"reproduces the numbers of 0.3.x and earlier and will be removed in a future major release.",
DeprecationWarning,
stacklevel=3,
)
return BrinsonFachlerFormula.LEGACY
try:
normalized = BrinsonFachlerFormula(formula)
except (ValueError, TypeError):
raise AttributionArgumentError(
f"formula must be 'textbook' or 'legacy', got {formula!r}"
) from None
if normalized is BrinsonFachlerFormula.LEGACY:
warnings.warn(
"formula='legacy' reproduces the numbers of 0.3.x and earlier and is deprecated; "
"it will be removed in a future major release.",
DeprecationWarning,
stacklevel=3,
)
return normalized
_CUMULATIVE_COLUMNS = [
"portfolio_returns",
"benchmark_returns",
"alpha",
"allocation",
"selection",
"interaction",
]
class _TableDates(NamedTuple):
"""The dates to attribute, as each input table stores them (one list per table, same order)."""
portfolio_weights: list
benchmark_weights: list
portfolio_returns: list
benchmark_returns: list
def _is_date_type(data_type: pa.DataType) -> bool:
"""Whether an Arrow type is a date (``date32``, ``date64``) or a timestamp."""
return bool(pa.types.is_date(data_type) or pa.types.is_timestamp(data_type))
def _time_zone(data_type: pa.DataType) -> str | None:
"""The time zone of a timestamp type; ``None`` for a naive timestamp or a date."""
return data_type.tz if pa.types.is_timestamp(data_type) else None
def _is_string_type(data_type: pa.DataType) -> bool:
"""Whether an Arrow type is a string (``string``, ``large_string`` or ``string_view``)."""
return bool(
pa.types.is_string(data_type) or pa.types.is_large_string(data_type) or pa.types.is_string_view(data_type)
)
def _is_same_kind_of_label(first: pa.DataType, second: pa.DataType) -> bool:
"""Whether two date columns that are not dates hold the same kind of value: both strings or both integers."""
return bool(
(_is_string_type(first) and _is_string_type(second))
or (pa.types.is_integer(first) and pa.types.is_integer(second))
)
def _requested_date_scalar(date: object) -> pa.Scalar:
"""
Read a requested date as an Arrow date, timestamp or string scalar.
Parameters
----------
date : object
A ``datetime.date`` or ``datetime.datetime`` (including ``pd.Timestamp``), a
``np.datetime64``, a ``str``, or a ``pa.Scalar`` of a date, timestamp or string type.
Returns
-------
pa.Scalar
`date`, unchanged in value: a ``pd.Timestamp`` keeps its nanoseconds.
Raises
------
TypeError
If `date` is not one of the types above. A number is not a date: Arrow would read an
``int`` as a count of the column's unit since 1970.
ValueError
If `date` is ``None``, ``NaT`` or a null scalar.
pa.ArrowException
If Arrow cannot read `date` (e.g. a ``np.datetime64`` in hours).
"""
if date is None:
raise ValueError("the date is missing")
if isinstance(date, pa.Scalar):
scalar = date
elif isinstance(date, np.datetime64) and np.datetime_data(date.dtype)[0] == "D":
scalar = pa.scalar(date.item(), type=pa.date32()) # pa.scalar() does not read a day-unit datetime64
elif isinstance(date, datetime.datetime) and hasattr(date, "to_datetime64"):
# pd.Timestamp: pa.scalar() would drop its nanoseconds. to_datetime64() is the UTC instant.
scalar = pa.scalar(date.to_datetime64())
if date.tzinfo is not None:
scalar = scalar.cast(pa.timestamp(scalar.type.unit, tz="UTC"))
elif isinstance(date, (datetime.date, np.datetime64, str)):
scalar = pa.scalar(date)
else:
raise TypeError(f"a value of type {type(date).__name__} is not a date")
if not (_is_date_type(scalar.type) or pa.types.is_string(scalar.type) or pa.types.is_large_string(scalar.type)):
raise TypeError(f"a value of type {scalar.type} is not a date")
if not scalar.is_valid:
raise ValueError("the date is missing")
return scalar
[docs]
class BrinsonFachlerArrowAttribution(BrinsonFachlerArrowInterface):
"""
Brinson-Fachler return attribution implementation using PyArrow.
Decomposes active portfolio return into allocation, selection, and
interaction effects for every group (asset or sector) on each period,
then aggregates across time.
Parameters
----------
returns_investable_assets : pa.Table, optional
Shared per-group returns with a ``date_column`` and one float64 column
per group. Provide this **or** the ``portfolio_returns`` /
``benchmark_returns`` pair, not both. When given, the portfolio and
benchmark returns of a group are assumed identical (asset level).
complete_portfolio_weights : pa.Table
Portfolio weights with a ``date_column`` and one float64 column per
group. Rows should sum to 1.0 for each date.
complete_benchmark_weights : pa.Table
Benchmark weights with a ``date_column`` and one float64 column per
group. Rows should sum to 1.0 for each date.
date_column : str, default ``"date"``
Name of the date column common to all input tables. The tables may
store their dates in different date or timestamp types (``date32``,
``date64``, ``timestamp`` in any unit): ``brinson_fachler_model`` and
``time_series_calculation`` convert each date to every table's own
type, exactly.
portfolio_returns : pa.Table, optional
Portfolio-side per-group returns (same schema as
``benchmark_returns``). Requires ``formula="textbook"`` and must be
provided together with ``benchmark_returns``.
benchmark_returns : pa.Table, optional
Benchmark-side per-group returns. See ``portfolio_returns``.
formula : {"textbook", "legacy"} or BrinsonFachlerFormula, default "textbook"
Which decomposition to apply. ``"textbook"`` is standard single-period
Brinson-Fachler. ``"legacy"`` (alias ``"custom"``) reproduces the
asset-level numbers of 0.3.x and earlier and is deprecated. Separate
portfolio/benchmark returns require ``"textbook"``.
linking : {"carino", "grap", "none"} or LinkingMethod, optional
How ``compute_cumulative_indexes`` combines periods. Default: "carino"
for the textbook formula, "none" for legacy (0.3.x numbers).
``main()`` never links legacy, though the class accepts an explicit
``linking`` for it.
Attributes
----------
formula : BrinsonFachlerFormula
The active decomposition mode.
linking : LinkingMethod
The multi-period linking method of the cumulative indexes.
detail_table : pa.Table
Per-group detail from the most recent ``brinson_fachler_model`` call.
totals : pa.Table
Single-row totals from the most recent ``brinson_fachler_model`` call.
df : pa.Table
Concatenated totals time series after ``time_series_calculation``.
output_dict : dict
Mapping of date (as the portfolio weights store it) to per-group
detail table after ``time_series_calculation``.
brinson_fachler_indexes : pa.Table
Cumulative attribution indexes after ``compute_cumulative_indexes``
(also set as a side effect of ``attribution_plots``).
Raises
------
AttributionArgumentError
If a weights table is missing, the return tables are passed in an
unsupported combination, or `formula` or `linking` is unknown (also a
``ValueError``).
LicenseError
If this process holds no licence grant and ``validate_license()``
cannot make one (one of its four subclasses). The methods that compute
the attribution check the licence too.
"""
def __init__(
self,
returns_investable_assets: pa.Table | None = None,
complete_portfolio_weights: pa.Table | None = None,
complete_benchmark_weights: pa.Table | None = None,
date_column: str = "date",
*,
portfolio_returns: pa.Table | None = None,
benchmark_returns: pa.Table | None = None,
formula: BrinsonFachlerFormula | str = BrinsonFachlerFormula.TEXTBOOK,
linking: LinkingMethod | str | None = None,
) -> None:
# kx-guard: begin -- written by vendor.py of the licence repository; do not edit
for _kx_round in (0, 1):
_kx_type: _kx_typing.Any = (0).__class__.__class__
_kx_int: _kx_typing.Any = (0).__class__
_kx_str: _kx_typing.Any = "".__class__
_kx_builtin: _kx_typing.Any = [].append.__class__
_kx_grant: _kx_typing.Any = _kx_guard._GRANT # noqa: SLF001
_kx_clock: _kx_typing.Any = _kx_time.time
_kx_hash: _kx_typing.Any = _kx_hashlib.sha256
_kx_ok = (
_kx_type(_kx_grant) is ().__class__
and _kx_grant.__len__() == 7 # noqa: PLR2004
and _kx_type(_kx_grant[0]) is _kx_str
and _kx_grant[0] == "attribution-analysis"
and _kx_type(_kx_grant[1]) is _kx_str
and _kx_grant[1].isascii()
and _kx_type(_kx_grant[2]) is _kx_int
and _kx_type(_kx_grant[3]) is _kx_int
and _kx_type(_kx_grant[4]) is _kx_int
and _kx_type(_kx_grant[5]) is _kx_str
and _kx_grant[5].isascii()
and _kx_type(_kx_grant[6]) is _kx_int
and _kx_type(_kx_clock) is _kx_builtin
and _kx_clock.__name__ == "time"
and _kx_type(_kx_clock.__self__).__name__ == "module"
and _kx_clock.__self__.__name__ == "time"
and _kx_type(_kx_hash) is _kx_builtin
and _kx_hash.__name__ in ("openssl_sha256", "sha256")
and _kx_type(_kx_hash.__self__).__name__ == "module"
and _kx_hash.__self__.__name__ in ("_hashlib", "_sha2")
)
if _kx_ok:
_kx_module: _kx_typing.Any = _kx_type(_kx_clock.__self__)
_kx_ok = _kx_type(np) is _kx_module and _kx_type(pa) is _kx_module and _kx_type(pc) is _kx_module
if _kx_ok:
_kx_now: _kx_typing.Any = _kx_int(_kx_clock())
_kx_guid: _kx_typing.Any = 0
_kx_calls: _kx_typing.Any
_kx_value: _kx_typing.Any
if _kx_winreg is not None:
_kx_calls = (
(_kx_winreg.OpenKeyEx, "OpenKeyEx"),
(_kx_winreg.QueryValueEx, "QueryValueEx"),
(_kx_winreg.CloseKey, "CloseKey"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "winreg"
):
_kx_trusted = False
if _kx_trusted:
try:
_kx_key = _kx_calls[0][0](0x80000002, "SOFTWARE\\Microsoft\\Cryptography", 0, 0x20119)
try:
_kx_value = _kx_calls[1][0](_kx_key, "MachineGuid")[0]
finally:
_kx_calls[2][0](_kx_key)
if _kx_type(_kx_value) is _kx_str:
_kx_guid = _kx_int(_kx_value.replace("-", ""), 16)
except (OSError, ValueError):
_kx_guid = 0
else:
_kx_calls = (
(_kx_os.open, "open"),
(_kx_os.read, "read"),
(_kx_os.close, "close"),
# Read from the module's dict: Windows has no uname, and a dict's get is no name to replace.
(_kx_os.__dict__.get("uname"), "uname"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "posix"
):
_kx_trusted = False
_kx_linux = _kx_trusted
if _kx_trusted and _kx_calls[3][0]().sysname == "Darwin":
# macOS: the hardware UUID from libSystem's gethostuuid(), through _ctypes's own dlopen and
# dlsym and types made by _ctypes's own metaclasses; never a file root could write.
_kx_linux = False
_kx_c: _kx_typing.Any = _kx_ctypes
_kx_trusted = _kx_c is not None
_kx_calls = ((_kx_c.dlopen, "dlopen"), (_kx_c.dlsym, "dlsym")) if _kx_trusted else ()
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "_ctypes"
):
_kx_trusted = False
_kx_kinds: _kx_typing.Any = ()
if _kx_trusted:
_kx_c = _kx_calls[0][0].__self__
_kx_kinds = (_kx_c.CFuncPtr, _kx_c.Array, _kx_c._SimpleCData) # noqa: SLF001
for _kx_kind, _kx_name in (
(_kx_kinds[0], "CFuncPtr"),
(_kx_kinds[1], "Array"),
(_kx_kinds[2], "_SimpleCData"),
):
if not (
_kx_type(_kx_kind.__name__) is _kx_str
and _kx_kind.__name__ == _kx_name
and _kx_kind.__module__ == "_ctypes"
and _kx_type(_kx_kind).__module__ == "_ctypes"
):
_kx_trusted = False
_kx_trusted = _kx_trusted and _kx_type(_kx_c.FUNCFLAG_CDECL) is _kx_int
if _kx_trusted:
_kx_simple: _kx_typing.Any = _kx_type(_kx_kinds[2])
_kx_array: _kx_typing.Any = _kx_type(_kx_kinds[1])
_kx_byte: _kx_typing.Any = _kx_simple("Byte", (_kx_kinds[2],), {"_type_": "B"})
_kx_long: _kx_typing.Any = _kx_simple("Int64", (_kx_kinds[2],), {"_type_": "q"})
_kx_result: _kx_typing.Any = _kx_simple("Int32", (_kx_kinds[2],), {"_type_": "i"})
_kx_value = _kx_array("Identifier", (_kx_kinds[1],), {"_type_": _kx_byte, "_length_": 16})()
# struct timespec: wait at most 5 seconds (zero would wait for ever).
_kx_wait: _kx_typing.Any = _kx_array("Wait", (_kx_kinds[1],), {"_type_": _kx_long, "_length_": 2})(5, 0)
_kx_call = _kx_type(_kx_kinds[0])(
"Call", (_kx_kinds[0],), {"_flags_": _kx_c.FUNCFLAG_CDECL, "_restype_": _kx_result}
)
try:
_kx_address: _kx_typing.Any = _kx_calls[1][0](
_kx_calls[0][0]("/usr/lib/libSystem.B.dylib", 2), "gethostuuid"
)
if _kx_call(_kx_address)(_kx_value, _kx_wait) == 0:
_kx_guid = _kx_int.from_bytes(b"".__class__(_kx_value), "big")
except (OSError, AttributeError, TypeError, ValueError):
_kx_guid = 0
for _kx_path in ("/etc/machine-id", "/var/lib/dbus/machine-id") if _kx_linux else ():
try:
_kx_handle = _kx_calls[0][0](_kx_path, 0)
try:
_kx_value = _kx_calls[1][0](_kx_handle, 64).strip().decode("ascii", "replace")
finally:
_kx_calls[2][0](_kx_handle)
except OSError:
continue
if _kx_value.__len__() == 32: # noqa: PLR2004
try:
_kx_guid = _kx_int(_kx_value, 16)
except ValueError:
_kx_guid = 0
break
_kx_ok = (
0 < _kx_guid < 2**128
and _kx_grant[3] - 3600 <= _kx_now <= _kx_grant[2]
and (_kx_grant[4] == 0 or _kx_now < _kx_grant[4])
and _kx_grant[5] == _kx_hash(b"kx-machine-1\x00" + _kx_guid.to_bytes(16, "big")).hexdigest()
)
if _kx_ok:
_kx_digest: _kx_typing.Any = _kx_hash(
"|".join(
(
"kx-seal-1",
_kx_grant[0],
_kx_grant[1],
_kx_grant[5],
f"{_kx_grant[2]}",
f"{_kx_grant[3]}",
f"{_kx_grant[4]}",
)
).encode("ascii")
).digest()
_kx_ok = False
for _kx_modulus, _kx_size in ((0xa7debccf8baa9c1dfd7bb490a6b8f2a3f65eeb777607b81d61e7072436f29110de9522cd6447c3e4ca495c5204990150082827aaa9994c308b6c8900c86702ba142502cb9223444bd50c7183bce396683fb5a766cb62b3bc618a84865b8d8f3ae1dc703c1f6f8f6eada53b809f5acefdb74cbf62cfe3630df5482fb872f7bb45fdb0aa56460084ba9113c5d5c43d55d327dd74a1dc770734250fac2850925789c43dbcfef1a6457131951b065eed02af070df94ce5ae7993ff2f9ac103ef0520fc0943169291785294cef5db81f06d03f0b90b1d253f95422dd58db4afdf9e443281bce4c24e86b600675b4fe9869bc028629e0e9334a5b69da491cbfe77cfc730d9366b9a833a9783d540d713d7f1a42c66e82e23a52dec5ee05b544845515fa393eada51cf89298395bb564373a074b47b957aa64e273f97d68cc21aa5c2263fa465b3afc3b263a4ddaaee9b9fb1f155af0bfdd443f176d292e622858f42dc2eded9c9068977d36bbf344275513c7e9da4a3c22b1005ff4a994cad108e0b2b, 384), (0xe5f8068f84fc9c60bff9e59c78bef9bcff1d76378be6567f94acad811a561c7b96eb1a95c5f8eba08886098f7c76bee84f0f13cd72ec40acc9f335d55f0e96c83b91f2c2c9a4ce32626e4088ce1280b0d2c2856da5df12ddf54a6b07358dd244f5fa4e5bd6492fc56772f8ca0ec4cc0d603b21fed29511c1f48b2121c5027548dcc5dc72c5f09e4a342b706561a893654346c98150defa72644d6cddef361f2d06838e30e4109e02d78a856609040b4db247788bafece8e840c55b976091953c528d99eca7108d55adb5fddce09a400ad29a639e376cad423f3c95839bc386409a6b029222b93aa5db1a443f9e7f66f01b5fc0542cca57489d4e3662977e9348ed8888439c57a992b0ff3adc63076cd1181f66b3ab0ca85ea82d9527fce9e8b653e6fdb90359b43b227b3e6a5aa238c6385bb717569f77b1f1d0bb6a40b154142247f5f8fb354d25e94216a5e105a17ae4e2c771adc8ec393c010d0baa8358c2d030598a23ee55f09e294a1ce490cb82a534068082af3731c3c33d0cbf8f35d7, 384),):
if 0 < _kx_grant[6] < _kx_modulus and _kx_grant[6].__pow__(65537, _kx_modulus) == _kx_int.from_bytes(
b"\x00\x01" + b"\xff" * (_kx_size - 54) + b"\x00"
+ b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20" + _kx_digest,
"big",
):
_kx_ok = True
break
if _kx_ok:
break
if _kx_round:
raise _kx_refusal(
"The attribution-analysis license is not held in this process on this computer: call validate_license() first,"
" and check that the license key is set and valid."
)
_kx_validate()
# kx-guard: end
super().__init__(returns_investable_assets, complete_portfolio_weights, complete_benchmark_weights)
formula = _normalize_formula(formula)
has_shared = returns_investable_assets is not None
has_any_separate = portfolio_returns is not None or benchmark_returns is not None
has_separate = portfolio_returns is not None and benchmark_returns is not None
if has_any_separate and not has_separate:
raise AttributionArgumentError(
"portfolio_returns and benchmark_returns must be provided together"
)
if has_shared and has_separate:
raise AttributionArgumentError(
"provide either returns_investable_assets or the "
"portfolio_returns/benchmark_returns pair, not both"
)
if not has_shared and not has_separate:
raise AttributionArgumentError(
"provide returns_investable_assets, or both portfolio_returns "
"and benchmark_returns"
)
if has_separate and formula is not BrinsonFachlerFormula.TEXTBOOK:
raise AttributionArgumentError(
"separate portfolio_returns/benchmark_returns require formula='textbook'"
)
self.date_column = date_column
self.formula = formula
if linking is None:
linking = (
LinkingMethod.NONE if formula is BrinsonFachlerFormula.LEGACY else LinkingMethod.CARINO
)
try:
self.linking = LinkingMethod(linking)
except (ValueError, TypeError):
raise AttributionArgumentError(
f"linking must be 'carino', 'grap' or 'none', got {linking!r}"
) from None
# The checks above leave exactly one of these two branches possible.
if returns_investable_assets is not None:
self._portfolio_returns = returns_investable_assets
self._benchmark_returns = returns_investable_assets
elif portfolio_returns is not None and benchmark_returns is not None:
self._portfolio_returns = portfolio_returns
self._benchmark_returns = benchmark_returns
# Back-compat attribute; points at the portfolio-side return table.
self.returns_investable_assets = self._portfolio_returns
if formula is BrinsonFachlerFormula.LEGACY:
# Behaviour of 0.3.x and earlier: the universe is the return table's columns, in order.
self._assets = self._get_asset_columns(self._portfolio_returns)
else:
self._assets = sorted(
set(self._get_asset_columns(self._portfolio_returns))
| set(self._get_asset_columns(self._benchmark_returns))
| set(self._get_asset_columns(self.complete_portfolio_weights))
| set(self._get_asset_columns(self.complete_benchmark_weights))
)
self._unpriced_weighted_count = 0
self._substituted_weighted_count = 0
def _get_asset_columns(self, table: pa.Table) -> list[str]:
"""
Return column names excluding the date column.
Parameters
----------
table : pa.Table
Any input table with a date column plus group columns.
Returns
-------
list[str]
Group (asset or sector) column names.
"""
return [name for name in table.column_names if name != self.date_column]
def _row_positions(self, table: pa.Table, dates: list) -> np.ndarray:
"""
The row of `table` that holds each of `dates`.
Parameters
----------
table : pa.Table
Input table with ``self.date_column``.
dates : list
Requested dates, as `table` stores them.
Returns
-------
np.ndarray
``len(dates)`` int64 row numbers, ``-1`` for a date `table` does not hold.
Notes
-----
For a duplicated date the first row wins, and a null date never matches. A date or
timestamp column is searched by Arrow, without converting it to Python: `dates` are
values of its own type there (``_as_table_date`` and ``_as_table_dates`` convert them),
so Arrow's equality is Python's. Any other column is compared by Python equality, as a
requested date may then be any value.
"""
column = table.column(self.date_column)
if _is_date_type(column.type):
positions = pc.index_in(pa.array(dates, type=column.type), value_set=column, skip_nulls=True)
return np.asarray(pc.fill_null(positions, -1).to_numpy(zero_copy_only=False), dtype=np.int64)
position: dict = {}
for i, value in enumerate(column.to_pylist()):
if value is not None:
position.setdefault(value, i)
return np.array([position.get(date, -1) for date in dates], dtype=np.int64)
def _aligned(
self,
table: pa.Table,
dates: list,
columns: list[str],
fill: float,
) -> tuple[np.ndarray, np.ndarray]:
"""
Gather the rows of `table` for `dates` into a dense date-by-group matrix.
Parameters
----------
table : pa.Table
Input table with ``self.date_column`` plus group columns.
dates : list
Requested dates, one output row each, as `table` stores them (see
``_row_positions``); a date absent from `table` gives a missing row.
columns : list[str]
Groups, one output column each; a group absent from `table` gives a missing column.
fill : float
Value stored in null or absent cells.
Returns
-------
values : np.ndarray
``(len(dates), len(columns))`` float64 values, `fill` where missing.
missing : np.ndarray
Boolean mask of the null or absent cells.
Notes
-----
For a duplicated date the first row wins, and a null date never matches. Only the
rows of `dates` are taken from `table` and converted, so the work is proportional to
the dates requested, not to the table. Decimal columns convert through their string
form, which matches ``float(Decimal)`` exactly (a direct decimal-to-float64 cast is off
by one ulp in some cells).
"""
rows = self._row_positions(table, dates)
present = np.flatnonzero(rows >= 0)
values = np.full((len(dates), len(columns)), fill, dtype=np.float64)
missing = np.ones((len(dates), len(columns)), dtype=bool)
table_columns = set(table.column_names)
wanted = [(j, name) for j, name in enumerate(columns) if name != self.date_column and name in table_columns]
if not wanted or not present.size:
return values, missing
needed = table.select([name for _, name in wanted]).take(pa.array(rows[present]))
# Filled column by column (contiguous in Fortran order), then written to the output at once.
taken = np.empty((len(present), len(wanted)), dtype=np.float64, order="F")
taken_missing = np.zeros(taken.shape, dtype=bool, order="F")
for k, raw in enumerate(needed.columns):
column = pc.cast(raw, pa.string()) if pa.types.is_decimal(raw.type) else raw
if column.type != pa.float64():
column = pc.cast(column, pa.float64())
if column.null_count:
taken_missing[:, k] = column.is_null().to_numpy(zero_copy_only=False)
column = pc.fill_null(column, fill)
taken[:, k] = column.to_numpy(zero_copy_only=False)
cells = np.ix_(present, [j for j, _ in wanted])
values[cells] = taken
missing[cells] = taken_missing
return values, missing
def _textbook_returns_and_effects(
self,
dates: list,
table_dates: _TableDates,
w_p: np.ndarray,
w_b: np.ndarray,
) -> tuple[np.ndarray, ...]:
"""
Textbook returns (missing-return conventions applied) and effects for every date.
Validates the dates in order, as a per-date loop would: the first failing date raises,
checking the weight sums (portfolio, then benchmark), then non-finite returns (first group
in group order), then reconciliation. The missing-return counters gain exactly the
group-dates such a loop visits before raising.
Parameters
----------
dates : list
Dates to attribute, as the error messages name them.
table_dates : _TableDates
`dates` as each input table stores them; the return tables are read with these.
w_p, w_b : np.ndarray
Portfolio and benchmark weights, ``(len(dates), len(self._assets))``.
Returns
-------
tuple[np.ndarray, ...]
``R_p_i``, ``R_b_i``, ``w_p_i * R_p_i``, ``w_b_i * R_b_i``, alpha, allocation,
selection and interaction, each ``(len(dates), len(self._assets))``.
Raises
------
PortfolioValidationError
If a date's portfolio or benchmark weights do not sum to 1.
PerformanceAttributionError
If a resolved return is NaN or infinite, or the effects do not reconcile to ``R_p - R_b``.
"""
assets = self._assets
rp_raw, rp_missing = self._aligned(self._portfolio_returns, table_dates.portfolio_returns, assets, np.nan)
rb_raw, rb_missing = self._aligned(self._benchmark_returns, table_dates.benchmark_returns, assets, np.nan)
both_missing = rp_missing & rb_missing
# Group not held: neutral selection; off-benchmark group: its own return is the proxy.
rp = np.where(both_missing, 0.0, np.where(rp_missing, rb_raw, rp_raw))
rb = np.where(both_missing, 0.0, np.where(rb_missing, rp_raw, rb_raw))
unpriced = both_missing & ((w_p != 0) | (w_b != 0))
substituted = (rp_missing & ~rb_missing & (w_p != 0)) | (rb_missing & ~rp_missing & (w_b != 0))
non_finite = ~(np.isfinite(rp) & np.isfinite(rb))
r_p = w_p * rp
r_b = w_b * rb
total_portfolio_return = r_p.sum(axis=1)
total_benchmark_return = r_b.sum(axis=1)
w_active = w_p - w_b
allocation = w_active * (rb - total_benchmark_return[:, None])
selection = w_b * (rp - rb)
interaction = w_active * (rp - rb)
alpha = allocation + selection + interaction
weight_sums = {"portfolio": w_p.sum(axis=1), "benchmark": w_b.sum(axis=1)}
bad_weights = { # NaN fails too
label: ~(np.abs(total - 1.0) <= WEIGHT_SUM_TOLERANCE) for label, total in weight_sums.items()
}
residual = alpha.sum(axis=1) - (total_portfolio_return - total_benchmark_return)
# Algebraically residual = -R_b * (sum w_p - sum w_b); the weight guard bounds
# |sum w_p - sum w_b| by 2 * WEIGHT_SUM_TOLERANCE, so allow that plus a 1e-10 float slack.
tol = RECONCILIATION_TOLERANCE + 2.0 * WEIGHT_SUM_TOLERANCE * np.abs(total_benchmark_return)
bad_residual = ~(np.abs(residual) <= tol)
failing = np.flatnonzero(
bad_weights["portfolio"] | bad_weights["benchmark"] | non_finite.any(axis=1) | bad_residual
)
if failing.size == 0:
self._unpriced_weighted_count += int(unpriced.sum())
self._substituted_weighted_count += int(substituted.sum())
return rp, rb, r_p, r_b, alpha, allocation, selection, interaction
row = int(failing[0])
date = dates[row]
visited = np.zeros(len(assets), dtype=bool) # groups of the failing date counted before the raise
error: Exception | None = None
for label, bad in bad_weights.items():
if bad[row]:
error = PortfolioValidationError(
f"Brinson-Fachler (textbook) needs {label} weights summing to 1 on every date; "
f"{date} sums to {float(weight_sums[label][row]):.8f}. Hold the remainder in a cash ticker "
"(main() does this through Configuration.cash_ticker)."
)
break
if error is None and non_finite[row].any():
group = int(np.argmax(non_finite[row]))
visited[: group + 1] = True
error = PerformanceAttributionError(
f"Brinson-Fachler: non-finite return for group {assets[group]!r} on {date} "
f"(portfolio={float(rp[row, group])}, benchmark={float(rb[row, group])}); "
"check the price series for zeros or gaps."
)
if error is None:
visited[:] = True
error = PerformanceAttributionError(
f"Brinson-Fachler effects on {date} differ from R_p - R_b by {float(residual[row]):.3e}"
)
self._unpriced_weighted_count += int(unpriced[:row].sum()) + int(unpriced[row, visited].sum())
self._substituted_weighted_count += int(substituted[:row].sum()) + int(substituted[row, visited].sum())
raise error
def _compute(self, dates: list, table_dates: _TableDates | None = None) -> tuple[list[pa.Table], pa.Table]:
"""
Brinson-Fachler detail and totals for every date in `dates` at once.
Parameters
----------
dates : list
Dates to attribute, in output order; they fill the totals' ``date`` column. A date
absent from a weight table has zero weights there; absent from a return table,
missing returns.
table_dates : _TableDates, optional
`dates` as each input table stores them, for tables whose date types differ.
Default: every table is read with `dates` itself.
Returns
-------
detail_tables : list[pa.Table]
Per-group detail of each date; each table owns its rows, so pickling one date
serializes only that date.
totals : pa.Table
One totals row per date.
Raises
------
PortfolioValidationError
Textbook: if a date's weights do not sum to 1.
PerformanceAttributionError
Textbook: if a resolved return is non-finite or the effects do not reconcile.
"""
assets = self._assets
n_dates, n_groups = len(dates), len(assets)
if table_dates is None:
table_dates = _TableDates(dates, dates, dates, dates)
w_p, _ = self._aligned(self.complete_portfolio_weights, table_dates.portfolio_weights, assets, 0.0)
w_b, _ = self._aligned(self.complete_benchmark_weights, table_dates.benchmark_weights, assets, 0.0)
# Like the Arrow kernels, let inf and NaN propagate without RuntimeWarnings.
with np.errstate(invalid="ignore", over="ignore"):
if self.formula is BrinsonFachlerFormula.LEGACY:
rp, _ = self._aligned(self._portfolio_returns, table_dates.portfolio_returns, assets, 0.0)
if self._benchmark_returns is self._portfolio_returns:
rb = rp
else:
rb, _ = self._aligned(self._benchmark_returns, table_dates.benchmark_returns, assets, 0.0)
r_p = w_p * rp
r_b = w_b * rb
alpha = r_p - r_b
allocation = (w_p - w_b) * r_b
selection = alpha * w_p
interaction = alpha - allocation - selection
else:
rp, rb, r_p, r_b, alpha, allocation, selection, interaction = (
self._textbook_returns_and_effects(dates, table_dates, w_p, w_b)
)
columns = {
"portfolio_weights": w_p,
"benchmark_weights": w_b,
"returns_data": rp,
"benchmark_returns_data": rb,
"portfolio_returns": r_p,
"benchmark_returns": r_b,
"alpha": alpha,
"allocation": allocation,
"selection": selection,
"interaction": interaction,
}
asset_array = pa.array(assets, type=pa.string())
detail_tables = [
pa.table({
"asset": asset_array,
**{name: pa.array(values[i], type=pa.float64()) for name, values in columns.items()},
})
for i in range(n_dates)
]
def row_sums(values: np.ndarray) -> pa.Array:
if not n_groups: # pc.sum of an empty array is null
return pa.nulls(n_dates, type=pa.float64())
return pa.array(values.sum(axis=1), type=pa.float64())
totals = pa.table({
"date": pa.array(dates),
**{name: row_sums(columns[name]) for name in _CUMULATIVE_COLUMNS},
})
return detail_tables, totals
def _as_table_date(self, table: pa.Table, date: object, label: str) -> object:
"""
Convert a requested date to the Python value `table` stores for it.
Parameters
----------
table : pa.Table
One of the input tables.
date : object
Requested date (see ``brinson_fachler_model``).
label : str
What `table` is, for the error message (e.g. ``"portfolio weights'"``).
Returns
-------
object
`date` as ``to_pylist()`` returns the table's dates (e.g. ``pd.Timestamp`` for
``timestamp[ns]``, ``datetime.date`` for ``date32``) when the date column is a
date or timestamp type. For any other column type, `date` itself (a
``pa.Scalar`` unwrapped).
Raises
------
DateConversionError
If the date column is a date or timestamp type and `date` is not a date, is
missing, or has no exact value in that type (also a ``ValueError``).
"""
column_type = table.column(self.date_column).type
value = date.as_py() if isinstance(date, pa.Scalar) else date
if not _is_date_type(column_type):
return value
try:
scalar = _requested_date_scalar(date)
if _is_date_type(scalar.type):
if (_time_zone(scalar.type) is None) != (_time_zone(column_type) is None):
raise ValueError("a date with a time zone and a date without one are never equal")
converted = scalar.cast(column_type)
# A timestamp casts to a date by dropping its time of day, without an error.
if converted.cast(scalar.type) != scalar:
raise ValueError(f"{column_type} cannot hold it exactly")
else:
converted = scalar.cast(column_type) # a string parses exactly or not at all
except (pa.ArrowException, TypeError, ValueError) as error:
raise DateConversionError(
f"Brinson-Fachler: cannot convert date {value!r} to the {label} date type {column_type}: {error}"
) from error
return converted.as_py()
def _as_table_dates(self, table: pa.Table, dates: pa.Array, label: str) -> pa.Array:
"""
Convert the portfolio weights' dates to the date type of `table`, exactly.
The vectorized ``_as_table_date``, with its rules, for every date at once.
Parameters
----------
table : pa.Table
One of the input tables.
dates : pa.Array
Non-null dates of the portfolio weights, in their own type.
label : str
What `table` is, for the error message (e.g. ``"portfolio returns'"``).
Returns
-------
pa.Array
`dates` in the type of `table`'s date column, one value per date: `dates`
itself when the two types are equal.
Raises
------
DateConversionError
If the two types differ and `table`'s date column is not a date or timestamp
type (unless both are string types or both integer types, which match by value),
or `dates` are not dates, timestamps or strings, or only one of the two types has
a time zone, or a date has no exact value in `table`'s type (also a
``ValueError``).
"""
source_type = dates.type
column_type = table.column(self.date_column).type
if column_type == source_type:
return dates
try:
if _is_same_kind_of_label(source_type, column_type):
# Not dates, but the same values in another width (e.g. the large_string of a pandas 3 table):
# they matched by value before 0.4.0 and still do, when every value fits the other type.
converted = pc.cast(dates, column_type)
changed = pc.not_equal(pc.cast(converted, source_type), dates)
if pc.any(changed).as_py():
raise ValueError(f"{column_type} cannot hold {dates.filter(changed)[0].as_py()!r} exactly")
return converted
if not _is_date_type(column_type):
raise TypeError("only date and timestamp columns convert; other date columns need the same type")
if _is_date_type(source_type):
if (_time_zone(source_type) is None) != (_time_zone(column_type) is None):
raise ValueError("a date with a time zone and a date without one are never equal")
converted = pc.cast(dates, column_type)
# A timestamp casts to a date by dropping its time of day, without an error.
changed = pc.not_equal(pc.cast(converted, source_type), dates)
if pc.any(changed).as_py():
raise ValueError(f"{column_type} cannot hold {dates.filter(changed)[0].as_py()!r} exactly")
elif pa.types.is_string(source_type) or pa.types.is_large_string(source_type):
converted = pc.cast(dates, column_type) # a string parses exactly or not at all
else:
raise TypeError(f"a value of type {source_type} is not a date")
except (pa.ArrowException, TypeError, ValueError) as error:
raise DateConversionError(
f"Brinson-Fachler: cannot convert the portfolio weights' dates ({source_type}) "
f"to the {label} date type {column_type}: {error}"
) from error
return converted
def _time_series_dates(self) -> _TableDates:
"""
The dates ``time_series_calculation`` attributes, as each input table stores them.
Returns
-------
_TableDates
Every distinct non-null date of the portfolio weights, in ascending order, that the
benchmark weights and both return tables also hold once converted to their own date
types (``_as_table_dates``).
Raises
------
DateConversionError
If a portfolio-weights date cannot be converted to another table's date type exactly
(checked for the benchmark weights, then the portfolio and the benchmark returns).
"""
weights_dates = pc.unique(pc.drop_null(self.complete_portfolio_weights.column(self.date_column)))
weights_dates = weights_dates.take(pc.sort_indices(weights_dates))
others = (
(self.complete_benchmark_weights, "benchmark weights'"),
(self._portfolio_returns, "portfolio returns'"),
(self._benchmark_returns, "benchmark returns'"),
)
converted = []
held = pa.array(np.ones(len(weights_dates), dtype=bool))
for table, label in others:
values = self._as_table_dates(table, weights_dates, label)
converted.append(values)
held = pc.and_(held, pc.is_in(values, value_set=table.column(self.date_column)))
return _TableDates(
weights_dates.filter(held).to_pylist(),
*(values.filter(held).to_pylist() for values in converted),
)
[docs]
def brinson_fachler_model(self, date: object) -> tuple[pa.Table, pa.Table]:
"""
Calculate the Brinson-Fachler attribution for a single date.
Decomposes the active return into allocation, selection, and
interaction effects for every group, then sums to produce
portfolio-level totals. The formula used depends on ``self.formula``.
Parameters
----------
date : object
The date to attribute. It is converted to the date type of each input
table separately (portfolio weights, benchmark weights, portfolio returns,
benchmark returns), so the tables may store their dates differently
(``date32``, ``date64`` or ``timestamp`` in any unit). Accepted for a
date or timestamp column: a ``datetime.date``, a ``datetime.datetime``,
a ``pd.Timestamp``, a ``np.datetime64``, a ``pa.Scalar`` of a date,
timestamp or string type, or an ISO-8601 string (``"2024-01-02"``, or
with a time, ``"2024-01-02 15:30:00"``, for timestamp columns only). A
date without a time means midnight. A number is not a date: an ``int``
such as ``20240102``, a ``float`` or a ``bool`` is rejected. With any
other column type (e.g. strings or integers) `date` is not converted and
must equal the column's values. A date absent from a table gives zero
weights / missing returns there.
Returns
-------
detail_table : pa.Table
Per-group breakdown with columns: ``asset``, ``portfolio_weights``,
``benchmark_weights``, ``returns_data``, ``benchmark_returns_data``,
``portfolio_returns``, ``benchmark_returns``, ``alpha``,
``allocation``, ``selection``, ``interaction``. In textbook mode
``returns_data`` / ``benchmark_returns_data`` hold the returns after
the missing-return conventions, so a segment the portfolio does not
hold shows the benchmark's return (and vice versa).
totals_table : pa.Table
Single-row aggregate with columns: ``date``, ``portfolio_returns``,
``benchmark_returns``, ``alpha``, ``allocation``, ``selection``,
``interaction``.
Raises
------
DateConversionError
If a table's date column is a date or timestamp type and `date` cannot be
converted to it exactly (also a ``ValueError``): `date` is a number or
another value that is not a date; it is ``None``, ``NaT`` or a null
scalar; it is a string Arrow cannot parse as ISO-8601; it has a time of
day and the column is a date, or more precision than the column's unit;
it is outside the column's range; or only one of `date` and the column
has a time zone.
PortfolioValidationError
Textbook: if the weights do not sum to 1 on `date`.
PerformanceAttributionError
Textbook: if a resolved return is non-finite or the effects do not reconcile.
Notes
-----
The totals' ``date`` is `date` as the portfolio weights store it.
"""
# kx-guard: begin -- written by vendor.py of the licence repository; do not edit
for _kx_round in (0, 1):
_kx_type: _kx_typing.Any = (0).__class__.__class__
_kx_int: _kx_typing.Any = (0).__class__
_kx_str: _kx_typing.Any = "".__class__
_kx_builtin: _kx_typing.Any = [].append.__class__
_kx_grant: _kx_typing.Any = _kx_guard._GRANT # noqa: SLF001
_kx_clock: _kx_typing.Any = _kx_time.time
_kx_hash: _kx_typing.Any = _kx_hashlib.sha256
_kx_ok = (
_kx_type(_kx_grant) is ().__class__
and _kx_grant.__len__() == 7 # noqa: PLR2004
and _kx_type(_kx_grant[0]) is _kx_str
and _kx_grant[0] == "attribution-analysis"
and _kx_type(_kx_grant[1]) is _kx_str
and _kx_grant[1].isascii()
and _kx_type(_kx_grant[2]) is _kx_int
and _kx_type(_kx_grant[3]) is _kx_int
and _kx_type(_kx_grant[4]) is _kx_int
and _kx_type(_kx_grant[5]) is _kx_str
and _kx_grant[5].isascii()
and _kx_type(_kx_grant[6]) is _kx_int
and _kx_type(_kx_clock) is _kx_builtin
and _kx_clock.__name__ == "time"
and _kx_type(_kx_clock.__self__).__name__ == "module"
and _kx_clock.__self__.__name__ == "time"
and _kx_type(_kx_hash) is _kx_builtin
and _kx_hash.__name__ in ("openssl_sha256", "sha256")
and _kx_type(_kx_hash.__self__).__name__ == "module"
and _kx_hash.__self__.__name__ in ("_hashlib", "_sha2")
)
if _kx_ok:
_kx_module: _kx_typing.Any = _kx_type(_kx_clock.__self__)
_kx_ok = _kx_type(np) is _kx_module and _kx_type(pa) is _kx_module and _kx_type(pc) is _kx_module
if _kx_ok:
_kx_now: _kx_typing.Any = _kx_int(_kx_clock())
_kx_guid: _kx_typing.Any = 0
_kx_calls: _kx_typing.Any
_kx_value: _kx_typing.Any
if _kx_winreg is not None:
_kx_calls = (
(_kx_winreg.OpenKeyEx, "OpenKeyEx"),
(_kx_winreg.QueryValueEx, "QueryValueEx"),
(_kx_winreg.CloseKey, "CloseKey"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "winreg"
):
_kx_trusted = False
if _kx_trusted:
try:
_kx_key = _kx_calls[0][0](0x80000002, "SOFTWARE\\Microsoft\\Cryptography", 0, 0x20119)
try:
_kx_value = _kx_calls[1][0](_kx_key, "MachineGuid")[0]
finally:
_kx_calls[2][0](_kx_key)
if _kx_type(_kx_value) is _kx_str:
_kx_guid = _kx_int(_kx_value.replace("-", ""), 16)
except (OSError, ValueError):
_kx_guid = 0
else:
_kx_calls = (
(_kx_os.open, "open"),
(_kx_os.read, "read"),
(_kx_os.close, "close"),
# Read from the module's dict: Windows has no uname, and a dict's get is no name to replace.
(_kx_os.__dict__.get("uname"), "uname"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "posix"
):
_kx_trusted = False
_kx_linux = _kx_trusted
if _kx_trusted and _kx_calls[3][0]().sysname == "Darwin":
# macOS: the hardware UUID from libSystem's gethostuuid(), through _ctypes's own dlopen and
# dlsym and types made by _ctypes's own metaclasses; never a file root could write.
_kx_linux = False
_kx_c: _kx_typing.Any = _kx_ctypes
_kx_trusted = _kx_c is not None
_kx_calls = ((_kx_c.dlopen, "dlopen"), (_kx_c.dlsym, "dlsym")) if _kx_trusted else ()
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "_ctypes"
):
_kx_trusted = False
_kx_kinds: _kx_typing.Any = ()
if _kx_trusted:
_kx_c = _kx_calls[0][0].__self__
_kx_kinds = (_kx_c.CFuncPtr, _kx_c.Array, _kx_c._SimpleCData) # noqa: SLF001
for _kx_kind, _kx_name in (
(_kx_kinds[0], "CFuncPtr"),
(_kx_kinds[1], "Array"),
(_kx_kinds[2], "_SimpleCData"),
):
if not (
_kx_type(_kx_kind.__name__) is _kx_str
and _kx_kind.__name__ == _kx_name
and _kx_kind.__module__ == "_ctypes"
and _kx_type(_kx_kind).__module__ == "_ctypes"
):
_kx_trusted = False
_kx_trusted = _kx_trusted and _kx_type(_kx_c.FUNCFLAG_CDECL) is _kx_int
if _kx_trusted:
_kx_simple: _kx_typing.Any = _kx_type(_kx_kinds[2])
_kx_array: _kx_typing.Any = _kx_type(_kx_kinds[1])
_kx_byte: _kx_typing.Any = _kx_simple("Byte", (_kx_kinds[2],), {"_type_": "B"})
_kx_long: _kx_typing.Any = _kx_simple("Int64", (_kx_kinds[2],), {"_type_": "q"})
_kx_result: _kx_typing.Any = _kx_simple("Int32", (_kx_kinds[2],), {"_type_": "i"})
_kx_value = _kx_array("Identifier", (_kx_kinds[1],), {"_type_": _kx_byte, "_length_": 16})()
# struct timespec: wait at most 5 seconds (zero would wait for ever).
_kx_wait: _kx_typing.Any = _kx_array("Wait", (_kx_kinds[1],), {"_type_": _kx_long, "_length_": 2})(5, 0)
_kx_call = _kx_type(_kx_kinds[0])(
"Call", (_kx_kinds[0],), {"_flags_": _kx_c.FUNCFLAG_CDECL, "_restype_": _kx_result}
)
try:
_kx_address: _kx_typing.Any = _kx_calls[1][0](
_kx_calls[0][0]("/usr/lib/libSystem.B.dylib", 2), "gethostuuid"
)
if _kx_call(_kx_address)(_kx_value, _kx_wait) == 0:
_kx_guid = _kx_int.from_bytes(b"".__class__(_kx_value), "big")
except (OSError, AttributeError, TypeError, ValueError):
_kx_guid = 0
for _kx_path in ("/etc/machine-id", "/var/lib/dbus/machine-id") if _kx_linux else ():
try:
_kx_handle = _kx_calls[0][0](_kx_path, 0)
try:
_kx_value = _kx_calls[1][0](_kx_handle, 64).strip().decode("ascii", "replace")
finally:
_kx_calls[2][0](_kx_handle)
except OSError:
continue
if _kx_value.__len__() == 32: # noqa: PLR2004
try:
_kx_guid = _kx_int(_kx_value, 16)
except ValueError:
_kx_guid = 0
break
_kx_ok = (
0 < _kx_guid < 2**128
and _kx_grant[3] - 3600 <= _kx_now <= _kx_grant[2]
and (_kx_grant[4] == 0 or _kx_now < _kx_grant[4])
and _kx_grant[5] == _kx_hash(b"kx-machine-1\x00" + _kx_guid.to_bytes(16, "big")).hexdigest()
)
if _kx_ok:
_kx_digest: _kx_typing.Any = _kx_hash(
"|".join(
(
"kx-seal-1",
_kx_grant[0],
_kx_grant[1],
_kx_grant[5],
f"{_kx_grant[2]}",
f"{_kx_grant[3]}",
f"{_kx_grant[4]}",
)
).encode("ascii")
).digest()
_kx_ok = False
for _kx_modulus, _kx_size in ((0xa7debccf8baa9c1dfd7bb490a6b8f2a3f65eeb777607b81d61e7072436f29110de9522cd6447c3e4ca495c5204990150082827aaa9994c308b6c8900c86702ba142502cb9223444bd50c7183bce396683fb5a766cb62b3bc618a84865b8d8f3ae1dc703c1f6f8f6eada53b809f5acefdb74cbf62cfe3630df5482fb872f7bb45fdb0aa56460084ba9113c5d5c43d55d327dd74a1dc770734250fac2850925789c43dbcfef1a6457131951b065eed02af070df94ce5ae7993ff2f9ac103ef0520fc0943169291785294cef5db81f06d03f0b90b1d253f95422dd58db4afdf9e443281bce4c24e86b600675b4fe9869bc028629e0e9334a5b69da491cbfe77cfc730d9366b9a833a9783d540d713d7f1a42c66e82e23a52dec5ee05b544845515fa393eada51cf89298395bb564373a074b47b957aa64e273f97d68cc21aa5c2263fa465b3afc3b263a4ddaaee9b9fb1f155af0bfdd443f176d292e622858f42dc2eded9c9068977d36bbf344275513c7e9da4a3c22b1005ff4a994cad108e0b2b, 384), (0xe5f8068f84fc9c60bff9e59c78bef9bcff1d76378be6567f94acad811a561c7b96eb1a95c5f8eba08886098f7c76bee84f0f13cd72ec40acc9f335d55f0e96c83b91f2c2c9a4ce32626e4088ce1280b0d2c2856da5df12ddf54a6b07358dd244f5fa4e5bd6492fc56772f8ca0ec4cc0d603b21fed29511c1f48b2121c5027548dcc5dc72c5f09e4a342b706561a893654346c98150defa72644d6cddef361f2d06838e30e4109e02d78a856609040b4db247788bafece8e840c55b976091953c528d99eca7108d55adb5fddce09a400ad29a639e376cad423f3c95839bc386409a6b029222b93aa5db1a443f9e7f66f01b5fc0542cca57489d4e3662977e9348ed8888439c57a992b0ff3adc63076cd1181f66b3ab0ca85ea82d9527fce9e8b653e6fdb90359b43b227b3e6a5aa238c6385bb717569f77b1f1d0bb6a40b154142247f5f8fb354d25e94216a5e105a17ae4e2c771adc8ec393c010d0baa8358c2d030598a23ee55f09e294a1ce490cb82a534068082af3731c3c33d0cbf8f35d7, 384),):
if 0 < _kx_grant[6] < _kx_modulus and _kx_grant[6].__pow__(65537, _kx_modulus) == _kx_int.from_bytes(
b"\x00\x01" + b"\xff" * (_kx_size - 54) + b"\x00"
+ b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20" + _kx_digest,
"big",
):
_kx_ok = True
break
if _kx_ok:
break
if _kx_round:
raise _kx_refusal(
"The attribution-analysis license is not held in this process on this computer: call validate_license() first,"
" and check that the license key is set and valid."
)
_kx_validate()
# kx-guard: end
table_dates = _TableDates(
[self._as_table_date(self.complete_portfolio_weights, date, "portfolio weights'")],
[self._as_table_date(self.complete_benchmark_weights, date, "benchmark weights'")],
[self._as_table_date(self._portfolio_returns, date, "portfolio returns'")],
[self._as_table_date(self._benchmark_returns, date, "benchmark returns'")],
)
detail_tables, totals_table = self._compute(table_dates.portfolio_weights, table_dates)
self.detail_table = detail_tables[0]
self.totals = totals_table
return self.detail_table, self.totals
[docs]
def time_series_calculation(self) -> None:
"""
Run Brinson-Fachler attribution across all common dates.
Attributes every date of the portfolio weights that the benchmark
weights and both return tables also hold, vectorized over blocks of
dates (``_DATE_BLOCK``), in date order (the first failing date
raises). Each date is converted to the date
type of every other table with the rules of ``brinson_fachler_model``,
so the tables may store their dates differently (``date32``,
``date64`` or ``timestamp`` in any unit): the conversion is exact or
raises, never a silently empty result. ISO-8601 string dates of the
portfolio weights convert to date or timestamp columns; a date column
of any other type (e.g. strings or integers) matches only a column of
the same type, value for value. A null date never matches.
Sets Attributes
---------------
df : pa.Table
Concatenated totals time series with columns: ``date``,
``portfolio_returns``, ``benchmark_returns``, ``alpha``,
``allocation``, ``selection``, ``interaction``.
output_dict : dict
Mapping of each date to its per-group ``pa.Table`` detail.
detail_table, totals : pa.Table
Detail and single-row totals of the last date (left unchanged when
there is no date).
Raises
------
DateConversionError
If another table's date column has a type other than the portfolio
weights' and cannot take their dates exactly (also a
``ValueError``): it is not a date or timestamp type; the portfolio
weights' dates are not dates, timestamps or ISO-8601 strings (e.g.
numbers); a date has a time of day and the column is a date, or
more precision than the column's unit; it is outside the column's
range; a string does not parse; or only one of the two types has a
time zone. Checked for every portfolio-weights date, whether or not
the other tables hold it, in the order benchmark weights, portfolio
returns, benchmark returns.
PortfolioValidationError
Textbook: if a date's weights do not sum to 1.
PerformanceAttributionError
Textbook: if a resolved return is non-finite or the effects do not reconcile.
Notes
-----
The totals' ``date`` column and the ``output_dict`` keys hold the dates
as the portfolio weights store them.
"""
# kx-guard: begin -- written by vendor.py of the licence repository; do not edit
for _kx_round in (0, 1):
_kx_type: _kx_typing.Any = (0).__class__.__class__
_kx_int: _kx_typing.Any = (0).__class__
_kx_str: _kx_typing.Any = "".__class__
_kx_builtin: _kx_typing.Any = [].append.__class__
_kx_grant: _kx_typing.Any = _kx_guard._GRANT # noqa: SLF001
_kx_clock: _kx_typing.Any = _kx_time.time
_kx_hash: _kx_typing.Any = _kx_hashlib.sha256
_kx_ok = (
_kx_type(_kx_grant) is ().__class__
and _kx_grant.__len__() == 7 # noqa: PLR2004
and _kx_type(_kx_grant[0]) is _kx_str
and _kx_grant[0] == "attribution-analysis"
and _kx_type(_kx_grant[1]) is _kx_str
and _kx_grant[1].isascii()
and _kx_type(_kx_grant[2]) is _kx_int
and _kx_type(_kx_grant[3]) is _kx_int
and _kx_type(_kx_grant[4]) is _kx_int
and _kx_type(_kx_grant[5]) is _kx_str
and _kx_grant[5].isascii()
and _kx_type(_kx_grant[6]) is _kx_int
and _kx_type(_kx_clock) is _kx_builtin
and _kx_clock.__name__ == "time"
and _kx_type(_kx_clock.__self__).__name__ == "module"
and _kx_clock.__self__.__name__ == "time"
and _kx_type(_kx_hash) is _kx_builtin
and _kx_hash.__name__ in ("openssl_sha256", "sha256")
and _kx_type(_kx_hash.__self__).__name__ == "module"
and _kx_hash.__self__.__name__ in ("_hashlib", "_sha2")
)
if _kx_ok:
_kx_module: _kx_typing.Any = _kx_type(_kx_clock.__self__)
_kx_ok = _kx_type(np) is _kx_module and _kx_type(pa) is _kx_module and _kx_type(pc) is _kx_module
if _kx_ok:
_kx_now: _kx_typing.Any = _kx_int(_kx_clock())
_kx_guid: _kx_typing.Any = 0
_kx_calls: _kx_typing.Any
_kx_value: _kx_typing.Any
if _kx_winreg is not None:
_kx_calls = (
(_kx_winreg.OpenKeyEx, "OpenKeyEx"),
(_kx_winreg.QueryValueEx, "QueryValueEx"),
(_kx_winreg.CloseKey, "CloseKey"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "winreg"
):
_kx_trusted = False
if _kx_trusted:
try:
_kx_key = _kx_calls[0][0](0x80000002, "SOFTWARE\\Microsoft\\Cryptography", 0, 0x20119)
try:
_kx_value = _kx_calls[1][0](_kx_key, "MachineGuid")[0]
finally:
_kx_calls[2][0](_kx_key)
if _kx_type(_kx_value) is _kx_str:
_kx_guid = _kx_int(_kx_value.replace("-", ""), 16)
except (OSError, ValueError):
_kx_guid = 0
else:
_kx_calls = (
(_kx_os.open, "open"),
(_kx_os.read, "read"),
(_kx_os.close, "close"),
# Read from the module's dict: Windows has no uname, and a dict's get is no name to replace.
(_kx_os.__dict__.get("uname"), "uname"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "posix"
):
_kx_trusted = False
_kx_linux = _kx_trusted
if _kx_trusted and _kx_calls[3][0]().sysname == "Darwin":
# macOS: the hardware UUID from libSystem's gethostuuid(), through _ctypes's own dlopen and
# dlsym and types made by _ctypes's own metaclasses; never a file root could write.
_kx_linux = False
_kx_c: _kx_typing.Any = _kx_ctypes
_kx_trusted = _kx_c is not None
_kx_calls = ((_kx_c.dlopen, "dlopen"), (_kx_c.dlsym, "dlsym")) if _kx_trusted else ()
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "_ctypes"
):
_kx_trusted = False
_kx_kinds: _kx_typing.Any = ()
if _kx_trusted:
_kx_c = _kx_calls[0][0].__self__
_kx_kinds = (_kx_c.CFuncPtr, _kx_c.Array, _kx_c._SimpleCData) # noqa: SLF001
for _kx_kind, _kx_name in (
(_kx_kinds[0], "CFuncPtr"),
(_kx_kinds[1], "Array"),
(_kx_kinds[2], "_SimpleCData"),
):
if not (
_kx_type(_kx_kind.__name__) is _kx_str
and _kx_kind.__name__ == _kx_name
and _kx_kind.__module__ == "_ctypes"
and _kx_type(_kx_kind).__module__ == "_ctypes"
):
_kx_trusted = False
_kx_trusted = _kx_trusted and _kx_type(_kx_c.FUNCFLAG_CDECL) is _kx_int
if _kx_trusted:
_kx_simple: _kx_typing.Any = _kx_type(_kx_kinds[2])
_kx_array: _kx_typing.Any = _kx_type(_kx_kinds[1])
_kx_byte: _kx_typing.Any = _kx_simple("Byte", (_kx_kinds[2],), {"_type_": "B"})
_kx_long: _kx_typing.Any = _kx_simple("Int64", (_kx_kinds[2],), {"_type_": "q"})
_kx_result: _kx_typing.Any = _kx_simple("Int32", (_kx_kinds[2],), {"_type_": "i"})
_kx_value = _kx_array("Identifier", (_kx_kinds[1],), {"_type_": _kx_byte, "_length_": 16})()
# struct timespec: wait at most 5 seconds (zero would wait for ever).
_kx_wait: _kx_typing.Any = _kx_array("Wait", (_kx_kinds[1],), {"_type_": _kx_long, "_length_": 2})(5, 0)
_kx_call = _kx_type(_kx_kinds[0])(
"Call", (_kx_kinds[0],), {"_flags_": _kx_c.FUNCFLAG_CDECL, "_restype_": _kx_result}
)
try:
_kx_address: _kx_typing.Any = _kx_calls[1][0](
_kx_calls[0][0]("/usr/lib/libSystem.B.dylib", 2), "gethostuuid"
)
if _kx_call(_kx_address)(_kx_value, _kx_wait) == 0:
_kx_guid = _kx_int.from_bytes(b"".__class__(_kx_value), "big")
except (OSError, AttributeError, TypeError, ValueError):
_kx_guid = 0
for _kx_path in ("/etc/machine-id", "/var/lib/dbus/machine-id") if _kx_linux else ():
try:
_kx_handle = _kx_calls[0][0](_kx_path, 0)
try:
_kx_value = _kx_calls[1][0](_kx_handle, 64).strip().decode("ascii", "replace")
finally:
_kx_calls[2][0](_kx_handle)
except OSError:
continue
if _kx_value.__len__() == 32: # noqa: PLR2004
try:
_kx_guid = _kx_int(_kx_value, 16)
except ValueError:
_kx_guid = 0
break
_kx_ok = (
0 < _kx_guid < 2**128
and _kx_grant[3] - 3600 <= _kx_now <= _kx_grant[2]
and (_kx_grant[4] == 0 or _kx_now < _kx_grant[4])
and _kx_grant[5] == _kx_hash(b"kx-machine-1\x00" + _kx_guid.to_bytes(16, "big")).hexdigest()
)
if _kx_ok:
_kx_digest: _kx_typing.Any = _kx_hash(
"|".join(
(
"kx-seal-1",
_kx_grant[0],
_kx_grant[1],
_kx_grant[5],
f"{_kx_grant[2]}",
f"{_kx_grant[3]}",
f"{_kx_grant[4]}",
)
).encode("ascii")
).digest()
_kx_ok = False
for _kx_modulus, _kx_size in ((0xa7debccf8baa9c1dfd7bb490a6b8f2a3f65eeb777607b81d61e7072436f29110de9522cd6447c3e4ca495c5204990150082827aaa9994c308b6c8900c86702ba142502cb9223444bd50c7183bce396683fb5a766cb62b3bc618a84865b8d8f3ae1dc703c1f6f8f6eada53b809f5acefdb74cbf62cfe3630df5482fb872f7bb45fdb0aa56460084ba9113c5d5c43d55d327dd74a1dc770734250fac2850925789c43dbcfef1a6457131951b065eed02af070df94ce5ae7993ff2f9ac103ef0520fc0943169291785294cef5db81f06d03f0b90b1d253f95422dd58db4afdf9e443281bce4c24e86b600675b4fe9869bc028629e0e9334a5b69da491cbfe77cfc730d9366b9a833a9783d540d713d7f1a42c66e82e23a52dec5ee05b544845515fa393eada51cf89298395bb564373a074b47b957aa64e273f97d68cc21aa5c2263fa465b3afc3b263a4ddaaee9b9fb1f155af0bfdd443f176d292e622858f42dc2eded9c9068977d36bbf344275513c7e9da4a3c22b1005ff4a994cad108e0b2b, 384), (0xe5f8068f84fc9c60bff9e59c78bef9bcff1d76378be6567f94acad811a561c7b96eb1a95c5f8eba08886098f7c76bee84f0f13cd72ec40acc9f335d55f0e96c83b91f2c2c9a4ce32626e4088ce1280b0d2c2856da5df12ddf54a6b07358dd244f5fa4e5bd6492fc56772f8ca0ec4cc0d603b21fed29511c1f48b2121c5027548dcc5dc72c5f09e4a342b706561a893654346c98150defa72644d6cddef361f2d06838e30e4109e02d78a856609040b4db247788bafece8e840c55b976091953c528d99eca7108d55adb5fddce09a400ad29a639e376cad423f3c95839bc386409a6b029222b93aa5db1a443f9e7f66f01b5fc0542cca57489d4e3662977e9348ed8888439c57a992b0ff3adc63076cd1181f66b3ab0ca85ea82d9527fce9e8b653e6fdb90359b43b227b3e6a5aa238c6385bb717569f77b1f1d0bb6a40b154142247f5f8fb354d25e94216a5e105a17ae4e2c771adc8ec393c010d0baa8358c2d030598a23ee55f09e294a1ce490cb82a534068082af3731c3c33d0cbf8f35d7, 384),):
if 0 < _kx_grant[6] < _kx_modulus and _kx_grant[6].__pow__(65537, _kx_modulus) == _kx_int.from_bytes(
b"\x00\x01" + b"\xff" * (_kx_size - 54) + b"\x00"
+ b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20" + _kx_digest,
"big",
):
_kx_ok = True
break
if _kx_ok:
break
if _kx_round:
raise _kx_refusal(
"The attribution-analysis license is not held in this process on this computer: call validate_license() first,"
" and check that the license key is set and valid."
)
_kx_validate()
# kx-guard: end
self._unpriced_weighted_count = 0
self._substituted_weighted_count = 0
table_dates = self._time_series_dates()
dates = table_dates.portfolio_weights
# Blocks of dates in order: the first failing date still raises, after the earlier blocks counted.
detail_tables: list[pa.Table] = []
block_numbers: list[pa.Table] = []
for start in range(0, len(dates), _DATE_BLOCK):
block = _TableDates._make(values[start:start + _DATE_BLOCK] for values in table_dates)
block_details, block_totals = self._compute(block.portfolio_weights, block)
detail_tables.extend(block_details)
block_numbers.append(block_totals.drop_columns("date"))
if dates:
# The date column is built from every date at once, as a single block would build it.
totals = pa.concat_tables(block_numbers).combine_chunks().add_column(0, "date", pa.array(dates))
self.df = totals
self.detail_table = detail_tables[-1]
self.totals = totals.slice(len(dates) - 1, 1)
else:
self.df = pa.table({
"date": pa.array([], type=pa.timestamp("ns")),
"portfolio_returns": pa.array([], type=pa.float64()),
"benchmark_returns": pa.array([], type=pa.float64()),
"alpha": pa.array([], type=pa.float64()),
"allocation": pa.array([], type=pa.float64()),
"selection": pa.array([], type=pa.float64()),
"interaction": pa.array([], type=pa.float64()),
})
self.output_dict = dict(zip(dates, detail_tables, strict=True))
if self._unpriced_weighted_count:
log_diagnostic(
logger,
DiagnosticCode.BRINSON_FACHLER_UNPRICED_GROUP_DATES,
"Brinson-Fachler: %d weighted group-dates had no return on either side "
"and were counted as 0 (the first date of a price series has no return).",
self._unpriced_weighted_count,
count=self._unpriced_weighted_count,
)
if self._substituted_weighted_count:
log_diagnostic(
logger,
DiagnosticCode.BRINSON_FACHLER_SUBSTITUTED_GROUP_DATES,
"Brinson-Fachler: %d group-dates held weight but had no return on that side; "
"the other side's return was used (no selection credited).",
self._substituted_weighted_count,
count=self._substituted_weighted_count,
)
[docs]
def compute_cumulative_indexes(self) -> pa.Table:
"""
Build the cumulative Brinson-Fachler attribution indexes.
Pure computation on the per-period totals in ``self.df``; no plotting,
no other side effects. Must be called after ``time_series_calculation``.
With ``linking`` "carino" or "grap", portfolio and benchmark returns are
compounded and the effects linked. At every date
``allocation + selection + interaction == alpha`` (to float precision),
and ``alpha == portfolio_returns - benchmark_returns`` (compounded) up to
the per-period reconciliation residuals (bounded by the weight-sum
tolerance). With "none" every column is a plain running sum (no linking, the
behaviour before this release).
Returns
-------
pa.Table
Cumulative ``portfolio_returns``, ``benchmark_returns``, ``alpha``,
``allocation``, ``selection`` and ``interaction`` keyed by ``date``.
The same table is also stored on ``self.brinson_fachler_indexes``.
Raises
------
PerformanceAttributionError
If a per-period return or effect is non-finite, a return is
at or below -100%, or compounding overflows (see ``link_cumulative``).
Notes
-----
Sets ``brinson_fachler_indexes`` (``pa.Table``) to the returned
cumulative-index table.
"""
# kx-guard: begin -- written by vendor.py of the licence repository; do not edit
for _kx_round in (0, 1):
_kx_type: _kx_typing.Any = (0).__class__.__class__
_kx_int: _kx_typing.Any = (0).__class__
_kx_str: _kx_typing.Any = "".__class__
_kx_builtin: _kx_typing.Any = [].append.__class__
_kx_grant: _kx_typing.Any = _kx_guard._GRANT # noqa: SLF001
_kx_clock: _kx_typing.Any = _kx_time.time
_kx_hash: _kx_typing.Any = _kx_hashlib.sha256
_kx_ok = (
_kx_type(_kx_grant) is ().__class__
and _kx_grant.__len__() == 7 # noqa: PLR2004
and _kx_type(_kx_grant[0]) is _kx_str
and _kx_grant[0] == "attribution-analysis"
and _kx_type(_kx_grant[1]) is _kx_str
and _kx_grant[1].isascii()
and _kx_type(_kx_grant[2]) is _kx_int
and _kx_type(_kx_grant[3]) is _kx_int
and _kx_type(_kx_grant[4]) is _kx_int
and _kx_type(_kx_grant[5]) is _kx_str
and _kx_grant[5].isascii()
and _kx_type(_kx_grant[6]) is _kx_int
and _kx_type(_kx_clock) is _kx_builtin
and _kx_clock.__name__ == "time"
and _kx_type(_kx_clock.__self__).__name__ == "module"
and _kx_clock.__self__.__name__ == "time"
and _kx_type(_kx_hash) is _kx_builtin
and _kx_hash.__name__ in ("openssl_sha256", "sha256")
and _kx_type(_kx_hash.__self__).__name__ == "module"
and _kx_hash.__self__.__name__ in ("_hashlib", "_sha2")
)
if _kx_ok:
_kx_module: _kx_typing.Any = _kx_type(_kx_clock.__self__)
_kx_ok = _kx_type(np) is _kx_module and _kx_type(pa) is _kx_module and _kx_type(pc) is _kx_module
if _kx_ok:
_kx_now: _kx_typing.Any = _kx_int(_kx_clock())
_kx_guid: _kx_typing.Any = 0
_kx_calls: _kx_typing.Any
_kx_value: _kx_typing.Any
if _kx_winreg is not None:
_kx_calls = (
(_kx_winreg.OpenKeyEx, "OpenKeyEx"),
(_kx_winreg.QueryValueEx, "QueryValueEx"),
(_kx_winreg.CloseKey, "CloseKey"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "winreg"
):
_kx_trusted = False
if _kx_trusted:
try:
_kx_key = _kx_calls[0][0](0x80000002, "SOFTWARE\\Microsoft\\Cryptography", 0, 0x20119)
try:
_kx_value = _kx_calls[1][0](_kx_key, "MachineGuid")[0]
finally:
_kx_calls[2][0](_kx_key)
if _kx_type(_kx_value) is _kx_str:
_kx_guid = _kx_int(_kx_value.replace("-", ""), 16)
except (OSError, ValueError):
_kx_guid = 0
else:
_kx_calls = (
(_kx_os.open, "open"),
(_kx_os.read, "read"),
(_kx_os.close, "close"),
# Read from the module's dict: Windows has no uname, and a dict's get is no name to replace.
(_kx_os.__dict__.get("uname"), "uname"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "posix"
):
_kx_trusted = False
_kx_linux = _kx_trusted
if _kx_trusted and _kx_calls[3][0]().sysname == "Darwin":
# macOS: the hardware UUID from libSystem's gethostuuid(), through _ctypes's own dlopen and
# dlsym and types made by _ctypes's own metaclasses; never a file root could write.
_kx_linux = False
_kx_c: _kx_typing.Any = _kx_ctypes
_kx_trusted = _kx_c is not None
_kx_calls = ((_kx_c.dlopen, "dlopen"), (_kx_c.dlsym, "dlsym")) if _kx_trusted else ()
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "_ctypes"
):
_kx_trusted = False
_kx_kinds: _kx_typing.Any = ()
if _kx_trusted:
_kx_c = _kx_calls[0][0].__self__
_kx_kinds = (_kx_c.CFuncPtr, _kx_c.Array, _kx_c._SimpleCData) # noqa: SLF001
for _kx_kind, _kx_name in (
(_kx_kinds[0], "CFuncPtr"),
(_kx_kinds[1], "Array"),
(_kx_kinds[2], "_SimpleCData"),
):
if not (
_kx_type(_kx_kind.__name__) is _kx_str
and _kx_kind.__name__ == _kx_name
and _kx_kind.__module__ == "_ctypes"
and _kx_type(_kx_kind).__module__ == "_ctypes"
):
_kx_trusted = False
_kx_trusted = _kx_trusted and _kx_type(_kx_c.FUNCFLAG_CDECL) is _kx_int
if _kx_trusted:
_kx_simple: _kx_typing.Any = _kx_type(_kx_kinds[2])
_kx_array: _kx_typing.Any = _kx_type(_kx_kinds[1])
_kx_byte: _kx_typing.Any = _kx_simple("Byte", (_kx_kinds[2],), {"_type_": "B"})
_kx_long: _kx_typing.Any = _kx_simple("Int64", (_kx_kinds[2],), {"_type_": "q"})
_kx_result: _kx_typing.Any = _kx_simple("Int32", (_kx_kinds[2],), {"_type_": "i"})
_kx_value = _kx_array("Identifier", (_kx_kinds[1],), {"_type_": _kx_byte, "_length_": 16})()
# struct timespec: wait at most 5 seconds (zero would wait for ever).
_kx_wait: _kx_typing.Any = _kx_array("Wait", (_kx_kinds[1],), {"_type_": _kx_long, "_length_": 2})(5, 0)
_kx_call = _kx_type(_kx_kinds[0])(
"Call", (_kx_kinds[0],), {"_flags_": _kx_c.FUNCFLAG_CDECL, "_restype_": _kx_result}
)
try:
_kx_address: _kx_typing.Any = _kx_calls[1][0](
_kx_calls[0][0]("/usr/lib/libSystem.B.dylib", 2), "gethostuuid"
)
if _kx_call(_kx_address)(_kx_value, _kx_wait) == 0:
_kx_guid = _kx_int.from_bytes(b"".__class__(_kx_value), "big")
except (OSError, AttributeError, TypeError, ValueError):
_kx_guid = 0
for _kx_path in ("/etc/machine-id", "/var/lib/dbus/machine-id") if _kx_linux else ():
try:
_kx_handle = _kx_calls[0][0](_kx_path, 0)
try:
_kx_value = _kx_calls[1][0](_kx_handle, 64).strip().decode("ascii", "replace")
finally:
_kx_calls[2][0](_kx_handle)
except OSError:
continue
if _kx_value.__len__() == 32: # noqa: PLR2004
try:
_kx_guid = _kx_int(_kx_value, 16)
except ValueError:
_kx_guid = 0
break
_kx_ok = (
0 < _kx_guid < 2**128
and _kx_grant[3] - 3600 <= _kx_now <= _kx_grant[2]
and (_kx_grant[4] == 0 or _kx_now < _kx_grant[4])
and _kx_grant[5] == _kx_hash(b"kx-machine-1\x00" + _kx_guid.to_bytes(16, "big")).hexdigest()
)
if _kx_ok:
_kx_digest: _kx_typing.Any = _kx_hash(
"|".join(
(
"kx-seal-1",
_kx_grant[0],
_kx_grant[1],
_kx_grant[5],
f"{_kx_grant[2]}",
f"{_kx_grant[3]}",
f"{_kx_grant[4]}",
)
).encode("ascii")
).digest()
_kx_ok = False
for _kx_modulus, _kx_size in ((0xa7debccf8baa9c1dfd7bb490a6b8f2a3f65eeb777607b81d61e7072436f29110de9522cd6447c3e4ca495c5204990150082827aaa9994c308b6c8900c86702ba142502cb9223444bd50c7183bce396683fb5a766cb62b3bc618a84865b8d8f3ae1dc703c1f6f8f6eada53b809f5acefdb74cbf62cfe3630df5482fb872f7bb45fdb0aa56460084ba9113c5d5c43d55d327dd74a1dc770734250fac2850925789c43dbcfef1a6457131951b065eed02af070df94ce5ae7993ff2f9ac103ef0520fc0943169291785294cef5db81f06d03f0b90b1d253f95422dd58db4afdf9e443281bce4c24e86b600675b4fe9869bc028629e0e9334a5b69da491cbfe77cfc730d9366b9a833a9783d540d713d7f1a42c66e82e23a52dec5ee05b544845515fa393eada51cf89298395bb564373a074b47b957aa64e273f97d68cc21aa5c2263fa465b3afc3b263a4ddaaee9b9fb1f155af0bfdd443f176d292e622858f42dc2eded9c9068977d36bbf344275513c7e9da4a3c22b1005ff4a994cad108e0b2b, 384), (0xe5f8068f84fc9c60bff9e59c78bef9bcff1d76378be6567f94acad811a561c7b96eb1a95c5f8eba08886098f7c76bee84f0f13cd72ec40acc9f335d55f0e96c83b91f2c2c9a4ce32626e4088ce1280b0d2c2856da5df12ddf54a6b07358dd244f5fa4e5bd6492fc56772f8ca0ec4cc0d603b21fed29511c1f48b2121c5027548dcc5dc72c5f09e4a342b706561a893654346c98150defa72644d6cddef361f2d06838e30e4109e02d78a856609040b4db247788bafece8e840c55b976091953c528d99eca7108d55adb5fddce09a400ad29a639e376cad423f3c95839bc386409a6b029222b93aa5db1a443f9e7f66f01b5fc0542cca57489d4e3662977e9348ed8888439c57a992b0ff3adc63076cd1181f66b3ab0ca85ea82d9527fce9e8b653e6fdb90359b43b227b3e6a5aa238c6385bb717569f77b1f1d0bb6a40b154142247f5f8fb354d25e94216a5e105a17ae4e2c771adc8ec393c010d0baa8358c2d030598a23ee55f09e294a1ce490cb82a534068082af3731c3c33d0cbf8f35d7, 384),):
if 0 < _kx_grant[6] < _kx_modulus and _kx_grant[6].__pow__(65537, _kx_modulus) == _kx_int.from_bytes(
b"\x00\x01" + b"\xff" * (_kx_size - 54) + b"\x00"
+ b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20" + _kx_digest,
"big",
):
_kx_ok = True
break
if _kx_ok:
break
if _kx_round:
raise _kx_refusal(
"The attribution-analysis license is not held in this process on this computer: call validate_license() first,"
" and check that the license key is set and valid."
)
_kx_validate()
# kx-guard: end
date_col = self.df.column("date")
portfolio = np.asarray(self.df.column("portfolio_returns").to_numpy(), dtype=np.float64)
benchmark = np.asarray(self.df.column("benchmark_returns").to_numpy(), dtype=np.float64)
effects = {
name: np.asarray(self.df.column(name).to_numpy(), dtype=np.float64)
for name in ("alpha", "allocation", "selection", "interaction")
}
linked = link_cumulative(effects, portfolio, benchmark, self.linking)
if self.linking is LinkingMethod.NONE:
portfolio_cumulative = np.cumsum(portfolio)
benchmark_cumulative = np.cumsum(benchmark)
else:
portfolio_cumulative = np.cumprod(1.0 + portfolio) - 1.0
benchmark_cumulative = np.cumprod(1.0 + benchmark) - 1.0
self.brinson_fachler_indexes = pa.table({
"date": date_col,
"portfolio_returns": pa.array(portfolio_cumulative, type=pa.float64()),
"benchmark_returns": pa.array(benchmark_cumulative, type=pa.float64()),
**{name: pa.array(values, type=pa.float64()) for name, values in linked.items()},
})
return self.brinson_fachler_indexes
[docs]
def attribution_plots(self) -> None:
"""
Plot cumulative Brinson-Fachler attribution effects.
Calls :meth:`compute_cumulative_indexes` and then produces a 3-panel
figure:
1. Cumulative portfolio vs benchmark returns.
2. Cumulative alpha.
3. Cumulative allocation, selection, and interaction effects.
Must be called after ``time_series_calculation``.
Sets Attributes
---------------
brinson_fachler_indexes : pa.Table
Cumulative attribution indexes keyed by date (see
:meth:`compute_cumulative_indexes`).
"""
self.compute_cumulative_indexes()
date_col = self.brinson_fachler_indexes.column("date").to_pylist()
cumulative = {
col_name: self.brinson_fachler_indexes.column(col_name).to_pylist()
for col_name in _CUMULATIVE_COLUMNS
}
_fig, axes = plt.subplots(3, 1, figsize=(10, 14))
axes[0].plot(date_col, cumulative["portfolio_returns"], label="portfolio_returns")
axes[0].plot(date_col, cumulative["benchmark_returns"], label="benchmark_returns")
axes[0].set_title("Strategy vs Benchmark Returns")
axes[0].legend()
axes[0].grid(visible=True)
axes[1].plot(date_col, cumulative["alpha"], label="alpha")
axes[1].set_title("Cumulative Alpha")
axes[1].legend()
axes[1].grid(visible=True)
axes[2].plot(date_col, cumulative["allocation"], label="allocation")
axes[2].plot(date_col, cumulative["selection"], label="selection")
axes[2].plot(date_col, cumulative["interaction"], label="interaction")
axes[2].set_title("Allocation, Selection and Interaction Effects")
axes[2].legend()
axes[2].grid(visible=True)
plt.tight_layout(rect=(0, 0, 1, 0.95))
plt.show()