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/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""attrix-base: the open foundation of the attrix packages.
|
|
2
|
+
|
|
3
|
+
Everything up to "the portfolio and the model data are ready":
|
|
4
|
+
|
|
5
|
+
* ``protocol`` — the one-verb data protocol: ``Plane``, the canonical plane
|
|
6
|
+
schemas, ``Provider`` and ``DictProvider``.
|
|
7
|
+
* ``cache`` — ``CachingProvider``, in-memory caching middleware.
|
|
8
|
+
* ``overlay`` — ``OverlayProvider``, plane-routing middleware.
|
|
9
|
+
* ``calendar`` — trading-day helpers over the ``Calendar`` plane.
|
|
10
|
+
* ``symbology`` — ``Mapper``, client identifiers to a model's SecurityID.
|
|
11
|
+
* ``rollforward`` — ``Snapshot`` / ``project`` / ``project_book``: drift
|
|
12
|
+
holdings forward or backward with provider returns.
|
|
13
|
+
* ``frontier`` — ``resolve``, the look-through of nested holdings.
|
|
14
|
+
|
|
15
|
+
Data readers live in ``attrix-providers``; the analyses (attribution, factor
|
|
16
|
+
scoring) live in ``attrix``. Both build on this package.
|
|
17
|
+
|
|
18
|
+
Logging follows the standard-library convention: each module logs to
|
|
19
|
+
``getLogger(__name__)`` and the package attaches only a NullHandler — it never
|
|
20
|
+
configures handlers, levels, or the root logger; the application owns that.
|
|
21
|
+
"""
|
|
22
|
+
import logging as _logging
|
|
23
|
+
from importlib.metadata import PackageNotFoundError as _PackageNotFoundError, version as _dist_version
|
|
24
|
+
|
|
25
|
+
from .cache import CachingProvider
|
|
26
|
+
from .calendar import forward_map, trading_days, trading_grid
|
|
27
|
+
from .frontier import resolve
|
|
28
|
+
from .overlay import OverlayProvider
|
|
29
|
+
from .protocol import ID_COL, KEY_COLS, STATIC, DictProvider, Plane, Provider
|
|
30
|
+
from .rollforward import BookRoll, Roll, Snapshot, project, project_book
|
|
31
|
+
from .symbology import Mapper
|
|
32
|
+
|
|
33
|
+
_logging.getLogger(__name__).addHandler(_logging.NullHandler())
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
# The installed distribution's metadata is the single source of truth; nothing
|
|
37
|
+
# in the source tree carries a version literal.
|
|
38
|
+
__version__ = _dist_version("attrix-base")
|
|
39
|
+
except _PackageNotFoundError: # imported from a source tree with no dist installed
|
|
40
|
+
__version__ = "0+unknown"
|
|
41
|
+
|
|
42
|
+
__all__ = ["Plane", "Provider", "DictProvider", "ID_COL", "KEY_COLS", "STATIC",
|
|
43
|
+
"CachingProvider", "OverlayProvider", "Mapper",
|
|
44
|
+
"trading_days", "trading_grid", "forward_map",
|
|
45
|
+
"Snapshot", "project", "project_book", "Roll", "BookRoll",
|
|
46
|
+
"resolve"]
|
attrix_base/cache.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Optional in-memory caching middleware: demand-driven, session-scoped.
|
|
2
|
+
|
|
3
|
+
A pure decorator on the data protocol — the engine cannot tell it is there.
|
|
4
|
+
This layer never persists anything: cross-session warmth belongs to the data
|
|
5
|
+
side (lake, file drop, service cache). Its job is narrower — within a session,
|
|
6
|
+
demand already served must never reach the provider again.
|
|
7
|
+
|
|
8
|
+
The model is 1D, not 2D. Demand is a rectangle (ids x dates), but coverage is
|
|
9
|
+
tracked per date only:
|
|
10
|
+
|
|
11
|
+
_mem[(plane, date)] -> DataFrame rows fetched so far for that date
|
|
12
|
+
_asked[(plane, date)] -> frozenset | ALL ids ever *requested* for that date
|
|
13
|
+
|
|
14
|
+
``_asked`` records what was asked, ``_mem`` what came back; the difference is
|
|
15
|
+
vendor-missing (date, id) cells — negative knowledge, probed once per session.
|
|
16
|
+
ALL marks an ``ids=None`` fetch (factor planes, or an explicit whole-universe
|
|
17
|
+
request); it satisfies any later id set for that date.
|
|
18
|
+
|
|
19
|
+
A request decomposes per date: missing(d) = ids - asked(d). Dates are grouped
|
|
20
|
+
by identical missing set, one batched inner call per group — typically <= 2
|
|
21
|
+
(brand-new dates want all requested ids, partially covered dates want the
|
|
22
|
+
delta), zero when coverage holds. Input id/date order, duplicates, and
|
|
23
|
+
container types never matter.
|
|
24
|
+
|
|
25
|
+
``columns=`` requests bypass the cache entirely (forwarded to the inner
|
|
26
|
+
provider, nothing stored): only full-column frames are cached, so coverage
|
|
27
|
+
stays 1D and every frame of a plane keeps one schema.
|
|
28
|
+
|
|
29
|
+
Pair planes (SecurityCov) carry TWO id legs per row, so per-id patching is
|
|
30
|
+
unsound — pairs(A) + pairs(B) misses the cross pairs of A x B. Coverage per
|
|
31
|
+
date is a SUPPORT SET instead: a request hits only when its ids are a subset
|
|
32
|
+
of the support already fetched; anything wider refetches the UNION support
|
|
33
|
+
for that date and REPLACES the frame (a support-filtered pair frame is tiny,
|
|
34
|
+
so a fresh union fetch beats a pair-complement query). Serving filters both
|
|
35
|
+
legs to the request; an ids=None fetch marks the date complete, as in 1D.
|
|
36
|
+
|
|
37
|
+
Growth is bounded by ``max_bytes``: whole dates are evicted LRU-first, frame
|
|
38
|
+
and coverage together, so an evicted date simply refetches — no coverage
|
|
39
|
+
holes. Asked-but-empty dates keep their (tiny) coverage entry and are never
|
|
40
|
+
evicted. Coverage sets are interned — the dates of one request share one
|
|
41
|
+
frozenset object — so bookkeeping stays negligible next to the frames.
|
|
42
|
+
"""
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
import logging
|
|
46
|
+
|
|
47
|
+
import polars as pl
|
|
48
|
+
|
|
49
|
+
from .protocol import ID_COL, STATIC, Plane
|
|
50
|
+
|
|
51
|
+
log = logging.getLogger(__name__)
|
|
52
|
+
|
|
53
|
+
_EMPTY = frozenset()
|
|
54
|
+
_ALL = object() # coverage value: an ids=None fetch served this date completely
|
|
55
|
+
|
|
56
|
+
#: pair planes: the two id-leg columns; covered per date by SUPPORT SET
|
|
57
|
+
_PAIR_LEGS = {Plane.SECURITY_COV: ("SecurityID", "OtherID")}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CachingProvider:
|
|
61
|
+
"""``inner`` — any protocol Provider; ``max_bytes`` — optional RAM budget for
|
|
62
|
+
cached frames (None = unbounded); whole dates evict least-recently-used."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, inner, max_bytes: int | None = None):
|
|
65
|
+
self.inner = inner
|
|
66
|
+
self.max_bytes = max_bytes
|
|
67
|
+
self._mem: dict[tuple[str, str], pl.DataFrame] = {} # insertion order = LRU
|
|
68
|
+
self._asked: dict[tuple[str, str], object] = {}
|
|
69
|
+
self._bytes = 0
|
|
70
|
+
self._static: dict[str, pl.DataFrame] = {} # STATIC plane -> id-keyed frame
|
|
71
|
+
self._static_asked: dict[str, object] = {} # STATIC plane -> frozenset(ids) | ALL
|
|
72
|
+
|
|
73
|
+
# ---- the protocol verb ----
|
|
74
|
+
def get_data(self, plane, ids, dates, *, columns=None, construct=None):
|
|
75
|
+
if columns is not None:
|
|
76
|
+
# user projection: pass straight through. The cache holds only
|
|
77
|
+
# full-column frames (a projected frame would be served later as if
|
|
78
|
+
# complete), so a projected result is neither served from nor written
|
|
79
|
+
# into it; the inner provider gets the pushdown instead.
|
|
80
|
+
if construct is None:
|
|
81
|
+
return self.inner.get_data(plane, ids, dates, columns=columns)
|
|
82
|
+
return self.inner.get_data(plane, ids, dates, columns=columns,
|
|
83
|
+
construct=construct)
|
|
84
|
+
plane = Plane(plane)
|
|
85
|
+
if construct is not None and (plane in STATIC or plane in _PAIR_LEGS):
|
|
86
|
+
# no construct-variant STATIC/pair data exists today: pass through
|
|
87
|
+
return self.inner.get_data(plane, ids, dates, construct=construct)
|
|
88
|
+
if plane in STATIC:
|
|
89
|
+
return self._get_static(plane, ids, ID_COL.get(plane), dates)
|
|
90
|
+
if plane in _PAIR_LEGS:
|
|
91
|
+
return self._get_pair(plane, ids, dates)
|
|
92
|
+
# the construct variant is a DIFFERENT dataset of the same plane: it keys
|
|
93
|
+
# (and caches) separately, and the inner fetch carries it
|
|
94
|
+
key = str(plane) if construct is None else f"{plane}:{construct}"
|
|
95
|
+
dates = tuple(sorted(set(dates))) # canonical: hashable, order-free
|
|
96
|
+
id_col = ID_COL.get(plane)
|
|
97
|
+
want = None if ids is None or id_col is None else frozenset(ids)
|
|
98
|
+
gaps = self._gaps(key, want, dates)
|
|
99
|
+
if not gaps:
|
|
100
|
+
log.info("hit %s: %d dates served from memory", key, len(dates))
|
|
101
|
+
for miss, ds in gaps.items():
|
|
102
|
+
self._patch(plane, key, miss, ds, construct)
|
|
103
|
+
out = self._serve(key, want, dates, id_col)
|
|
104
|
+
self._evict()
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
# ---- static reference planes: id coverage, date-independent, never evicted ----
|
|
108
|
+
def _get_static(self, plane, ids, id_col, dates):
|
|
109
|
+
"""Cache by id, ignore date (assumed immutable). A date hint — the latest
|
|
110
|
+
requested — is passed to the inner provider only to locate a snapshot;
|
|
111
|
+
coverage and storage are id-keyed. ids missing from the vendor are still
|
|
112
|
+
marked asked, so they are probed once per session, never re-fetched."""
|
|
113
|
+
key = str(plane)
|
|
114
|
+
want = None if ids is None or id_col is None else frozenset(ids)
|
|
115
|
+
asked = self._static_asked.get(key)
|
|
116
|
+
miss = (frozenset() if asked is _ALL
|
|
117
|
+
else None if want is None
|
|
118
|
+
else want - (asked or _EMPTY))
|
|
119
|
+
if miss is None or miss:
|
|
120
|
+
hint = [max(dates)] if dates else []
|
|
121
|
+
got = self.inner.get_data(plane, None if miss is None else sorted(miss), hint)
|
|
122
|
+
if got is not None and got.height:
|
|
123
|
+
old = self._static.get(key)
|
|
124
|
+
self._static[key] = (got if old is None else
|
|
125
|
+
pl.concat([old, got], how="diagonal_relaxed")
|
|
126
|
+
.unique(subset=[id_col], keep="first"))
|
|
127
|
+
log.info("fetch %s: %s names (reference)", key,
|
|
128
|
+
"all" if miss is None else len(miss))
|
|
129
|
+
self._static_asked[key] = _ALL if miss is None else (asked or _EMPTY) | miss
|
|
130
|
+
out = self._static.get(key)
|
|
131
|
+
if out is None:
|
|
132
|
+
return None
|
|
133
|
+
if want is not None and id_col in out.columns:
|
|
134
|
+
return out.filter(pl.col(id_col).is_in(sorted(want)))
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
# ---- pair planes: per-date SUPPORT-SET coverage, union-refetch on widen ----
|
|
138
|
+
def _get_pair(self, plane, ids, dates):
|
|
139
|
+
"""Two id legs per row: a date is covered for a SUPPORT set, hit iff
|
|
140
|
+
the request's ids are a subset. Widening refetches that date for the
|
|
141
|
+
union support and replaces the frame; serving filters both legs."""
|
|
142
|
+
key = str(plane)
|
|
143
|
+
dates = tuple(sorted(set(dates)))
|
|
144
|
+
want = None if ids is None else frozenset(ids)
|
|
145
|
+
groups: dict[object, list[str]] = {} # new support -> dates
|
|
146
|
+
for d in dates:
|
|
147
|
+
asked = self._asked.get((key, d))
|
|
148
|
+
if asked is _ALL:
|
|
149
|
+
continue
|
|
150
|
+
if want is None:
|
|
151
|
+
groups.setdefault(None, []).append(d) # full fetch wanted
|
|
152
|
+
elif not (want <= (asked or _EMPTY)):
|
|
153
|
+
groups.setdefault((asked or _EMPTY) | want, []).append(d)
|
|
154
|
+
if not groups:
|
|
155
|
+
log.info("hit %s: %d dates served from memory", key, len(dates))
|
|
156
|
+
for sup, ds in groups.items():
|
|
157
|
+
log.info("miss %s: fetching pairs over %s names, %d dates",
|
|
158
|
+
key, "all" if sup is None else len(sup), len(ds))
|
|
159
|
+
got = self.inner.get_data(plane, None if sup is None else sorted(sup), ds)
|
|
160
|
+
parts = ({k[0]: v for k, v in got.partition_by("date", as_dict=True).items()}
|
|
161
|
+
if got is not None and got.height else {})
|
|
162
|
+
for d in ds:
|
|
163
|
+
if (sub := parts.get(d)) is not None and sub.height:
|
|
164
|
+
self._put((key, d), sub) # REPLACE: union supersedes
|
|
165
|
+
self._asked[(key, d)] = _ALL if sup is None else sup
|
|
166
|
+
frames = self._resident(key, dates)
|
|
167
|
+
if not frames:
|
|
168
|
+
return None
|
|
169
|
+
out = pl.concat(frames, how="diagonal_relaxed")
|
|
170
|
+
if want is not None:
|
|
171
|
+
la, lb = _PAIR_LEGS[plane]
|
|
172
|
+
out = out.filter(pl.col(la).is_in(sorted(want))
|
|
173
|
+
& pl.col(lb).is_in(sorted(want)))
|
|
174
|
+
self._evict()
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
# ---- gap analysis: per-date set difference, grouped by identical gap ----
|
|
178
|
+
def _gaps(self, key, want, dates):
|
|
179
|
+
groups: dict[object, list[str]] = {}
|
|
180
|
+
for d in dates:
|
|
181
|
+
asked = self._asked.get((key, d))
|
|
182
|
+
if asked is _ALL:
|
|
183
|
+
continue
|
|
184
|
+
if want is None:
|
|
185
|
+
groups.setdefault(None, []).append(d) # full fetch wanted
|
|
186
|
+
elif (miss := want - (asked or _EMPTY)):
|
|
187
|
+
groups.setdefault(miss, []).append(d)
|
|
188
|
+
return groups
|
|
189
|
+
|
|
190
|
+
# ---- one batched inner call per gap group: merge rows, extend coverage ----
|
|
191
|
+
def _patch(self, plane, key, miss, ds, construct=None):
|
|
192
|
+
log.info("miss %s: fetching %s names over %d dates",
|
|
193
|
+
key, "all" if miss is None else len(miss), len(ds))
|
|
194
|
+
want = None if miss is None else sorted(miss)
|
|
195
|
+
got = (self.inner.get_data(plane, want, ds) if construct is None
|
|
196
|
+
else self.inner.get_data(plane, want, ds, construct=construct))
|
|
197
|
+
parts = ({k[0]: v for k, v in got.partition_by("date", as_dict=True).items()}
|
|
198
|
+
if got is not None and got.height else {})
|
|
199
|
+
for d in ds:
|
|
200
|
+
sub = parts.get(d)
|
|
201
|
+
if sub is not None and sub.height:
|
|
202
|
+
old = self._mem.get((key, d))
|
|
203
|
+
self._put((key, d), sub if miss is None or old is None
|
|
204
|
+
else pl.concat([old, sub], how="diagonal_relaxed"))
|
|
205
|
+
if miss is None:
|
|
206
|
+
for d in ds:
|
|
207
|
+
self._asked[(key, d)] = _ALL
|
|
208
|
+
else:
|
|
209
|
+
unions: dict[frozenset, frozenset] = {} # intern: one set per distinct old
|
|
210
|
+
for d in ds:
|
|
211
|
+
old = self._asked.get((key, d), _EMPTY)
|
|
212
|
+
if (new := unions.get(old)) is None:
|
|
213
|
+
new = unions[old] = old | miss
|
|
214
|
+
self._asked[(key, d)] = new
|
|
215
|
+
|
|
216
|
+
def _resident(self, key, dates):
|
|
217
|
+
"""Cached frames for ``dates`` in date order, LRU-touched."""
|
|
218
|
+
frames = []
|
|
219
|
+
for d in dates:
|
|
220
|
+
if (f := self._mem.get((key, d))) is not None:
|
|
221
|
+
self._mem[(key, d)] = self._mem.pop((key, d)) # LRU touch
|
|
222
|
+
frames.append(f)
|
|
223
|
+
return frames
|
|
224
|
+
|
|
225
|
+
def _serve(self, key, want, dates, id_col):
|
|
226
|
+
frames = self._resident(key, dates)
|
|
227
|
+
if not frames:
|
|
228
|
+
return None
|
|
229
|
+
# diagonal: per-date frames of one plane may differ in width when the
|
|
230
|
+
# vendor's column set drifts across the cached history (factor birth/
|
|
231
|
+
# retirement); the union schema carries null where a date lacked the column
|
|
232
|
+
out = pl.concat(frames, how="diagonal_relaxed")
|
|
233
|
+
if want is not None and id_col in out.columns:
|
|
234
|
+
return out.filter(pl.col(id_col).is_in(sorted(want)))
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
# ---- memory accounting ----
|
|
238
|
+
def _put(self, k, df):
|
|
239
|
+
if (old := self._mem.pop(k, None)) is not None:
|
|
240
|
+
self._bytes -= old.estimated_size()
|
|
241
|
+
self._mem[k] = df
|
|
242
|
+
self._bytes += df.estimated_size()
|
|
243
|
+
|
|
244
|
+
def _evict(self):
|
|
245
|
+
"""LRU by whole date, but only planes WITH an id dimension participate:
|
|
246
|
+
the factor planes (FactorCov, FactorReturn) are structurally tiny and hit
|
|
247
|
+
by every request, and the pair plane (SecurityCov) is support-filtered
|
|
248
|
+
down to the issuer-linked pairs of the book — evicting any of them saves
|
|
249
|
+
nothing and costs a provider round trip, so they stay pinned."""
|
|
250
|
+
if self.max_bytes is None or self._bytes <= self.max_bytes:
|
|
251
|
+
return
|
|
252
|
+
for k in [k for k in self._mem if ID_COL.get(Plane(k[0])) is not None]:
|
|
253
|
+
if self._bytes <= self.max_bytes:
|
|
254
|
+
break
|
|
255
|
+
df = self._mem.pop(k)
|
|
256
|
+
self._asked.pop(k, None)
|
|
257
|
+
self._bytes -= df.estimated_size()
|
attrix_base/calendar.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Trading-calendar helpers over a provider's ``Calendar`` plane.
|
|
2
|
+
|
|
3
|
+
``get_data`` takes explicit dates, so a provider cannot be asked for "the trading
|
|
4
|
+
days between X and Y" or "the day after X" directly. Every helper here does the
|
|
5
|
+
same thing instead: ask the Calendar plane about each calendar day of a span and
|
|
6
|
+
keep the days it returns. The Calendar plane is the sole arbiter of what counts
|
|
7
|
+
as a trading day.
|
|
8
|
+
|
|
9
|
+
* ``trading_days`` — the trading days in ``[lo, hi]``; ``None`` when the
|
|
10
|
+
provider serves no Calendar.
|
|
11
|
+
* ``trading_grid`` — the same, as the contiguous grid a roll compounds over;
|
|
12
|
+
raises when there is no Calendar.
|
|
13
|
+
* ``forward_map`` — ``date -> its next trading day``, for forward-timed reads.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
from bisect import bisect_right
|
|
19
|
+
from datetime import date as _date, timedelta
|
|
20
|
+
from typing import Iterable
|
|
21
|
+
|
|
22
|
+
from .protocol import Plane
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _span(lo: str, hi: str, pad_days: int = 0) -> list[str]:
|
|
28
|
+
"""Every calendar day in ``[lo, hi + pad_days]``, as ISO strings."""
|
|
29
|
+
a, b = _date.fromisoformat(lo), _date.fromisoformat(hi)
|
|
30
|
+
return [(a + timedelta(days=k)).isoformat() for k in range((b - a).days + 1 + pad_days)]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _chunks(seq, n):
|
|
34
|
+
for i in range(0, len(seq), n):
|
|
35
|
+
yield seq[i : i + n]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def trading_days(provider, lo: str, hi: str, *, chunk_days: int | None = None) -> list[str] | None:
|
|
39
|
+
"""The sorted trading days in ``[lo, hi]`` (ISO dates, inclusive) from the
|
|
40
|
+
provider's Calendar plane. ``None`` when the provider serves no Calendar for
|
|
41
|
+
the span (the plane is absent, or it returned no row at all). A provider that
|
|
42
|
+
returns rows, none of them a day of the span, gives ``[]``.
|
|
43
|
+
|
|
44
|
+
Only rows whose ``date`` is one of the days asked for count: a provider may
|
|
45
|
+
return more than it was asked, and anything else in the column is ignored.
|
|
46
|
+
|
|
47
|
+
``chunk_days`` splits the fetch into pieces of at most that many calendar
|
|
48
|
+
days, one ``get_data`` call per piece; ``None`` (the default) asks for the
|
|
49
|
+
whole span in one call."""
|
|
50
|
+
span = _span(lo, hi)
|
|
51
|
+
days: set[str] = set()
|
|
52
|
+
served = False
|
|
53
|
+
for chunk in _chunks(span, chunk_days) if chunk_days else [span]:
|
|
54
|
+
log.debug("demand %s: %s names over %d dates", Plane.CALENDAR, "all", len(chunk))
|
|
55
|
+
cal = provider.get_data(Plane.CALENDAR, None, chunk)
|
|
56
|
+
if cal is None or not cal.height or "date" not in cal.columns:
|
|
57
|
+
continue
|
|
58
|
+
served = True
|
|
59
|
+
asked = set(chunk)
|
|
60
|
+
days.update(d for d in cal["date"].to_list() if d in asked)
|
|
61
|
+
return sorted(days) if served else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def trading_grid(provider, lo: str, hi: str, extra: Iterable[str] = ()) -> list[str]:
|
|
65
|
+
"""The contiguous trading days in ``[lo, hi]`` (inclusive) from the provider's
|
|
66
|
+
Calendar plane, unioned with any ``extra`` dates that fall in range (anchors and
|
|
67
|
+
requested dates are kept even should the calendar omit them). Per-day returns
|
|
68
|
+
are compounded over THIS grid, so it must hold every trading day in the span —
|
|
69
|
+
raises ``ValueError`` when no Calendar is served, since the grid cannot
|
|
70
|
+
otherwise be built."""
|
|
71
|
+
days = trading_days(provider, lo, hi)
|
|
72
|
+
if days is None:
|
|
73
|
+
raise ValueError(
|
|
74
|
+
"roll over a date range needs a Calendar plane to fill the trading-day grid, "
|
|
75
|
+
"but the provider served none — give a provider whose get_data serves "
|
|
76
|
+
"Plane.CALENDAR (DictProvider derives one; the QES providers serve one)")
|
|
77
|
+
return sorted(set(days).union(d for d in extra if lo <= d <= hi))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def forward_map(provider, dates, chunk_days: int = 252) -> dict:
|
|
81
|
+
"""``date -> its next trading day``, one uniform rule for EVERY date: each
|
|
82
|
+
date independently maps to the first Calendar trading day strictly after it
|
|
83
|
+
(so D1->next(D1), D2->next(D2), etc. — D2 is resolved on its own, not assumed
|
|
84
|
+
to be D1's successor, even if the dates aren't contiguous).
|
|
85
|
+
|
|
86
|
+
Built from ONE Calendar read over the contiguous range [first, last+14d] — the
|
|
87
|
+
+14d makes the last date's successor visible. A date with no later trading day
|
|
88
|
+
in range (or no Calendar served) is dropped from the map; the caller decides
|
|
89
|
+
what a missing entry means. ``dates`` must be sorted ascending; an empty
|
|
90
|
+
``dates`` returns ``{}`` without fetching. The read is split into
|
|
91
|
+
``chunk_days``-sized ``get_data`` calls."""
|
|
92
|
+
dates = list(dates)
|
|
93
|
+
if not dates:
|
|
94
|
+
return {}
|
|
95
|
+
a = _date.fromisoformat(dates[0])
|
|
96
|
+
hi = (_date.fromisoformat(dates[-1]) + timedelta(days=14)).isoformat()
|
|
97
|
+
days = trading_days(provider, a.isoformat(), hi, chunk_days=chunk_days)
|
|
98
|
+
if not days:
|
|
99
|
+
log.warning("no Calendar plane served: forward-timed reads are uncovered. "
|
|
100
|
+
"Serve Plane.CALENDAR.")
|
|
101
|
+
return {}
|
|
102
|
+
out = {}
|
|
103
|
+
for d in dates: # ISO strings sort chronologically
|
|
104
|
+
k = bisect_right(days, d) # first trading day strictly after d
|
|
105
|
+
if k < len(days):
|
|
106
|
+
out[d] = days[k]
|
|
107
|
+
return out
|
attrix_base/frontier.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""The cut resolver: turn the holdings DAG into the flat leaf set the kernels consume.
|
|
2
|
+
|
|
3
|
+
ONE recursion, parametrized by ``atom`` — the terminal granularity that drives
|
|
4
|
+
every plane's id resolution (linear AND quadratic reuse the same cut):
|
|
5
|
+
|
|
6
|
+
atom="Security" expand everything to securities. UserComposite via stored
|
|
7
|
+
edges, Composite via CompWeights. A Composite with no
|
|
8
|
+
CompWeights cannot expand -> it stays a leaf (a localized
|
|
9
|
+
fallback to atom-Composite for that one node). No
|
|
10
|
+
composite-level Exposure/Return is needed when this resolves.
|
|
11
|
+
atom="Composite" stop at Composite (and Security). UserComposite still expands
|
|
12
|
+
via edges. Composites are atomic: their residual is
|
|
13
|
+
independent (their own CompRisk), the cheap approximation.
|
|
14
|
+
|
|
15
|
+
``fold`` lists labels (holdings ``Group`` values) where DISPLAY stops: a node
|
|
16
|
+
whose label is in ``fold`` still expands for data, but everything below carries
|
|
17
|
+
``node`` = the folded id, so the engine merges those leaves into one display row.
|
|
18
|
+
``atom`` and ``fold`` are independent: atom is the compute floor, fold the display
|
|
19
|
+
aggregation. fold=None -> every leaf displays as itself; the time series never folds.
|
|
20
|
+
|
|
21
|
+
Same id under the same node accumulates weight (multi-path); same id under two
|
|
22
|
+
nodes stays two rows (two display lines, e.g. a security held both directly and
|
|
23
|
+
through a folded sleeve).
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import logging
|
|
28
|
+
|
|
29
|
+
import polars as pl
|
|
30
|
+
|
|
31
|
+
log = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
_OUT = {"date": pl.Utf8, "id": pl.Utf8, "weight": pl.Float64, "kind": pl.Utf8,
|
|
34
|
+
"label": pl.Utf8, "node": pl.Utf8}
|
|
35
|
+
|
|
36
|
+
_KIND = {"Security": "security", "UserComposite": "usercomp"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def resolve(target, dates, get_children, get_compweights,
|
|
40
|
+
atom="Security", fold=None, max_depth=64) -> pl.DataFrame:
|
|
41
|
+
"""``get_children(ids) -> (date, CompositeID, SecurityID, weight, AssetType[, label])``
|
|
42
|
+
— stored edges of UserComposite parents. ``get_compweights(ids) -> (date,
|
|
43
|
+
CompositeID, ConstituentID, weight)`` — provider-composite constituents (only
|
|
44
|
+
consulted when atom='Security'). Returns ``(date, id, weight, kind, label,
|
|
45
|
+
node)``, kind in security/comp/usercomp."""
|
|
46
|
+
fold = set(fold or [])
|
|
47
|
+
deep = atom == "Security"
|
|
48
|
+
|
|
49
|
+
def children(ids):
|
|
50
|
+
n = get_children(ids)
|
|
51
|
+
if not n.is_empty() and "label" not in n.columns:
|
|
52
|
+
n = n.with_columns(pl.col("AssetType").alias("label"))
|
|
53
|
+
return n
|
|
54
|
+
|
|
55
|
+
fr = children([target])
|
|
56
|
+
if fr.is_empty():
|
|
57
|
+
return pl.DataFrame(schema=_OUT)
|
|
58
|
+
fr = fr.filter(pl.col("date").is_in(list(dates))).select(
|
|
59
|
+
"date", pl.col("SecurityID").alias("id"), "weight", "AssetType", "label",
|
|
60
|
+
pl.col("SecurityID").alias("node"))
|
|
61
|
+
if fr.is_empty():
|
|
62
|
+
return pl.DataFrame(schema=_OUT)
|
|
63
|
+
|
|
64
|
+
# a parent pins its children to its own node when it folds (label in fold) or
|
|
65
|
+
# is already inside a folded subtree (node != id)
|
|
66
|
+
pin = pl.col("label").is_in(list(fold)) | (pl.col("node") != pl.col("id"))
|
|
67
|
+
|
|
68
|
+
rows = []
|
|
69
|
+
stuck = [] # composites that should have expanded (atom=Security) but had no CompWeights
|
|
70
|
+
for _ in range(max_depth):
|
|
71
|
+
leaf = (pl.col("AssetType") == "Security") | (
|
|
72
|
+
(pl.col("AssetType") == "Composite") & (not deep))
|
|
73
|
+
rows.append(fr.filter(leaf))
|
|
74
|
+
rest = fr.filter(~leaf)
|
|
75
|
+
if rest.is_empty():
|
|
76
|
+
break
|
|
77
|
+
parts = []
|
|
78
|
+
uc = rest.filter(pl.col("AssetType") == "UserComposite")
|
|
79
|
+
if uc.height:
|
|
80
|
+
n = children(uc["id"].unique().to_list())
|
|
81
|
+
if n.is_empty():
|
|
82
|
+
rows.append(uc) # no edges: stays a row
|
|
83
|
+
else:
|
|
84
|
+
j = uc.join(n, left_on=["date", "id"], right_on=["date", "CompositeID"], how="inner")
|
|
85
|
+
parts.append(j.select(
|
|
86
|
+
"date", pl.col("SecurityID").alias("id"),
|
|
87
|
+
(pl.col("weight") * pl.col("weight_right")).alias("weight"),
|
|
88
|
+
pl.col("AssetType_right").alias("AssetType"),
|
|
89
|
+
pl.col("label_right").alias("label"),
|
|
90
|
+
pl.when(pin).then(pl.col("node")).otherwise(pl.col("SecurityID")).alias("node")))
|
|
91
|
+
miss = uc.join(n.select("date", pl.col("CompositeID").alias("id")).unique(),
|
|
92
|
+
on=["date", "id"], how="anti")
|
|
93
|
+
if miss.height:
|
|
94
|
+
rows.append(miss)
|
|
95
|
+
if deep:
|
|
96
|
+
cp = rest.filter(pl.col("AssetType") == "Composite")
|
|
97
|
+
if cp.height:
|
|
98
|
+
w = get_compweights(cp["id"].unique().to_list())
|
|
99
|
+
if w is None or w.is_empty():
|
|
100
|
+
rows.append(cp) # no weights: stays a row
|
|
101
|
+
stuck.extend(cp["id"].unique().to_list())
|
|
102
|
+
else:
|
|
103
|
+
j = cp.join(w, left_on=["date", "id"], right_on=["date", "CompositeID"], how="inner")
|
|
104
|
+
parts.append(j.select(
|
|
105
|
+
"date", pl.col("ConstituentID").alias("id"),
|
|
106
|
+
(pl.col("weight") * pl.col("weight_right")).alias("weight"),
|
|
107
|
+
pl.lit("Security").alias("AssetType"),
|
|
108
|
+
pl.lit("Security").alias("label"),
|
|
109
|
+
pl.when(pin).then(pl.col("node")).otherwise(pl.col("ConstituentID")).alias("node")))
|
|
110
|
+
miss = cp.join(w.select("date", pl.col("CompositeID").alias("id")).unique(),
|
|
111
|
+
on=["date", "id"], how="anti")
|
|
112
|
+
if miss.height:
|
|
113
|
+
rows.append(miss)
|
|
114
|
+
stuck.extend(miss["id"].unique().to_list())
|
|
115
|
+
if not parts:
|
|
116
|
+
break
|
|
117
|
+
fr = pl.concat(parts)
|
|
118
|
+
|
|
119
|
+
if stuck:
|
|
120
|
+
u = sorted(set(stuck))
|
|
121
|
+
log.debug("atom=Security: %d composite(s) had no CompWeights, kept as atomic "
|
|
122
|
+
"leaves (residual uses CompRisk, no look-through): %s",
|
|
123
|
+
len(u), u if len(u) <= 10 else u[:10] + ["..."])
|
|
124
|
+
|
|
125
|
+
if not any(r.height for r in rows):
|
|
126
|
+
return pl.DataFrame(schema=_OUT)
|
|
127
|
+
out = pl.concat(rows).group_by(["date", "id", "node"]).agg(
|
|
128
|
+
pl.col("weight").sum(),
|
|
129
|
+
pl.col("AssetType").first(),
|
|
130
|
+
pl.col("label").first())
|
|
131
|
+
return out.with_columns(
|
|
132
|
+
pl.col("AssetType").replace_strict(_KIND, default="comp").alias("kind")
|
|
133
|
+
).select("date", "id", "weight", "kind", "label", "node")
|
attrix_base/overlay.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Plane-routing middleware: compose two providers into one.
|
|
2
|
+
|
|
3
|
+
Planes listed in ``planes`` are served by ``overlay``; every other plane falls to
|
|
4
|
+
``base``. A stateless passthrough — the engine cannot tell it from a single
|
|
5
|
+
provider (see ``attrix_base.protocol``: caching is middleware; so is routing). Used to
|
|
6
|
+
swap a subset of planes' data source (e.g. feed the ``EXPOSURE`` plane from a
|
|
7
|
+
RiskPlus z-score feed while structure/mapping planes stay on the base model).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from .protocol import Plane
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OverlayProvider:
|
|
15
|
+
"""Route ``get_data`` by plane. ``base`` and ``overlay`` each implement the
|
|
16
|
+
provider protocol; ``planes`` is the set of planes served by ``overlay`` (its
|
|
17
|
+
members may be ``Plane`` values or their string names). Explicit plane-set
|
|
18
|
+
routing — never a fall-back-on-None — so an empty overlay result cannot
|
|
19
|
+
silently resolve against ``base``."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, base, overlay, planes):
|
|
22
|
+
self.base = base
|
|
23
|
+
self.overlay = overlay
|
|
24
|
+
self.planes = {Plane(p) for p in planes}
|
|
25
|
+
|
|
26
|
+
def get_data(self, plane, ids, dates, *, columns=None):
|
|
27
|
+
target = self.overlay if Plane(plane) in self.planes else self.base
|
|
28
|
+
return target.get_data(plane, ids, dates, columns=columns)
|