attrix-base 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- attrix_base/__init__.py +46 -0
- attrix_base/cache.py +257 -0
- attrix_base/calendar.py +107 -0
- attrix_base/frontier.py +133 -0
- attrix_base/overlay.py +28 -0
- attrix_base/protocol.py +185 -0
- attrix_base/rollforward.py +354 -0
- attrix_base/symbology.py +204 -0
- attrix_base-1.0.0.dist-info/METADATA +119 -0
- attrix_base-1.0.0.dist-info/RECORD +13 -0
- attrix_base-1.0.0.dist-info/WHEEL +5 -0
- attrix_base-1.0.0.dist-info/licenses/LICENSE +202 -0
- attrix_base-1.0.0.dist-info/top_level.txt +1 -0
attrix_base/protocol.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""The data protocol: the ONLY seam between an engine and the outside world.
|
|
2
|
+
|
|
3
|
+
An engine built on this protocol (an analysis, a roll, an identifier mapping) is
|
|
4
|
+
stateless. It never persists, never caches across requests, and never talks to
|
|
5
|
+
a vendor — it declares batch demand through ``Provider.get_data`` and computes
|
|
6
|
+
on whatever comes back. Caching (in-memory demand coverage, negative knowledge)
|
|
7
|
+
is middleware: wrap any Provider in ``CachingProvider`` and the engine cannot
|
|
8
|
+
tell the difference.
|
|
9
|
+
|
|
10
|
+
One verb::
|
|
11
|
+
|
|
12
|
+
get_data(plane, ids, dates, *, columns=None) -> DataFrame | None
|
|
13
|
+
|
|
14
|
+
* ``plane`` — a ``Plane`` value (engine taxonomy, never vendor file names).
|
|
15
|
+
* ``ids`` — id batch to filter to; ``None`` for planes with no id dimension
|
|
16
|
+
(FactorCov, FactorReturn).
|
|
17
|
+
* ``dates`` — explicit ISO dates (any iterable: list/tuple/set; order and
|
|
18
|
+
duplicates are irrelevant), the whole request window in ONE call
|
|
19
|
+
(a provider may derive min/max and range-scan internally).
|
|
20
|
+
PIT is simply a one-date request, not a second paradigm.
|
|
21
|
+
* ``columns``— optional projection, the column analog of ``ids``: return only
|
|
22
|
+
these value/reference columns, plus the plane's key columns
|
|
23
|
+
(``KEY_COLS``), which always ride along unrequested. A requested
|
|
24
|
+
column the data lacks is simply absent, never an error — exactly
|
|
25
|
+
the missing-row philosophy on the other axis. ``None`` = all
|
|
26
|
+
columns. Downstream it doubles as a read hint: a columnar backend
|
|
27
|
+
may prune decode (parquet), a CSV backend may ignore it — either
|
|
28
|
+
way the result must equal the full read projected. It is a USER
|
|
29
|
+
convenience: the engine never passes it, and ``CachingProvider``
|
|
30
|
+
passes it straight through (only full-column frames are cached).
|
|
31
|
+
* return — long/wide frame in the plane's canonical schema below, carrying an
|
|
32
|
+
in-data ``date`` column. Return what exists: a missing (date, id)
|
|
33
|
+
is simply an absent row, never an error. ``None`` = the plane is
|
|
34
|
+
not served at all. The engine diffs demand against the result —
|
|
35
|
+
that diff IS the coverage report.
|
|
36
|
+
|
|
37
|
+
Canonical schemas (all dates Utf8 ISO, values Float64):
|
|
38
|
+
|
|
39
|
+
Exposure date, SecurityID, <one column per factor>
|
|
40
|
+
Risk date, SecurityID, SpecificRisk (annualized SD)
|
|
41
|
+
Return date, SecurityID, TotalReturn (arithmetic, per period)
|
|
42
|
+
FactorCov date, factor, <one column per factor> (annualized variance)
|
|
43
|
+
FactorReturn date, factor, value
|
|
44
|
+
CompWeights date, CompositeID, ConstituentID, weight
|
|
45
|
+
SecurityCov date, SecurityID, OtherID, value (pairwise residual covariance,
|
|
46
|
+
annualized — issuer-specific links like GOOGL/GOOG; each unordered
|
|
47
|
+
pair once, direction irrelevant). ``ids`` is the SUPPORT set: a
|
|
48
|
+
provider may return only pairs with BOTH legs in it, or any
|
|
49
|
+
superset — the engine keeps only support-covered pairs either way.
|
|
50
|
+
Master SecurityID, <reference cols> id-keyed reference data, NO date
|
|
51
|
+
column; a ``STATIC`` plane — date-independent, cached by id and
|
|
52
|
+
assumed immutable. The provider unifies the vendor's security- and
|
|
53
|
+
composite-level master files (composite ids ride in SecurityID),
|
|
54
|
+
exactly as Exposure unifies SecurityExposure + CompExposure.
|
|
55
|
+
SEDOL/CUSIP/ SecurityID + the namesake identifier column(s) — SEDOL7, CUSIP, or
|
|
56
|
+
FIGI (FIGI, BBTICKER). Optional id-keyed reference planes, NO date column,
|
|
57
|
+
all ``STATIC``; consumed by symbology mapping, not the engine.
|
|
58
|
+
FactorMeta factor, <reference cols> factor-keyed reference, NO date
|
|
59
|
+
column; a ``STATIC`` plane (date-independent, cached by id, assumed
|
|
60
|
+
immutable). Carries a grouping column (default ``Category``:
|
|
61
|
+
Style/Industry/Country/Currency) plus passthrough cols (FactorAlias,
|
|
62
|
+
Exterior, ...). The factor analog of Master.
|
|
63
|
+
Calendar date trading days of THIS model's
|
|
64
|
+
market (no id dimension); of the dates asked, return the subset that
|
|
65
|
+
are trading days. Optional — ``None`` when not served. An analysis
|
|
66
|
+
uses it to find the trading day AFTER a holding date, so an
|
|
67
|
+
end-of-day holding can be attributed the return it earns over the
|
|
68
|
+
NEXT period (``calendar.forward_map``); a roll uses it for the
|
|
69
|
+
trading-day grid it compounds over (``calendar.trading_grid``).
|
|
70
|
+
Per-model: a European model's holidays differ from a US one's.
|
|
71
|
+
"""
|
|
72
|
+
from __future__ import annotations
|
|
73
|
+
|
|
74
|
+
from enum import StrEnum
|
|
75
|
+
from typing import Iterable, Protocol, Sequence
|
|
76
|
+
|
|
77
|
+
import polars as pl
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Plane(StrEnum):
|
|
81
|
+
EXPOSURE = "Exposure"
|
|
82
|
+
RISK = "Risk"
|
|
83
|
+
RETURN = "Return"
|
|
84
|
+
FACTOR_COV = "FactorCov"
|
|
85
|
+
FACTOR_RETURN = "FactorReturn"
|
|
86
|
+
COMP_WEIGHTS = "CompWeights"
|
|
87
|
+
SECURITY_COV = "SecurityCov"
|
|
88
|
+
MASTER = "Master"
|
|
89
|
+
SEDOL = "SEDOL"
|
|
90
|
+
CUSIP = "CUSIP"
|
|
91
|
+
FIGI = "FIGI"
|
|
92
|
+
FACTOR_META = "FactorMeta"
|
|
93
|
+
CALENDAR = "Calendar"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
#: id column per plane; None = the plane has no id dimension
|
|
97
|
+
ID_COL = {
|
|
98
|
+
Plane.EXPOSURE: "SecurityID",
|
|
99
|
+
Plane.RISK: "SecurityID",
|
|
100
|
+
Plane.RETURN: "SecurityID",
|
|
101
|
+
Plane.FACTOR_COV: None,
|
|
102
|
+
Plane.FACTOR_RETURN: None,
|
|
103
|
+
Plane.COMP_WEIGHTS: "CompositeID",
|
|
104
|
+
Plane.SECURITY_COV: None, # pairwise: two id legs, no single id column — the
|
|
105
|
+
# cache covers it per date by SUPPORT SET instead,
|
|
106
|
+
# providers filter both pair legs by the ids arg
|
|
107
|
+
Plane.MASTER: "SecurityID", # securities and composites share this id column
|
|
108
|
+
Plane.SEDOL: "SecurityID", # optional identifier reference (SecurityID, SEDOL7)
|
|
109
|
+
Plane.CUSIP: "SecurityID", # optional identifier reference (SecurityID, CUSIP)
|
|
110
|
+
Plane.FIGI: "SecurityID", # optional identifier reference (SecurityID, FIGI, BBTICKER)
|
|
111
|
+
Plane.FACTOR_META: "factor", # factor-keyed reference, like Master but on the factor axis
|
|
112
|
+
Plane.CALENDAR: None, # trading days only; no id dimension
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
#: reference planes: id-keyed, date-independent — cached by id, assumed immutable
|
|
116
|
+
STATIC = {Plane.MASTER, Plane.SEDOL, Plane.CUSIP, Plane.FIGI, Plane.FACTOR_META}
|
|
117
|
+
|
|
118
|
+
#: identity columns per plane — a ``columns=`` projection keeps these
|
|
119
|
+
#: unconditionally; the request selects among the OTHER (value/reference) columns
|
|
120
|
+
KEY_COLS = {
|
|
121
|
+
Plane.EXPOSURE: ("date", "SecurityID"),
|
|
122
|
+
Plane.RISK: ("date", "SecurityID"),
|
|
123
|
+
Plane.RETURN: ("date", "SecurityID"),
|
|
124
|
+
Plane.FACTOR_COV: ("date", "factor"),
|
|
125
|
+
Plane.FACTOR_RETURN: ("date", "factor"),
|
|
126
|
+
Plane.COMP_WEIGHTS: ("date", "CompositeID", "ConstituentID"),
|
|
127
|
+
Plane.SECURITY_COV: ("date", "SecurityID", "OtherID"),
|
|
128
|
+
Plane.MASTER: ("SecurityID",),
|
|
129
|
+
Plane.SEDOL: ("SecurityID",),
|
|
130
|
+
Plane.CUSIP: ("SecurityID",),
|
|
131
|
+
Plane.FIGI: ("SecurityID",),
|
|
132
|
+
Plane.FACTOR_META: ("factor",),
|
|
133
|
+
Plane.CALENDAR: ("date",),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def project(df: pl.DataFrame, keys: Sequence[str],
|
|
138
|
+
columns: Sequence[str] | None) -> pl.DataFrame:
|
|
139
|
+
"""Apply a ``columns`` projection: keys first (in ``keys`` order), then the
|
|
140
|
+
requested columns (in request order, deduped); anything absent is silently
|
|
141
|
+
skipped — the column analog of a missing row. ``columns=None`` = identity."""
|
|
142
|
+
if columns is None:
|
|
143
|
+
return df
|
|
144
|
+
ks = [k for k in keys if k in df.columns]
|
|
145
|
+
return df.select(ks + [c for c in dict.fromkeys(columns)
|
|
146
|
+
if c in df.columns and c not in set(ks)])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class Provider(Protocol):
|
|
150
|
+
def get_data(
|
|
151
|
+
self, plane: str, ids: Sequence[str] | None, dates: Iterable[str],
|
|
152
|
+
*, columns: Sequence[str] | None = None,
|
|
153
|
+
) -> pl.DataFrame | None: ...
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class DictProvider:
|
|
157
|
+
"""Serves frames you supply up front, for tests and notebooks: ``{plane: canonical frame}``.
|
|
158
|
+
A construct-variant frame (RiskPlus factor planes) keys as a ``(plane,
|
|
159
|
+
construct)`` tuple and is served only when ``get_data`` asks for that
|
|
160
|
+
construct.
|
|
161
|
+
|
|
162
|
+
The ``Calendar`` plane is **derived** when not supplied explicitly: its data dates
|
|
163
|
+
ARE its trading calendar (the union of ``date`` columns across the served frames),
|
|
164
|
+
so the return forward-shift works out of the box without a hand-built calendar."""
|
|
165
|
+
|
|
166
|
+
def __init__(self, frames: dict[str, pl.DataFrame]):
|
|
167
|
+
self.frames = dict(frames)
|
|
168
|
+
|
|
169
|
+
def _derived_calendar(self) -> pl.DataFrame | None:
|
|
170
|
+
days = sorted({d for f in self.frames.values()
|
|
171
|
+
if "date" in f.columns for d in f["date"].to_list()})
|
|
172
|
+
return pl.DataFrame({"date": days}, schema={"date": pl.Utf8}) if days else None
|
|
173
|
+
|
|
174
|
+
def get_data(self, plane, ids, dates, *, columns=None, construct=None):
|
|
175
|
+
df = self.frames.get(plane if construct is None else (plane, construct))
|
|
176
|
+
if df is None and construct is None and Plane(plane) is Plane.CALENDAR:
|
|
177
|
+
df = self._derived_calendar() # derive from data dates
|
|
178
|
+
if df is None:
|
|
179
|
+
return None
|
|
180
|
+
if "date" in df.columns: # STATIC reference planes have none
|
|
181
|
+
df = df.filter(pl.col("date").is_in(list(dates)))
|
|
182
|
+
id_col = ID_COL.get(Plane(plane))
|
|
183
|
+
if ids is not None and id_col is not None and id_col in df.columns:
|
|
184
|
+
df = df.filter(pl.col(id_col).is_in(list(ids)))
|
|
185
|
+
return project(df, KEY_COLS[Plane(plane)], columns)
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Passive roll-forward / back-cast: project ONE snapshot over a date window using
|
|
2
|
+
provider returns, deriving the drifted per-date weights an Attribution consumes.
|
|
3
|
+
|
|
4
|
+
Pure: snapshot + returns -> weights, no persistence. It reads the SAME provider as
|
|
5
|
+
Attribution — the ``Return`` plane (compounded total returns, corporate-action
|
|
6
|
+
adjusted) — so wrapping both in one CachingProvider fetches returns once, shared.
|
|
7
|
+
Only the cash return ``r_c`` is not a provider concern (no cash plane); it defaults
|
|
8
|
+
to 0 and can be set on the Snapshot.
|
|
9
|
+
|
|
10
|
+
The roll is anchor-relative, hence bidirectional. With a per-asset cumulative
|
|
11
|
+
index ``Phi``, every date scales by one ratio::
|
|
12
|
+
|
|
13
|
+
value_t = amount_anchor * Phi_t / Phi_anchor
|
|
14
|
+
|
|
15
|
+
t after the anchor multiplies (roll forward); t before divides (back-cast). The
|
|
16
|
+
back-cast reconstructs "had you held this exact basket and never traded" — valid
|
|
17
|
+
only within a no-rebalance segment; spanning a rebalance means a new Snapshot.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
|
|
23
|
+
import polars as pl
|
|
24
|
+
|
|
25
|
+
from .calendar import trading_grid
|
|
26
|
+
from .protocol import Plane
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Snapshot:
|
|
32
|
+
"""A t=anchor portfolio state in ABSOLUTE amounts (shorts stored positive),
|
|
33
|
+
plus the per-period cash return used to roll the cash ledger. Build via
|
|
34
|
+
``amounts`` (Mode A) or ``weights`` (Mode B); both normalize to this state."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, anchor, longs, shorts, cash, nav, cash_return=0.0, groups=None):
|
|
37
|
+
self.anchor = anchor
|
|
38
|
+
self.longs = dict(longs)
|
|
39
|
+
self.shorts = dict(shorts)
|
|
40
|
+
self.cash = float(cash)
|
|
41
|
+
self.nav = float(nav)
|
|
42
|
+
self.cash_return = float(cash_return)
|
|
43
|
+
self.groups = dict(groups or {})
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def amounts(cls, anchor, longs, shorts=None, cash=None, nav=None, cash_return=0.0, groups=None):
|
|
47
|
+
"""Mode A (absolute). Longs required; shorts default empty. Cash and NAV are
|
|
48
|
+
either-or: give one and the other is derived; give both and they are
|
|
49
|
+
reconciled (checksum); give neither and it is rejected."""
|
|
50
|
+
longs, shorts = dict(longs), dict(shorts or {})
|
|
51
|
+
gl, gs = sum(longs.values()), sum(shorts.values())
|
|
52
|
+
if cash is not None and nav is not None:
|
|
53
|
+
if abs(gl - gs + cash - nav) >= 0.01:
|
|
54
|
+
raise ValueError(f"unbalanced: L-S+Cash={gl - gs + cash:.4f} != NAV={nav:.4f}")
|
|
55
|
+
elif cash is not None:
|
|
56
|
+
nav = gl - gs + cash
|
|
57
|
+
elif nav is not None:
|
|
58
|
+
cash = nav - gl + gs
|
|
59
|
+
else:
|
|
60
|
+
raise ValueError("Mode A needs Cash or NAV (at least one)")
|
|
61
|
+
return cls(anchor, longs, shorts, cash, nav, cash_return, groups)
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def weights(cls, anchor, longs, shorts=None, nav=None, cash_return=0.0, groups=None):
|
|
65
|
+
"""Mode B (weights, shorts as positive magnitudes). NAV optional (default
|
|
66
|
+
100). Cash weight is implied: W^C = 1 - sum W^L + sum W^S."""
|
|
67
|
+
longs, shorts = dict(longs), dict(shorts or {})
|
|
68
|
+
nav = 100.0 if nav is None else float(nav)
|
|
69
|
+
cash = nav * (1.0 - sum(longs.values()) + sum(shorts.values()))
|
|
70
|
+
return cls(anchor, {k: nav * v for k, v in longs.items()},
|
|
71
|
+
{k: nav * v for k, v in shorts.items()}, cash, nav, cash_return, groups)
|
|
72
|
+
|
|
73
|
+
# signed absolute amounts at the anchor: long +, short - (so NAV = sum + cash)
|
|
74
|
+
def _signed(self):
|
|
75
|
+
ids = sorted(set(self.longs) | set(self.shorts))
|
|
76
|
+
return ids, [self.longs.get(i, 0.0) - self.shorts.get(i, 0.0) for i in ids]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _grid_or_span(provider, span) -> list[str]:
|
|
80
|
+
"""The trading-day grid spanning ``span`` (filled from the Calendar). Falls back to
|
|
81
|
+
``span`` as-is — with a warning — when no Calendar is served: correct only if
|
|
82
|
+
``span`` is already a contiguous trading-day grid."""
|
|
83
|
+
try:
|
|
84
|
+
return trading_grid(provider, span[0], span[-1], extra=span)
|
|
85
|
+
except ValueError:
|
|
86
|
+
log.warning("no Calendar plane: rolling over the given dates as-is. Results are "
|
|
87
|
+
"wrong if they are not a contiguous trading-day grid (missing days' "
|
|
88
|
+
"returns are silently skipped). Serve Plane.CALENDAR to fill the grid.")
|
|
89
|
+
return span
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def project(snapshot, dates, provider) -> "Roll":
|
|
93
|
+
"""Roll ``snapshot`` over ``dates`` (any side of its anchor) using the provider's
|
|
94
|
+
Return plane. Per-day returns are compounded over the FULL trading-day grid spanning
|
|
95
|
+
the request (filled from the Calendar plane), so a sparse ``dates`` or a gap between
|
|
96
|
+
the anchor and the first date no longer silently drops the intervening days' returns;
|
|
97
|
+
output is still reported at ``dates``. With no Calendar served it falls back to
|
|
98
|
+
``dates`` as-is (a warning; correct only if they are a contiguous grid). A missing
|
|
99
|
+
(date, id) return is reported in ``uncovered`` and the name is dropped from
|
|
100
|
+
``holdings`` that date — treated as liquidated to cash."""
|
|
101
|
+
s = snapshot
|
|
102
|
+
req = sorted(set(dates))
|
|
103
|
+
alld = _grid_or_span(provider, sorted(set(req) | {s.anchor}))
|
|
104
|
+
ids, signed = s._signed()
|
|
105
|
+
amt = pl.DataFrame({"SecurityID": ids, "amount0": signed})
|
|
106
|
+
|
|
107
|
+
ret = provider.get_data(Plane.RETURN, ids, alld) if ids else None
|
|
108
|
+
grid = pl.DataFrame({"SecurityID": [i for i in ids for _ in alld],
|
|
109
|
+
"date": alld * len(ids)})
|
|
110
|
+
if ret is not None and ret.height:
|
|
111
|
+
grid = grid.join(ret.select("date", "SecurityID", "TotalReturn"),
|
|
112
|
+
on=["date", "SecurityID"], how="left")
|
|
113
|
+
else:
|
|
114
|
+
grid = grid.with_columns(pl.lit(None, dtype=pl.Float64).alias("TotalReturn"))
|
|
115
|
+
uncov = grid.filter(pl.col("TotalReturn").is_null()).select("date", "SecurityID")
|
|
116
|
+
|
|
117
|
+
phi = (grid.with_columns(pl.col("TotalReturn").fill_null(0.0))
|
|
118
|
+
.sort(["SecurityID", "date"])
|
|
119
|
+
.with_columns((1.0 + pl.col("TotalReturn")).cum_prod().over("SecurityID").alias("Phi")))
|
|
120
|
+
anchor_phi = phi.filter(pl.col("date") == s.anchor).select("SecurityID", pl.col("Phi").alias("Phi_a"))
|
|
121
|
+
val = (phi.join(anchor_phi, on="SecurityID").join(amt, on="SecurityID")
|
|
122
|
+
.with_columns((pl.col("amount0") * pl.col("Phi") / pl.col("Phi_a")).alias("value"))
|
|
123
|
+
.select("date", "SecurityID", "value"))
|
|
124
|
+
|
|
125
|
+
pos = {d: k for k, d in enumerate(alld)}
|
|
126
|
+
ka = pos[s.anchor]
|
|
127
|
+
cash_df = pl.DataFrame({"date": alld,
|
|
128
|
+
"__cash": [s.cash * (1.0 + s.cash_return) ** (pos[d] - ka) for d in alld]})
|
|
129
|
+
nav = (val.group_by("date").agg(pl.col("value").sum().alias("__risky"))
|
|
130
|
+
.join(cash_df, on="date", how="right") # cash ledger covers every date
|
|
131
|
+
.with_columns(pl.col("__risky").fill_null(0.0))
|
|
132
|
+
.with_columns((pl.col("__risky") + pl.col("__cash")).alias("NAV"))
|
|
133
|
+
.select("date", "NAV"))
|
|
134
|
+
|
|
135
|
+
groups = pl.DataFrame({"SecurityID": ids,
|
|
136
|
+
"Group": [s.groups.get(i) or ("Short" if i in s.shorts else "Long")
|
|
137
|
+
for i in ids]})
|
|
138
|
+
return Roll(s, req, val, nav, groups, uncov)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
_RENAME = {"Date": "date", "ConstituentID": "SecurityID", "Weight": "weight"}
|
|
142
|
+
_STD = {"date", "CompositeID", "SecurityID", "weight", "AssetType", "label", "Group"}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _norm(book):
|
|
146
|
+
h = book.rename({k: v for k, v in _RENAME.items() if k in book.columns})
|
|
147
|
+
label = (pl.coalesce([pl.col("Group"), pl.col("AssetType")])
|
|
148
|
+
if "Group" in h.columns else pl.col("AssetType"))
|
|
149
|
+
return h.with_columns(label.alias("label"))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
_UNCOV_BOOK = {"date": pl.Utf8, "leaf": pl.Utf8}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _roll_segment(edges, target, anchor, grid, provider, nav, cash_return, max_depth):
|
|
156
|
+
"""Drift ONE anchor's nested book over the trading days ``grid`` (which starts at
|
|
157
|
+
``anchor``). Returns ``(book_all, nav_df, uncov)`` for this segment — the shared core
|
|
158
|
+
of the single- and multi-anchor rolls. Only Security/Composite leaves carry market
|
|
159
|
+
returns and drift; a UserComposite's value is the sum of its children; the structure
|
|
160
|
+
is fixed, every edge weight re-derives from drifted values. DAG-safe: a node reached
|
|
161
|
+
through several parents keeps a separate stake per path. Cycles raise."""
|
|
162
|
+
by_parent = {}
|
|
163
|
+
for r in edges.iter_rows(named=True):
|
|
164
|
+
by_parent.setdefault(r["CompositeID"], []).append((r["SecurityID"], r["weight"], r["AssetType"]))
|
|
165
|
+
|
|
166
|
+
paths = [] # each: {leaf, at, stake, edges:[(p,c)], nodes:[...]}
|
|
167
|
+
def walk(node, stake, es, ns, depth):
|
|
168
|
+
if depth > max_depth:
|
|
169
|
+
raise ValueError("book too deep or cyclic")
|
|
170
|
+
for c, w, at in by_parent.get(node, []):
|
|
171
|
+
if c in by_parent: # internal node -> recurse
|
|
172
|
+
walk(c, stake * w, es + [(node, c)], ns + [c], depth + 1)
|
|
173
|
+
else: # leaf asset
|
|
174
|
+
paths.append({"leaf": c, "at": at, "stake": stake * w,
|
|
175
|
+
"edges": es + [(node, c)], "nodes": ns + [c]})
|
|
176
|
+
walk(target, nav, [], [target], 0)
|
|
177
|
+
if not paths:
|
|
178
|
+
return pl.DataFrame(), pl.DataFrame(), pl.DataFrame(schema=_UNCOV_BOOK)
|
|
179
|
+
|
|
180
|
+
P = pl.DataFrame({"pid": range(len(paths)), "leaf": [p["leaf"] for p in paths],
|
|
181
|
+
"stake": [p["stake"] for p in paths]})
|
|
182
|
+
PN = pl.DataFrame({"pid": [i for i, p in enumerate(paths) for _ in p["nodes"]],
|
|
183
|
+
"node": [nd for p in paths for nd in p["nodes"]]})
|
|
184
|
+
PE = pl.DataFrame({"pid": [i for i, p in enumerate(paths) for _ in p["edges"]],
|
|
185
|
+
"parent": [e[0] for p in paths for e in p["edges"]],
|
|
186
|
+
"child": [e[1] for p in paths for e in p["edges"]]})
|
|
187
|
+
|
|
188
|
+
# cumulative-return ratio per leaf (Security/Composite); other leaves stay flat
|
|
189
|
+
leaf_at = {}
|
|
190
|
+
for p in paths:
|
|
191
|
+
leaf_at.setdefault(p["leaf"], p["at"])
|
|
192
|
+
ret_ids = sorted(l for l, at in leaf_at.items() if at in ("Security", "Composite"))
|
|
193
|
+
alld = grid # the segment's trading days
|
|
194
|
+
uncov = pl.DataFrame(schema=_UNCOV_BOOK)
|
|
195
|
+
ratios = []
|
|
196
|
+
if ret_ids:
|
|
197
|
+
ret = provider.get_data(Plane.RETURN, ret_ids, alld)
|
|
198
|
+
g = pl.DataFrame({"leaf": [l for l in ret_ids for _ in alld], "date": alld * len(ret_ids)})
|
|
199
|
+
if ret is not None and ret.height:
|
|
200
|
+
g = g.join(ret.select(pl.col("SecurityID").alias("leaf"), "date", "TotalReturn"),
|
|
201
|
+
on=["leaf", "date"], how="left")
|
|
202
|
+
else:
|
|
203
|
+
g = g.with_columns(pl.lit(None, dtype=pl.Float64).alias("TotalReturn"))
|
|
204
|
+
uncov = g.filter(pl.col("TotalReturn").is_null()).select("date", "leaf")
|
|
205
|
+
phi = (g.with_columns(pl.col("TotalReturn").fill_null(0.0)).sort(["leaf", "date"])
|
|
206
|
+
.with_columns((1.0 + pl.col("TotalReturn")).cum_prod().over("leaf").alias("Phi")))
|
|
207
|
+
anc = phi.filter(pl.col("date") == anchor).select("leaf", pl.col("Phi").alias("Phi_a"))
|
|
208
|
+
ratios.append(phi.join(anc, on="leaf").select(
|
|
209
|
+
"leaf", "date", (pl.col("Phi") / pl.col("Phi_a")).alias("ratio")))
|
|
210
|
+
flat = [l for l in leaf_at if l not in set(ret_ids)]
|
|
211
|
+
if flat:
|
|
212
|
+
ratios.append(pl.DataFrame({"leaf": [l for l in flat for _ in alld],
|
|
213
|
+
"date": alld * len(flat), "ratio": [1.0] * (len(flat) * len(alld))}))
|
|
214
|
+
ratio = pl.concat(ratios)
|
|
215
|
+
|
|
216
|
+
pv = (P.join(ratio, on="leaf").with_columns((pl.col("stake") * pl.col("ratio")).alias("value"))
|
|
217
|
+
.select("pid", "date", "value"))
|
|
218
|
+
node_val = PN.join(pv, on="pid").group_by("node", "date").agg(pl.col("value").sum().alias("V"))
|
|
219
|
+
edge_stake = PE.join(pv, on="pid").group_by("parent", "child", "date").agg(pl.col("value").sum().alias("S"))
|
|
220
|
+
|
|
221
|
+
pos = {d: k for k, d in enumerate(alld)}
|
|
222
|
+
ka = pos[anchor]
|
|
223
|
+
vt = node_val.filter(pl.col("node") == target).select("date", pl.col("V").alias("Vt"))
|
|
224
|
+
cash0 = nav - vt.filter(pl.col("date") == anchor)["Vt"][0]
|
|
225
|
+
cash_df = pl.DataFrame({"date": alld, "__cash": [cash0 * (1.0 + cash_return) ** (pos[d] - ka) for d in alld]})
|
|
226
|
+
nav_df = (vt.join(cash_df, on="date")
|
|
227
|
+
.with_columns((pl.col("Vt") + pl.col("__cash")).alias("NAV")).select("date", "NAV"))
|
|
228
|
+
|
|
229
|
+
ew = (edge_stake.join(node_val.rename({"node": "parent", "V": "Vp"}), on=["parent", "date"])
|
|
230
|
+
.join(nav_df, on="date")
|
|
231
|
+
.with_columns(pl.when(pl.col("parent") == target).then(pl.col("S") / pl.col("NAV"))
|
|
232
|
+
.when(pl.col("Vp") != 0).then(pl.col("S") / pl.col("Vp"))
|
|
233
|
+
.otherwise(0.0).alias("Weight")))
|
|
234
|
+
extras = [c for c in edges.columns if c not in _STD]
|
|
235
|
+
meta = edges.select(["CompositeID", "SecurityID", "AssetType", pl.col("label").alias("Group")] + extras
|
|
236
|
+
).unique(subset=["CompositeID", "SecurityID"], keep="first")
|
|
237
|
+
book_all = (ew.join(meta, left_on=["parent", "child"], right_on=["CompositeID", "SecurityID"])
|
|
238
|
+
.select(pl.col("date").alias("Date"), pl.col("parent").alias("CompositeID"),
|
|
239
|
+
pl.col("child").alias("ConstituentID"), "Weight", "AssetType", "Group", *extras)
|
|
240
|
+
.sort(["Date", "CompositeID", "ConstituentID"]))
|
|
241
|
+
return book_all, nav_df, uncov
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def project_book(book, target, provider, end_date=None, nav=100.0, cash_return=0.0, max_depth=64) -> "BookRoll":
|
|
245
|
+
"""Roll a NESTED book over a daily trading-day grid. **Each distinct date in ``book``
|
|
246
|
+
is a re-anchor (rebalance)**: that date's basket drifts forward over the trading days
|
|
247
|
+
until the NEXT book date, where the next basket takes over; the LAST basket drifts on
|
|
248
|
+
to ``end_date`` (or stops at its own date when ``end_date`` is None). Trading days
|
|
249
|
+
come from the provider's Calendar plane — the daily grid the per-day returns compound
|
|
250
|
+
over; a single-date book with no ``end_date`` needs none. NAV is computed per segment
|
|
251
|
+
and not stitched across rebalances (weights, which Attribution consumes, are what the
|
|
252
|
+
boundaries must keep clean — and they do: each date belongs to exactly one segment)."""
|
|
253
|
+
norm = _norm(book)
|
|
254
|
+
if not norm.height:
|
|
255
|
+
return BookRoll(target, [], pl.DataFrame(), pl.DataFrame(), pl.DataFrame(schema=_UNCOV_BOOK))
|
|
256
|
+
anchors = sorted(set(norm["date"].to_list()))
|
|
257
|
+
if end_date is not None and end_date < anchors[-1]:
|
|
258
|
+
raise ValueError(f"end_date {end_date} precedes the last holding date {anchors[-1]}")
|
|
259
|
+
grid = ([anchors[0]] if len(anchors) == 1 and end_date is None
|
|
260
|
+
else trading_grid(provider, anchors[0], end_date or anchors[-1], extra=anchors))
|
|
261
|
+
|
|
262
|
+
books, navs, uncovs = [], [], []
|
|
263
|
+
for i, a in enumerate(anchors):
|
|
264
|
+
nxt = anchors[i + 1] if i + 1 < len(anchors) else None
|
|
265
|
+
seg = [d for d in grid if d >= a and (nxt is None or d < nxt)] # [anchor_i, anchor_i+1)
|
|
266
|
+
if not seg:
|
|
267
|
+
continue
|
|
268
|
+
b, n, u = _roll_segment(norm.filter(pl.col("date") == a), target, a, seg,
|
|
269
|
+
provider, nav, cash_return, max_depth)
|
|
270
|
+
if b.height:
|
|
271
|
+
books.append(b); navs.append(n); uncovs.append(u)
|
|
272
|
+
book_all = pl.concat(books, how="diagonal_relaxed") if books else pl.DataFrame()
|
|
273
|
+
nav_all = pl.concat(navs) if navs else pl.DataFrame()
|
|
274
|
+
uncov = pl.concat(uncovs) if uncovs else pl.DataFrame(schema=_UNCOV_BOOK)
|
|
275
|
+
return BookRoll(target, grid, book_all, nav_all, uncov.sort(["date", "leaf"]))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class BookRoll:
|
|
279
|
+
"""Result of a nested projection: ``nav`` ledger, ``holdings`` (the per-date
|
|
280
|
+
drifted book ready to hand to an analysis), ``frozen`` (NAV<=0 dates, excluded)."""
|
|
281
|
+
|
|
282
|
+
def __init__(self, target, req, book_all, nav_all, uncov):
|
|
283
|
+
self.target = target
|
|
284
|
+
self._req = req
|
|
285
|
+
self._book = book_all
|
|
286
|
+
self._nav_all = nav_all
|
|
287
|
+
self.uncovered = uncov
|
|
288
|
+
|
|
289
|
+
@property
|
|
290
|
+
def nav(self) -> pl.DataFrame:
|
|
291
|
+
return self._nav_all.filter(pl.col("date").is_in(self._req)).sort("date")
|
|
292
|
+
|
|
293
|
+
@property
|
|
294
|
+
def frozen(self) -> list[str]:
|
|
295
|
+
if not self._nav_all.height:
|
|
296
|
+
return []
|
|
297
|
+
return (self._nav_all.filter((pl.col("NAV") <= 0) & pl.col("date").is_in(self._req))
|
|
298
|
+
.sort("date")["date"].to_list())
|
|
299
|
+
|
|
300
|
+
def holdings(self) -> pl.DataFrame:
|
|
301
|
+
if not self._book.height:
|
|
302
|
+
return self._book
|
|
303
|
+
ok = [d for d in self._req if d not in set(self.frozen)]
|
|
304
|
+
return self._book.filter(pl.col("Date").is_in(ok))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
class Roll:
|
|
308
|
+
"""Result of a projection. ``nav`` is the date->NAV ledger; ``holdings`` emits
|
|
309
|
+
the attrix book (drifted weights, shorts negative, cash excluded — including
|
|
310
|
+
names ``uncovered`` that date, which are treated as cash); dates where NAV<=0
|
|
311
|
+
are ``frozen`` (skipped from holdings, weights undefined)."""
|
|
312
|
+
|
|
313
|
+
def __init__(self, snapshot, req, val, nav, groups, uncov):
|
|
314
|
+
self.snapshot = snapshot
|
|
315
|
+
self._req = req
|
|
316
|
+
self._val = val
|
|
317
|
+
self._nav_all = nav
|
|
318
|
+
self._groups = groups
|
|
319
|
+
self.uncovered = uncov.sort(["date", "SecurityID"])
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def nav(self) -> pl.DataFrame:
|
|
323
|
+
return self._nav_all.filter(pl.col("date").is_in(self._req)).sort("date")
|
|
324
|
+
|
|
325
|
+
@property
|
|
326
|
+
def frozen(self) -> list[str]:
|
|
327
|
+
return (self._nav_all.filter((pl.col("NAV") <= 0) & pl.col("date").is_in(self._req))
|
|
328
|
+
.sort("date")["date"].to_list())
|
|
329
|
+
|
|
330
|
+
def holdings(self, target, asset_type="Security") -> pl.DataFrame:
|
|
331
|
+
if self.frozen:
|
|
332
|
+
log.warning("NAV<=0 on %d date(s); excluded from holdings: %s",
|
|
333
|
+
len(self.frozen), self.frozen)
|
|
334
|
+
held = (self._val.join(self._nav_all, on="date")
|
|
335
|
+
.filter((pl.col("NAV") > 0) & pl.col("date").is_in(self._req)))
|
|
336
|
+
# A name with no return on a date cannot be valued there, so it cannot be a
|
|
337
|
+
# live holding: drop it from the book on its uncovered dates. Its last value
|
|
338
|
+
# still sits in NAV, so the freed weight falls through to implied cash —
|
|
339
|
+
# i.e. the position is treated as liquidated to cash that day, not frozen.
|
|
340
|
+
# (Carrying it as a holding would feed NaN into downstream attribution.)
|
|
341
|
+
if self.uncovered.height:
|
|
342
|
+
kept = held.join(self.uncovered, on=["date", "SecurityID"], how="anti")
|
|
343
|
+
n_cash = held.height - kept.height
|
|
344
|
+
if n_cash:
|
|
345
|
+
log.info("roll: %d (date, id) uncovered -> treated as cash "
|
|
346
|
+
"(excluded from holdings; value remains in NAV)", n_cash)
|
|
347
|
+
held = kept
|
|
348
|
+
return (held.with_columns((pl.col("value") / pl.col("NAV")).alias("Weight"))
|
|
349
|
+
.join(self._groups, on="SecurityID", how="left")
|
|
350
|
+
.select(pl.col("date").alias("Date"),
|
|
351
|
+
pl.lit(target).alias("CompositeID"),
|
|
352
|
+
pl.col("SecurityID").alias("ConstituentID"),
|
|
353
|
+
"Weight", pl.lit(asset_type).alias("AssetType"), "Group")
|
|
354
|
+
.sort(["Date", "ConstituentID"]))
|