Source code for kaxanuk.attribution_analysis.interfaces.factor_model_arrow_attribution

import logging
import typing

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.compute as pc
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FuncFormatter, PercentFormatter

from kaxanuk.attribution_analysis.entities.attribution_options import (
    AGGREGATE_FACTOR_COLUMNS,
    COMPONENT_COLUMNS,
    FACTOR_DISPLAY_NAMES,
    INDUSTRY_FACTORS,
    STYLE_FACTORS,
    LinkingMethod,
)
from kaxanuk.attribution_analysis.entities.attribution_result import DiagnosticCode
from kaxanuk.attribution_analysis.exceptions import AttributionArgumentError, PerformanceAttributionError
from kaxanuk.attribution_analysis.interfaces.factor_model_arrow_interface import FactorModelArrowAttributionInterface
from kaxanuk.attribution_analysis.modules.diagnostics import log_diagnostic
from kaxanuk.attribution_analysis.modules.factor_totals import cumulative_totals_from_contributions
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

if typing.TYPE_CHECKING:
    # Type-only: matplotlib.typing is not imported at run time.
    from matplotlib.typing import LegendLocType

logger = logging.getLogger(__name__)


def _float_and_null(column: pa.Array | pa.ChunkedArray) -> tuple[np.ndarray, np.ndarray]:
    """
    Float64 values (nulls as NaN) and the null mask of an Arrow column.

    Parameters
    ----------
    column : pa.Array or pa.ChunkedArray
        Numeric column. Decimal columns go through a string cast so each value
        matches ``float(Decimal)`` exactly.

    Returns
    -------
    tuple[np.ndarray, np.ndarray]
        ``(values, nulls)``: float64 values with nulls as NaN, and a boolean
        mask that is True where the column is null.
    """
    nulls = np.asarray(column.is_null().to_numpy(zero_copy_only=False), dtype=bool)
    if pa.types.is_decimal(column.type):
        column = pc.cast(column, pa.string())
    values = pc.fill_null(pc.cast(column, pa.float64()), np.nan)
    return np.asarray(values.to_numpy(zero_copy_only=False), dtype=np.float64), nulls


def _date_label(date: object) -> str:
    """A date as ``YYYY-MM-DD`` for messages (``str`` of anything without ``strftime``)."""
    return date.strftime('%Y-%m-%d') if hasattr(date, 'strftime') else str(date)


def _row_lookup(dates_in_table: list, wanted: list, *, last_wins: bool) -> np.ndarray:
    """
    Row index in a table for each wanted date (-1 when absent).

    Parameters
    ----------
    dates_in_table : list
        The table's date column as Python values.
    wanted : list
        Dates to look up.
    last_wins : bool
        With duplicate dates, use the last row (True) or the first (False).

    Returns
    -------
    np.ndarray
        int64 row positions aligned with ``wanted``.
    """
    position: dict = {}
    for i, d in enumerate(dates_in_table):
        if last_wins or d not in position:
            position[d] = i
    return np.array([position.get(d, -1) for d in wanted], dtype=np.int64)


[docs] class FactorModelArrowAttribution(FactorModelArrowAttributionInterface): """ Multi-factor model attribution implementation using PyArrow. Decomposes portfolio returns into contributions from style factors, industry factors, and an idiosyncratic residual using portfolio weights and per-asset factor return tables. Parameters ---------- daily_portfolio_weights : pa.Table Daily portfolio weights with a ``date_column`` and one float64 column per asset ticker, in any row order: they are sorted by date (see the attribute of the same name). by_factor_factor_returns : dict[str, pa.Table] Mapping of factor name (e.g. ``"f_momentum"``) to a ``pa.Table`` of per-asset factor contributions (each cell: the asset's exposure x the factor return), each with a ``date_column`` and one float64 column per asset. Matched to the weights by date, so the row order does not matter. asset_returns : pa.Table Total asset returns with a ``date_column`` and one float64 column per asset ticker. Matched to the weights by date. portfolio_returns : pa.Table, optional Pre-computed portfolio returns with columns ``date`` and ``portfolio_returns``, matched to the weights by date. Computed from weights and asset returns if not provided. benchmark_returns : pa.Table, optional Benchmark returns table. date_column : str, default ``"date"`` Name of the date column common to all input tables. linking : LinkingMethod or str, default ``LinkingMethod.CARINO`` How cumulative contributions and shares combine periods: ``"carino"``, ``"grap"``, or ``"none"`` (plain running sums, no linking). side : str, default ``"portfolio"`` Which weights these are (``"portfolio"`` or ``"benchmark"``), named in the factor-coverage log line. Attributes ---------- daily_portfolio_weights : pa.Table The weights in ascending date order, the order of every derived table (``portfolio_attribution_ts``, a computed ``portfolio_returns``, ``simulated_rets``, ``pct_df_returns``, ``cumulative_totals()``) and the order linking compounds in, so no result depends on the input row order. The sort is stable: the rows of a repeated date keep their order. String dates sort as text, which is date order for ISO-8601 (``YYYY-MM-DD``). Rows with a null date are dropped, with a warning. Weights already sorted, without null dates, are kept as given (the same table). portfolio_attribution_ts : pa.Table Daily factor contribution time series after ``multifactor_attribution``. simulated_rets : pa.Table Cumulative (linked, unless ``linking="none"``) factor contributions after ``time_series_calculation``. pct_df_returns : pa.Table Daily percentage decomposition after ``calc_pct_area``. Raises ------ AttributionArgumentError If `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, daily_portfolio_weights: pa.Table, by_factor_factor_returns: dict[str, pa.Table], asset_returns: pa.Table, portfolio_returns: pa.Table | None = None, benchmark_returns: pa.Table | None = None, date_column: str = "date", linking: LinkingMethod | str = LinkingMethod.CARINO, side: str = "portfolio", ) -> 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(pd) 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__( daily_portfolio_weights=daily_portfolio_weights, by_factor_factor_returns=by_factor_factor_returns, asset_returns=asset_returns, portfolio_returns=portfolio_returns, benchmark_returns=benchmark_returns, ) self.date_column = date_column self._dropped_dates_warned = False self._unfactored_dates_warned = False self.side = side try: self.linking = LinkingMethod(linking) except (ValueError, TypeError): raise AttributionArgumentError(f"linking must be 'carino', 'grap' or 'none', got {linking!r}") from None # Every derived table follows the weights' row order, and linking compounds in it. self.daily_portfolio_weights = self._sorted_by_date(daily_portfolio_weights) def _sorted_by_date(self, weights: pa.Table) -> pa.Table: """ `weights` in ascending date order, without the rows that have no date. The sort is stable, so the rows of a repeated date keep their order. String dates sort as text, which is date order for ISO-8601 (``YYYY-MM-DD``). Rows with a null date are dropped with a warning: they have no place in the date order and would otherwise pair with the undated rows of the other tables. Parameters ---------- weights : pa.Table Weights with ``self.date_column``. Returns ------- pa.Table `weights` itself when it is already sorted and has no null date, otherwise a sorted copy. """ dates = weights.column(self.date_column) if dates.null_count: log_diagnostic( logger, DiagnosticCode.FACTOR_WEIGHT_ROWS_WITHOUT_DATE, 'Factor model: %d %s weight rows have no date and are not attributed.', dates.null_count, self.side, count=dates.null_count, details={"side": self.side}, ) weights = weights.filter(pc.is_valid(dates)) order = pc.sort_indices(weights, sort_keys=[(self.date_column, "ascending")]) if np.array_equal(order.to_numpy(), np.arange(weights.num_rows)): return weights return weights.take(order) def _get_non_date_columns(self, table: pa.Table) -> list[str]: """ Return column names excluding the date column. Parameters ---------- table : pa.Table Any table with a date column plus data columns. Returns ------- list[str] Non-date column names. """ return [name for name in table.column_names if name != self.date_column] def _compute_portfolio_returns(self) -> pa.Table: """ Compute portfolio-level returns from weights and asset returns. Calculates the weighted sum of asset returns for each date of the weights, in their (ascending date) order, and stores the result in ``self.portfolio_returns``. A date on which no held asset has a return (e.g. the first price date, where ``pct_change`` has no prior price) gets a null portfolio return, not 0, so ``cumulative_pct_decomp`` excludes it from the shares. Returns ------- pa.Table The table it stores on ``self.portfolio_returns``: columns ``date_column`` and ``portfolio_returns``. """ weights = self.daily_portfolio_weights w_dates = weights.column(self.date_column).to_pylist() r_rows = _row_lookup(self.asset_returns.column(self.date_column).to_pylist(), w_dates, last_wins=True) kept = r_rows >= 0 kept_rows = r_rows[kept] return_columns = set(self.asset_returns.column_names) asset_cols = [c for c in self._get_non_date_columns(weights) if c in return_columns] totals = np.zeros(kept_rows.size) any_pair = np.zeros(kept_rows.size, dtype=bool) for col in asset_cols: w_values, w_nulls = _float_and_null(weights.column(col)) r_values, r_nulls = _float_and_null(self.asset_returns.column(col)) pair = ~w_nulls[kept] & ~r_nulls[kept_rows] totals += np.where(pair, w_values[kept] * r_values[kept_rows], 0.0) any_pair |= pair out_dates = [d for d, k in zip(w_dates, kept, strict=True) if k] self.portfolio_returns = pa.table({ self.date_column: pa.array(out_dates), "portfolio_returns": pa.array(totals, type=pa.float64(), mask=~any_pair), }) return self.portfolio_returns def _portfolio_returns_table(self) -> pa.Table: """``portfolio_returns``, computed from the weights and asset returns when it was not given.""" if self.portfolio_returns is None: return self._compute_portfolio_returns() return self.portfolio_returns
[docs] def multifactor_attribution(self) -> None: """ Calculate multi-factor attribution across all dates. For each date in ``daily_portfolio_weights``, in ascending order, computes the portfolio-weighted sum of each factor's per-asset returns. Logs average factor coverage across the portfolio. Sets Attributes --------------- portfolio_attribution_ts : pa.Table Daily factor contributions with a date column and one float64 column per factor. """ # 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(pd) 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 weights = self.daily_portfolio_weights dates = weights.column(self.date_column).to_pylist() assets = self._get_non_date_columns(weights) n_dates, n_assets = len(dates), len(assets) asset_position = {a: j for j, a in enumerate(assets)} # Null and 0.0 weights are not holdings; a non-null NaN weight is (and propagates). weight_values = np.zeros((n_dates, n_assets)) held = np.zeros((n_dates, n_assets), dtype=bool) for j, asset in enumerate(assets): values, nulls = _float_and_null(weights.column(asset)) weight_values[:, j] = np.where(nulls, 0.0, values) held[:, j] = ~nulls & (values != 0.0) has_weight = held.any(axis=1) factor_present = np.zeros(n_dates, dtype=bool) covered = np.zeros((n_dates, n_assets), dtype=bool) per_factor: dict[str, tuple[np.ndarray, np.ndarray]] = {} for factor_name, factor_table in self.by_factor_factor_returns.items(): # Return components (carry, dividends) are contributions, not factor exposure: no coverage. counts_as_coverage = factor_name not in COMPONENT_COLUMNS rows = _row_lookup(factor_table.column(self.date_column).to_pylist(), dates, last_wins=True) on_date = rows >= 0 on_rows = rows[on_date] contribution = np.zeros(n_dates) for col in self._get_non_date_columns(factor_table): position = asset_position.get(col) if position is None: continue values, nulls = _float_and_null(factor_table.column(col)) factor_values = np.zeros(n_dates) factor_valid = np.zeros(n_dates, dtype=bool) factor_values[on_date] = values[on_rows] factor_valid[on_date] = ~nulls[on_rows] valid = factor_valid & held[:, position] # Masked-out cells (e.g. 0.0 weight x inf factor) may give NaN; np.where discards them. with np.errstate(invalid="ignore", over="ignore"): contribution += np.where(valid, weight_values[:, position] * factor_values, 0.0) if counts_as_coverage: covered[:, position] |= valid per_factor[factor_name] = (contribution, on_date) factor_present |= on_date keep = has_weight & factor_present if not keep.any(): self.portfolio_attribution_ts = pa.table({ self.date_column: pa.array([], type=pa.timestamp("ns")) }) return coverage = np.where(covered, weight_values, 0.0).sum(axis=1)[keep] logger.info( 'Average total factor coverage throughout the %s : %s', self.side, f'{float(coverage.mean()): .4%}' ) kept_dates = [d for d, k in zip(dates, keep, strict=True) if k] columns = {self.date_column: pa.array(kept_dates)} for factor_name in sorted(name for name, (_, on_date) in per_factor.items() if (on_date & keep).any()): contribution, on_date = per_factor[factor_name] columns[factor_name] = pa.array(np.where(on_date, contribution, 0.0)[keep], type=pa.float64()) self.portfolio_attribution_ts = pa.table(columns)
def _attribution_window(self) -> tuple[list, list[bool], np.ndarray, int]: """ Attribution dates that also have a non-null portfolio return. Returns ------- tuple ``(window_dates, keep, returns, dropped)``: the kept dates in ``portfolio_attribution_ts`` (ascending) order, a keep-mask over all attribution dates, the portfolio returns on the kept dates, and how many attribution dates were dropped. """ returns_by_date = self._returns_by_date() attr_dates = self.portfolio_attribution_ts.column(self.date_column).to_pylist() keep = [d in returns_by_date for d in attr_dates] window_dates = [d for d, k in zip(attr_dates, keep, strict=True) if k] returns = np.array([returns_by_date[d] for d in window_dates], dtype=np.float64) return window_dates, keep, returns, keep.count(False) def _returns_by_date(self) -> dict: """Non-null portfolio return by date (computed first when it was not given; a later row wins).""" portfolio_returns = self._portfolio_returns_table() return { d: v for d, v in zip( portfolio_returns.column(self.date_column).to_pylist(), portfolio_returns.column("portfolio_returns").to_pylist(), strict=True, ) if v is not None } def _window_contributions(self, columns: list[str], keep: list[bool]) -> dict[str, np.ndarray]: """Daily contributions of `columns` on the kept dates (nulls as 0).""" return { col: np.array( [(v or 0.0) for v, k in zip(self.portfolio_attribution_ts.column(col).to_pylist(), keep, strict=True) if k], dtype=np.float64, ) for col in columns } def _warn_dropped_dates(self, keep: list[bool]) -> None: """Warn (once per instance) about the attribution dates `keep` leaves out: those without a portfolio return.""" dropped = keep.count(False) if dropped and not self._dropped_dates_warned: dates = self.portfolio_attribution_ts.column(self.date_column).to_pylist() first_dropped = next(date for date, kept in zip(dates, keep, strict=True) if not kept) log_diagnostic( logger, DiagnosticCode.FACTOR_DATES_WITHOUT_PORTFOLIO_RETURN, 'Factor decomposition: %d attribution dates have no portfolio return ' 'and are excluded from the linked contributions, totals and shares.', dropped, count=dropped, first_date=first_dropped, details={"side": self.side}, ) self._dropped_dates_warned = True def _warn_unfactored_dates(self) -> None: """ Warn (once per instance) about dates with a portfolio return that the factors do not attribute. Such a date is not in ``portfolio_attribution_ts``: no factor table has a row for it, or no asset has a non-zero weight on it. The cumulative contributions, shares and totals leave its return out, so the cumulative portfolio return they reconcile to differs from the portfolio's own. A return of 0 (e.g. a day held entirely in cash) is not counted: leaving it out changes no total. It only reports; no number changes. """ if self._unfactored_dates_warned: return attributed = set(self.portfolio_attribution_ts.column(self.date_column).to_pylist()) unfactored = [ d for d, v in self._returns_by_date().items() if d is not None and d not in attributed and v != 0.0 ] if unfactored: first_unfactored = min(unfactored) log_diagnostic( logger, DiagnosticCode.FACTOR_DATES_WITHOUT_FACTOR_ATTRIBUTION, 'Factor decomposition: %d dates with a portfolio return have no factor attribution ' '(no factor data or no non-zero weight; first %s) and are excluded from the contributions, ' "shares and totals, so the cumulative portfolio return there differs from the portfolio's own.", len(unfactored), _date_label(first_unfactored), count=len(unfactored), first_date=first_unfactored, details={"side": self.side}, ) self._unfactored_dates_warned = True def _link_window( self, contributions: dict[str, np.ndarray], window_dates: list, returns: np.ndarray, ) -> dict[str, np.ndarray]: """ Link window contributions against the portfolio return (b = 0). Validates the inputs first so an error names the offending date instead of a period index. Raises ------ PerformanceAttributionError If a portfolio return is non-finite or <= -100%, or a contribution is non-finite (both naming the date), or linking itself fails. """ bad = np.flatnonzero(~np.isfinite(returns) | (returns <= -1.0)) if bad.size: i = int(bad[0]) raise PerformanceAttributionError( f"Factor model: portfolio return {float(returns[i])!r} on {_date_label(window_dates[i])} is not a " "finite value above -100%; check the price series for zeros or gaps." ) for name, values in contributions.items(): bad = np.flatnonzero(~np.isfinite(values)) if bad.size: first = _date_label(window_dates[int(bad[0])]) raise PerformanceAttributionError(f"Factor model: factor '{name}' contribution on {first} is not finite") return link_cumulative(contributions, returns, np.zeros_like(returns), self.linking)
[docs] def time_series_calculation(self) -> None: """ Compute cumulative factor contributions over time. With linking (default Carino) the table covers only dates with a portfolio return and each column is the factor's linked cumulative contribution (b = 0), so at every date the linked factors plus the linked residual equal the compounded portfolio return; with ``"none"`` it is the plain running sum over all attribution dates (no linking). Sets Attributes --------------- simulated_rets : pa.Table Cumulative factor contributions with the same columns as ``portfolio_attribution_ts``. Raises ------ PerformanceAttributionError If linking fails: a portfolio return <= -100% or a non-finite value (the message names the date), or cumulative growth overflow/underflow. Dates without a portfolio return are dropped with a warning (logged once per instance). Notes ----- Dates with a non-zero portfolio return but no factor attribution (no factor data, or no non-zero weight) are not in the table either; one warning per instance counts them and names the first. """ # 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(pd) 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._warn_unfactored_dates() if self.linking is LinkingMethod.NONE: columns = {self.date_column: self.portfolio_attribution_ts.column(self.date_column)} for col_name in self._get_non_date_columns(self.portfolio_attribution_ts): col = self.portfolio_attribution_ts.column(col_name) columns[col_name] = pc.cumulative_sum(col, skip_nulls=True) self.simulated_rets = pa.table(columns) return window_dates, keep, returns, _dropped = self._attribution_window() self._warn_dropped_dates(keep) factor_cols = self._get_non_date_columns(self.portfolio_attribution_ts) linked = self._link_window(self._window_contributions(factor_cols, keep), window_dates, returns) date_type = self.portfolio_attribution_ts.schema.field(self.date_column).type self.simulated_rets = pa.table({ self.date_column: pa.array(window_dates, type=date_type), **{col: pa.array(linked[col], type=pa.float64()) for col in factor_cols}, })
[docs] def decompose(self) -> None: """ Daily factor contributions and portfolio returns, without cumulative linking. Runs ``multifactor_attribution`` and computes ``portfolio_returns`` when they were not given. The active factor attribution uses it on the benchmark side, whose cumulative effects are linked against the active return rather than on their own. Raises ------ AttributionArgumentError If ``asset_returns`` is ``None`` (also a ``ValueError``). """ if self.asset_returns is None: raise AttributionArgumentError("asset_returns must be provided") self.multifactor_attribution() self._portfolio_returns_table()
[docs] def run(self) -> None: """ Execute the full attribution pipeline. Runs ``decompose`` (daily contributions and, if not provided, portfolio returns), then ``time_series_calculation``. Raises ------ AttributionArgumentError If ``asset_returns`` is ``None`` (also a ``ValueError``). """ self.decompose() self.time_series_calculation()
[docs] def calc_pct_area(self) -> None: """ Compute daily percentage decomposition of returns by factor. Divides each factor's daily contribution by the total portfolio return to get the fraction attributable to that factor. An idiosyncratic residual column (``f_idio_returns``) captures the portion of the portfolio return not explained by the factors; files in ``AGGREGATE_FACTOR_COLUMNS`` are not factors. The return components (``COMPONENT_COLUMNS``: ``f_carry``, ``f_dividends``) get their own share column and are taken out of the residual like the factors. NaN and Inf values are forward-filled. Sets Attributes --------------- pct_df_returns : pa.Table Daily percentage attribution with the same date column and one float64 column per factor plus ``f_idio_returns``. """ # 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(pd) 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 cols_to_drop = {self.date_column, *AGGREGATE_FACTOR_COLUMNS} factor_cols = [ c for c in self.portfolio_attribution_ts.column_names if c not in cols_to_drop ] attr_dates = self.portfolio_attribution_ts.column(self.date_column).to_pylist() portfolio_returns = self._portfolio_returns_table() pr_dates = portfolio_returns.column(self.date_column).to_pylist() pr_date_to_idx = {d: i for i, d in enumerate(pr_dates)} aligned_pr = [] for d in attr_dates: idx = pr_date_to_idx.get(d) if idx is not None: aligned_pr.append( portfolio_returns.column("portfolio_returns")[idx].as_py() ) else: aligned_pr.append(None) total_returns = pa.array(aligned_pr, type=pa.float64()) row_sums = None for col_name in factor_cols: col = self.portfolio_attribution_ts.column(col_name) row_sums = col if row_sums is None else pc.add(row_sums, col) if row_sums is None: row_sums = pa.array([0.0] * len(attr_dates), type=pa.float64()) idio = pc.subtract(total_returns, row_sums) pct_columns = {self.date_column: self.portfolio_attribution_ts.column(self.date_column)} for col_name in factor_cols: col = self.portfolio_attribution_ts.column(col_name) pct_columns[col_name] = pc.divide(col, total_returns) pct_columns['f_idio_returns'] = pc.divide(idio, total_returns) result_columns = {self.date_column: pct_columns[self.date_column]} for col_name in list(pct_columns.keys()): if col_name == self.date_column: continue values, _ = _float_and_null(pct_columns[col_name]) # Forward-fill null/NaN/Inf from the last finite value (0.0 before the first one). last = np.maximum.accumulate(np.where(np.isfinite(values), np.arange(values.size), -1)) filled = np.where(last >= 0, values[np.maximum(last, 0)], 0.0) result_columns[col_name] = pa.array(filled, type=pa.float64()) self.pct_df_returns = pa.table(result_columns)
def _linked_contributions(self) -> pa.Table: """``simulated_rets``, running ``time_series_calculation`` first if it has not run.""" if getattr(self, "simulated_rets", None) is None: self.time_series_calculation() return self.simulated_rets
[docs] def cumulative_pct_decomp(self) -> dict[str, float]: """ Compute the cumulative percentage decomposition over the attribution window. The window is the set of dates present in both ``portfolio_attribution_ts`` and ``portfolio_returns`` with a non-null portfolio return. With linking (default Carino, ``b = 0``) the total is the portfolio's compounded return over that window and each factor's amount is its linked cumulative contribution; with ``linking="none"`` the total is the sum of daily portfolio returns and each amount the sum of daily contributions. Either way ``idio_returns`` takes the remainder, so the shares sum to one. Attribution dates without a portfolio return are excluded and reported with a warning (once per instance). Dates with a non-zero portfolio return but no factor attribution (no factor data, or no non-zero weight) are outside the window too, so the total then differs from the portfolio's own return over all its dates; another warning (once per instance) counts them and names the first. ``calc_pct_area`` uses the same per-day portfolio return: the daily view is a per-day ratio, while this cumulative view is a ratio of window amounts, so the two need not match numerically. Files named in ``AGGREGATE_FACTOR_COLUMNS`` are never counted as factors. The return components (``f_carry``, ``f_dividends``) are keys of their own and are taken out of ``idio_returns``. Returns ------- dict[str, float] Mapping of factor name (plus ``"idio_returns"``) to its share of the total cumulative portfolio return. Empty if the window has no dates. Notes ----- The total is the portfolio's total (not excess) return. If the factor files hold excess-of-cash returns, the cash return lands in ``idio_returns``. """ # 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(pd) 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 window_dates, keep, returns, _dropped = self._attribution_window() self._warn_dropped_dates(keep) self._warn_unfactored_dates() if not window_dates: return {} cols_to_drop = {self.date_column, *AGGREGATE_FACTOR_COLUMNS} factor_cols = [c for c in self.portfolio_attribution_ts.column_names if c not in cols_to_drop] if self.linking is LinkingMethod.NONE: daily = self._window_contributions(factor_cols, keep) total_final_ret = float(returns.sum()) factor_values = {col: float(values.sum()) for col, values in daily.items()} else: # simulated_rets already holds every factor's linked cumulative contribution over this window. total_final_ret = float(np.prod(1.0 + returns) - 1.0) linked = self._linked_contributions() factor_values = {col: float(linked.column(col)[-1].as_py()) for col in factor_cols} factor_values['idio_returns'] = total_final_ret - sum(factor_values.values()) if total_final_ret == 0: return dict.fromkeys(factor_values, 0.0) return {k: v / total_final_ret for k, v in factor_values.items()}
[docs] def cumulative_totals(self) -> pa.Table: """ Cumulative portfolio, factor, component and idiosyncratic return from the model. The window is the attribution dates that have a portfolio return. ``portfolio_returns`` is the running total of the portfolio return over that window (a date with a non-zero portfolio return but no factor attribution is outside it, reported by one warning per instance), ``factor_returns`` the sum of the cumulative contributions of every factor (files in ``AGGREGATE_FACTOR_COLUMNS`` and the return components in ``COMPONENT_COLUMNS`` excluded), ``carry_returns`` / ``dividends_returns`` those of the components when supplied, and ``idiosyncratic_returns`` the remainder. With linking (``carino``/``grap``) ``portfolio_returns`` is compounded and the window and factor values are those of ``simulated_rets``, so ``factor_returns`` equals the sum of its factor columns (neither aggregates nor components). With linking ``none`` every column is an arithmetic running sum, so ``portfolio_returns`` differs from the compounded ``Total Return`` of the summary statistics. ``simulated_rets`` then also covers attribution dates without a portfolio return (e.g. the first price date) while this table does not, so ``factor_returns`` need not equal the sum of the ``simulated_rets`` columns. Derived from ``simulated_rets`` (see ``modules.factor_totals.cumulative_totals_from_contributions``), so the contributions are not linked again; ``time_series_calculation`` runs first if it has not. Returns ------- pa.Table Columns ``date``, ``portfolio_returns``, ``factor_returns``, then ``carry_returns`` / ``dividends_returns`` when those components were supplied, then ``idiosyncratic_returns``. ``factor_returns`` excludes the components. Empty (with those columns) when the window has no dates. Raises ------ PerformanceAttributionError If linking fails (see ``time_series_calculation``). """ # 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(pd) 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 contributions = self._linked_contributions() self._warn_unfactored_dates() return cumulative_totals_from_contributions( contributions, self._portfolio_returns_table(), self.linking, self.date_column )
# --- Plotting methods (convert to pandas at the matplotlib boundary) ---
[docs] def attribution_plots(self, title: str | None = None) -> None: """ Plot cumulative multi-factor attribution in a 3-panel figure. Panels show: (1) the model's cumulative portfolio / factor / idiosyncratic return, plus carry / dividends when supplied (``cumulative_totals``), (2) style and other factors (every factor that is not an industry or a return component, known style names first), (3) industry factors with a non-zero value. Files in ``AGGREGATE_FACTOR_COLUMNS`` are never drawn. Requires ``time_series_calculation`` to have been run. Parameters ---------- title : str, optional Overall figure title. Currently unused by the plot layout. """ df = self.simulated_rets.to_pandas() if self.date_column in df.columns: df = df.set_index(self.date_column) totals = self.cumulative_totals().to_pandas().set_index(self.date_column) # Same order as the Plotly totals: components after Idiosyncratic, so the colours of the first three # lines (assigned by position) do not depend on which components were supplied. totals_names = { "portfolio_returns": "Portfolio", "factor_returns": "Factors", "idiosyncratic_returns": "Idiosyncratic", "carry_returns": "Carry", "dividends_returns": "Dividends", } totals = totals[[c for c in totals_names if c in totals.columns]].rename(columns=totals_names) totals_title = " / ".join(["Total", "Factor", "Idiosyncratic", *totals.columns[3:]]) factor_cols = [c for c in df.columns if c not in AGGREGATE_FACTOR_COLUMNS and c not in COMPONENT_COLUMNS] style_cols = [c for c in STYLE_FACTORS if c in factor_cols] + sorted( c for c in factor_cols if c not in STYLE_FACTORS and c not in INDUSTRY_FACTORS ) industry_cols = [c for c in INDUSTRY_FACTORS if c in factor_cols] industries_df = df[industry_cols] industries_df = industries_df.loc[:, (industries_df != 0).any(axis=0)] _fig, axes = plt.subplots(3, 1, figsize=(12, 15), sharex=True) def style_axis(ax): ax.grid(visible=True, which="both", axis="both", alpha=0.35) ax.axhline(0, color="black", linewidth=1) ax.yaxis.set_major_formatter(PercentFormatter(xmax=1.0)) leg = ax.get_legend() if leg is not None: ax.legend(loc="upper left") if not totals.empty: totals.plot(ax=axes[0], alpha=0.85) axes[0].set_title(totals_title) style_axis(axes[0]) if style_cols: df[style_cols].plot(ax=axes[1], alpha=0.85) axes[1].set_title("Style and other factors") style_axis(axes[1]) if not industries_df.empty: industries_df.plot(ax=axes[2], alpha=0.85) axes[2].set_title("Industry Returns (non-zero columns)") style_axis(axes[2]) plt.tight_layout(rect=(0, 0, 1, 0.96)) plt.show()
[docs] def plot_stacked_weights_normalized( self, figsize: tuple[int, int] = (14, 7), title: str = "Return Attribution by Factor Over Time", y_label: str = "Share of Total Return", date_fmt: str = "%Y-%m", legend_loc: "LegendLocType" = "upper left", days_of_smoothing: int = 5, ) -> None: """ Plot a normalized stacked area chart of factor contributions. Each factor's absolute contribution is divided by the sum of all absolute contributions to show relative importance over time, smoothed with a trailing rolling mean that uses a partial window at the start, so the chart begins at the first date. The residual (``f_idio_returns``) is labelled "Idiosyncratic" and the return components "Carry" / "Dividends", as in the dashboard. Parameters ---------- figsize : tuple[int, int], default ``(14, 7)`` Matplotlib figure size in inches. title : str, default ``"Return Attribution by Factor Over Time"`` Chart title. A rolling-window suffix is appended automatically. y_label : str, default ``"Share of Total Return"`` Y-axis label. date_fmt : str, default ``"%Y-%m"`` Date format string for the x-axis. legend_loc : str, default ``"upper left"`` Matplotlib legend location. days_of_smoothing : int, default ``5`` Rolling window size in trading days for smoothing. """ self.calc_pct_area() df = self.pct_df_returns.to_pandas() if self.date_column in df.columns: df = df.set_index(self.date_column) df = df.ffill() if not isinstance(df.index, pd.DatetimeIndex): df.index = pd.to_datetime(df.index) df = df.sort_index() df = df.rename(columns=dict(FACTOR_DISPLAY_NAMES)) abs_components = df.abs() abs_total = abs_components.sum(axis=1) pct = abs_components.div(abs_total, axis=0).rolling(days_of_smoothing, min_periods=1).mean() pct = pct.fillna(0.0) colors = [plt.cm.tab20(i % 20) for i in range(len(df.columns))] fig, ax = plt.subplots(figsize=figsize) ax.stackplot( pct.index, [pct[col] for col in pct.columns], labels=list(pct.columns), colors=colors, alpha=0.75, ) ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y:.0%}")) ax.xaxis.set_major_formatter(DateFormatter(date_fmt)) fig.autofmt_xdate() ax.set_title( f"{title} (Rolling {days_of_smoothing}d)", fontsize=14, fontweight="bold", ) ax.set_ylabel(y_label) ax.set_ylim(0, 1) ax.legend(loc=legend_loc, fontsize=8, ncol=3) ax.grid(visible=True, alpha=0.3) plt.tight_layout() plt.show()
[docs] def last_day_decomposition(self, title: str) -> None: """ Plot a horizontal bar chart of cumulative factor decomposition. Shows each factor's percentage contribution to total cumulative return at the final date, colored green (positive) or red (negative). The residual is labelled "Idiosyncratic" and the return components "Carry" / "Dividends", as in the dashboard. Parameters ---------- title : str Chart title. Currently overridden internally to ``"Factor Contributions to Strategy Returns"``. """ total_pct = self.cumulative_pct_decomp() sorted_items = sorted(total_pct.items(), key=lambda x: x[1]) names = [FACTOR_DISPLAY_NAMES.get(item[0], item[0]) for item in sorted_items] values = [item[1] for item in sorted_items] colors = ['red' if v < 0 else 'green' for v in values] plt.figure(figsize=(12, 8)) bars = plt.barh(names, values, color=colors) for bar, value in zip(bars, values, strict=False): plt.text( bar.get_width() + (0.001 if value >= 0 else -0.001), bar.get_y() + bar.get_height() / 2, f"{value:.2%}", va='center', ha='left' if value >= 0 else 'right', ) plt.title("Factor Contributions to Strategy Returns") plt.xlabel("Contribution (%)") plt.tight_layout() plt.show()