perfattr 0.1.0a1__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.
- perfattr/__init__.py +16 -0
- perfattr/attribution.py +763 -0
- perfattr/py.typed +1 -0
- perfattr-0.1.0a1.dist-info/METADATA +77 -0
- perfattr-0.1.0a1.dist-info/RECORD +7 -0
- perfattr-0.1.0a1.dist-info/WHEEL +4 -0
- perfattr-0.1.0a1.dist-info/licenses/LICENSE +21 -0
perfattr/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Portable portfolio performance-attribution calculations."""
|
|
2
|
+
|
|
3
|
+
from perfattr.attribution import (
|
|
4
|
+
AttributionError,
|
|
5
|
+
AttributionResult,
|
|
6
|
+
calculate_attribution,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0a1"
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"AttributionError",
|
|
13
|
+
"AttributionResult",
|
|
14
|
+
"__version__",
|
|
15
|
+
"calculate_attribution",
|
|
16
|
+
]
|
perfattr/attribution.py
ADDED
|
@@ -0,0 +1,763 @@
|
|
|
1
|
+
"""Portable Brinson-Fachler performance-attribution calculations.
|
|
2
|
+
|
|
3
|
+
The initial vertical slice implements one already-aligned reporting period. It keeps
|
|
4
|
+
input normalization, financial validation, calculation, and reconciliation together
|
|
5
|
+
so the financial path remains easy to audit before multi-period behavior is added.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
import math
|
|
12
|
+
from typing import cast
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import numpy.typing as npt
|
|
16
|
+
import pandas as pd
|
|
17
|
+
from pandas.api.types import is_bool_dtype, is_datetime64_dtype, is_numeric_dtype
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_TOLERANCE = 1e-12
|
|
21
|
+
_REQUIRED_COLUMNS = (
|
|
22
|
+
"from_date",
|
|
23
|
+
"thru_date",
|
|
24
|
+
"identifier",
|
|
25
|
+
"weight",
|
|
26
|
+
"return",
|
|
27
|
+
"quantity_of_days",
|
|
28
|
+
)
|
|
29
|
+
_PERIOD_DETAIL_COLUMNS = (
|
|
30
|
+
"from_date",
|
|
31
|
+
"thru_date",
|
|
32
|
+
"quantity_of_days",
|
|
33
|
+
"identifier",
|
|
34
|
+
"portfolio_weight",
|
|
35
|
+
"portfolio_return",
|
|
36
|
+
"portfolio_contribution",
|
|
37
|
+
"benchmark_weight",
|
|
38
|
+
"benchmark_return",
|
|
39
|
+
"benchmark_contribution",
|
|
40
|
+
"active_weight",
|
|
41
|
+
"active_return",
|
|
42
|
+
"active_contribution",
|
|
43
|
+
"allocation_effect",
|
|
44
|
+
"selection_effect",
|
|
45
|
+
"total_effect",
|
|
46
|
+
"linked_portfolio_contribution",
|
|
47
|
+
"linked_benchmark_contribution",
|
|
48
|
+
"linked_active_contribution",
|
|
49
|
+
"linked_allocation_effect",
|
|
50
|
+
"linked_selection_effect",
|
|
51
|
+
"linked_total_effect",
|
|
52
|
+
)
|
|
53
|
+
_PERIOD_SUMMARY_COLUMNS = (
|
|
54
|
+
"from_date",
|
|
55
|
+
"thru_date",
|
|
56
|
+
"quantity_of_days",
|
|
57
|
+
"portfolio_return",
|
|
58
|
+
"benchmark_return",
|
|
59
|
+
"active_return",
|
|
60
|
+
"portfolio_contribution",
|
|
61
|
+
"benchmark_contribution",
|
|
62
|
+
"active_contribution",
|
|
63
|
+
"allocation_effect",
|
|
64
|
+
"selection_effect",
|
|
65
|
+
"total_effect",
|
|
66
|
+
"linked_portfolio_contribution",
|
|
67
|
+
"linked_benchmark_contribution",
|
|
68
|
+
"linked_active_contribution",
|
|
69
|
+
"linked_allocation_effect",
|
|
70
|
+
"linked_selection_effect",
|
|
71
|
+
"linked_total_effect",
|
|
72
|
+
)
|
|
73
|
+
_OVERALL_DETAIL_COLUMNS = (
|
|
74
|
+
"from_date",
|
|
75
|
+
"thru_date",
|
|
76
|
+
"identifier",
|
|
77
|
+
"portfolio_weight",
|
|
78
|
+
"portfolio_return",
|
|
79
|
+
"linked_portfolio_contribution",
|
|
80
|
+
"benchmark_weight",
|
|
81
|
+
"benchmark_return",
|
|
82
|
+
"linked_benchmark_contribution",
|
|
83
|
+
"active_weight",
|
|
84
|
+
"active_return",
|
|
85
|
+
"linked_active_contribution",
|
|
86
|
+
"linked_allocation_effect",
|
|
87
|
+
"linked_selection_effect",
|
|
88
|
+
"linked_total_effect",
|
|
89
|
+
)
|
|
90
|
+
_CUMULATIVE_COLUMNS = (
|
|
91
|
+
"from_date",
|
|
92
|
+
"thru_date",
|
|
93
|
+
"portfolio_return",
|
|
94
|
+
"benchmark_return",
|
|
95
|
+
"active_return",
|
|
96
|
+
"cumulative_portfolio_return",
|
|
97
|
+
"cumulative_benchmark_return",
|
|
98
|
+
"cumulative_active_return",
|
|
99
|
+
"linked_portfolio_contribution",
|
|
100
|
+
"linked_benchmark_contribution",
|
|
101
|
+
"linked_active_contribution",
|
|
102
|
+
"cumulative_portfolio_contribution",
|
|
103
|
+
"cumulative_benchmark_contribution",
|
|
104
|
+
"cumulative_active_contribution",
|
|
105
|
+
"linked_allocation_effect",
|
|
106
|
+
"linked_selection_effect",
|
|
107
|
+
"linked_total_effect",
|
|
108
|
+
"cumulative_allocation_effect",
|
|
109
|
+
"cumulative_selection_effect",
|
|
110
|
+
"cumulative_total_effect",
|
|
111
|
+
)
|
|
112
|
+
_RECONCILIATION_COLUMNS = (
|
|
113
|
+
"scope",
|
|
114
|
+
"from_date",
|
|
115
|
+
"thru_date",
|
|
116
|
+
"check",
|
|
117
|
+
"actual",
|
|
118
|
+
"expected",
|
|
119
|
+
"residual",
|
|
120
|
+
"tolerance",
|
|
121
|
+
"passed",
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class AttributionError(ValueError):
|
|
126
|
+
"""Report invalid financial input or a failed calculation invariant."""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass
|
|
130
|
+
class AttributionResult:
|
|
131
|
+
"""Hold portable attribution result frames.
|
|
132
|
+
|
|
133
|
+
Attributes:
|
|
134
|
+
period_detail: Attribution values for each period and identifier.
|
|
135
|
+
period_summary: Attribution totals for each period.
|
|
136
|
+
overall_detail: Full-horizon values for each identifier.
|
|
137
|
+
cumulative: Chronological period and cumulative totals.
|
|
138
|
+
reconciliation: Passing financial reconciliation evidence.
|
|
139
|
+
|
|
140
|
+
Notes:
|
|
141
|
+
The calculator does not mutate caller-supplied frames. Returned frames belong
|
|
142
|
+
to the caller and are independently mutable.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
period_detail: pd.DataFrame
|
|
146
|
+
period_summary: pd.DataFrame
|
|
147
|
+
overall_detail: pd.DataFrame
|
|
148
|
+
cumulative: pd.DataFrame
|
|
149
|
+
reconciliation: pd.DataFrame
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _float_array(frame: pd.DataFrame, column: str) -> npt.NDArray[np.float64]:
|
|
153
|
+
"""Return a DataFrame column as a float64 NumPy array."""
|
|
154
|
+
return np.asarray(frame[column], dtype=np.float64)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _int_scalar(frame: pd.DataFrame, column: str) -> int:
|
|
158
|
+
"""Return the first value of an integer column as an ordinary int."""
|
|
159
|
+
values = np.asarray(frame[column], dtype=np.int64)
|
|
160
|
+
return int(values[0])
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _has_true(values: pd.Series) -> bool:
|
|
164
|
+
"""Return whether a boolean Series contains a true value."""
|
|
165
|
+
return bool(np.asarray(values, dtype=np.bool_).any())
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _raise_invalid(side: str, message: str) -> None:
|
|
169
|
+
"""Raise a consistently formatted input error."""
|
|
170
|
+
raise AttributionError(f"{side} input {message}")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _normalize_dates(frame: pd.DataFrame, column: str, side: str) -> pd.Series:
|
|
174
|
+
"""Normalize a required date column to timezone-naive midnight values."""
|
|
175
|
+
values = cast(pd.Series, frame[column])
|
|
176
|
+
if _has_true(values.isna()):
|
|
177
|
+
_raise_invalid(side, f"column {column!r} contains null values")
|
|
178
|
+
if is_numeric_dtype(values.dtype) or is_bool_dtype(values.dtype):
|
|
179
|
+
_raise_invalid(side, f"column {column!r} must contain dates")
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
normalized = pd.to_datetime(values, errors="raise", format="mixed")
|
|
183
|
+
except (TypeError, ValueError, OverflowError) as error:
|
|
184
|
+
raise AttributionError(
|
|
185
|
+
f"{side} input column {column!r} contains an invalid date"
|
|
186
|
+
) from error
|
|
187
|
+
|
|
188
|
+
if isinstance(normalized.dtype, pd.DatetimeTZDtype):
|
|
189
|
+
_raise_invalid(side, f"column {column!r} must be timezone-naive")
|
|
190
|
+
if not is_datetime64_dtype(normalized.dtype):
|
|
191
|
+
_raise_invalid(side, f"column {column!r} must be timezone-naive")
|
|
192
|
+
return cast(
|
|
193
|
+
pd.Series,
|
|
194
|
+
normalized.dt.normalize().astype("datetime64[ns]"),
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _normalize_numeric(
|
|
199
|
+
frame: pd.DataFrame,
|
|
200
|
+
column: str,
|
|
201
|
+
side: str,
|
|
202
|
+
*,
|
|
203
|
+
nullable: bool,
|
|
204
|
+
) -> pd.Series:
|
|
205
|
+
"""Validate and normalize one financial numeric column."""
|
|
206
|
+
values = cast(pd.Series, frame[column])
|
|
207
|
+
if is_bool_dtype(values.dtype) or not is_numeric_dtype(values.dtype):
|
|
208
|
+
_raise_invalid(side, f"column {column!r} must contain numbers, not strings or booleans")
|
|
209
|
+
if not nullable and _has_true(values.isna()):
|
|
210
|
+
_raise_invalid(side, f"column {column!r} contains null values")
|
|
211
|
+
|
|
212
|
+
normalized = cast(pd.Series, values.astype("float64"))
|
|
213
|
+
finite_values = np.asarray(normalized.dropna(), dtype=np.float64)
|
|
214
|
+
if not np.isfinite(finite_values).all():
|
|
215
|
+
_raise_invalid(side, f"column {column!r} must contain only finite values")
|
|
216
|
+
return normalized
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _normalize_identifiers(frame: pd.DataFrame, side: str) -> pd.Series:
|
|
220
|
+
"""Validate identifiers without coercing their values."""
|
|
221
|
+
identifiers = cast(pd.Series, frame["identifier"])
|
|
222
|
+
identifier_types = cast(
|
|
223
|
+
pd.Series, identifiers.map(lambda value: isinstance(value, str))
|
|
224
|
+
)
|
|
225
|
+
if _has_true(identifiers.isna()) or not bool(
|
|
226
|
+
np.asarray(identifier_types, dtype=np.bool_).all()
|
|
227
|
+
):
|
|
228
|
+
_raise_invalid(side, "column 'identifier' must contain non-null strings")
|
|
229
|
+
normalized = cast(pd.Series, identifiers.astype("string[python]").str.strip())
|
|
230
|
+
if _has_true(normalized.eq("")):
|
|
231
|
+
_raise_invalid(side, "column 'identifier' contains an empty string")
|
|
232
|
+
return normalized
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _validate_period_structure(frame: pd.DataFrame, side: str) -> None:
|
|
236
|
+
"""Validate dates, unique keys, non-overlap, and constant day counts."""
|
|
237
|
+
key_columns = ["from_date", "thru_date", "identifier"]
|
|
238
|
+
if frame.duplicated(key_columns).any():
|
|
239
|
+
_raise_invalid(side, "contains a duplicate period and identifier key")
|
|
240
|
+
if (frame["from_date"] > frame["thru_date"]).any():
|
|
241
|
+
_raise_invalid(side, "contains a from_date after its thru_date")
|
|
242
|
+
|
|
243
|
+
periods = cast(
|
|
244
|
+
pd.DataFrame,
|
|
245
|
+
frame[["from_date", "thru_date", "quantity_of_days"]].drop_duplicates(),
|
|
246
|
+
).sort_values(["thru_date", "from_date"], kind="stable")
|
|
247
|
+
thru_dates = cast(pd.Series, periods["thru_date"])
|
|
248
|
+
if _has_true(thru_dates.duplicated()):
|
|
249
|
+
_raise_invalid(side, "maps one thru_date to more than one reporting period")
|
|
250
|
+
day_counts = cast(
|
|
251
|
+
pd.Series,
|
|
252
|
+
frame.groupby(["from_date", "thru_date"])["quantity_of_days"].nunique(),
|
|
253
|
+
)
|
|
254
|
+
if _has_true(day_counts.gt(1)):
|
|
255
|
+
_raise_invalid(side, "has inconsistent quantity_of_days within a period")
|
|
256
|
+
if len(periods) > 1:
|
|
257
|
+
starts = np.asarray(periods["from_date"], dtype="datetime64[ns]")
|
|
258
|
+
ends = np.asarray(periods["thru_date"], dtype="datetime64[ns]")
|
|
259
|
+
if np.any(starts[1:] <= ends[:-1]):
|
|
260
|
+
_raise_invalid(side, "contains overlapping reporting periods")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _normalize_input(frame: pd.DataFrame, side: str) -> pd.DataFrame:
|
|
264
|
+
"""Validate and copy one caller-owned prepared attribution frame."""
|
|
265
|
+
if frame.columns.has_duplicates:
|
|
266
|
+
_raise_invalid(side, "contains duplicate column labels")
|
|
267
|
+
missing = [column for column in _REQUIRED_COLUMNS if column not in frame.columns]
|
|
268
|
+
if missing:
|
|
269
|
+
_raise_invalid(side, f"is missing required columns: {', '.join(missing)}")
|
|
270
|
+
if frame.empty:
|
|
271
|
+
_raise_invalid(side, "must not be empty")
|
|
272
|
+
|
|
273
|
+
selected_columns = [*_REQUIRED_COLUMNS]
|
|
274
|
+
if "contribution" in frame.columns:
|
|
275
|
+
selected_columns.append("contribution")
|
|
276
|
+
normalized = cast(pd.DataFrame, frame.loc[:, selected_columns].copy(deep=True))
|
|
277
|
+
normalized["from_date"] = _normalize_dates(normalized, "from_date", side)
|
|
278
|
+
normalized["thru_date"] = _normalize_dates(normalized, "thru_date", side)
|
|
279
|
+
normalized["identifier"] = _normalize_identifiers(normalized, side)
|
|
280
|
+
normalized["weight"] = _normalize_numeric(
|
|
281
|
+
normalized, "weight", side, nullable=False
|
|
282
|
+
)
|
|
283
|
+
normalized["return"] = _normalize_numeric(
|
|
284
|
+
normalized, "return", side, nullable=True
|
|
285
|
+
)
|
|
286
|
+
day_values = _normalize_numeric(
|
|
287
|
+
normalized, "quantity_of_days", side, nullable=False
|
|
288
|
+
)
|
|
289
|
+
day_array = np.asarray(day_values, dtype=np.float64)
|
|
290
|
+
if np.any(day_array <= 0.0) or np.any(day_array != np.floor(day_array)):
|
|
291
|
+
_raise_invalid(side, "column 'quantity_of_days' must contain positive integers")
|
|
292
|
+
normalized["quantity_of_days"] = day_values.astype("int64")
|
|
293
|
+
|
|
294
|
+
input_returns = _float_array(normalized, "return")
|
|
295
|
+
weights = _float_array(normalized, "weight")
|
|
296
|
+
present_returns = ~np.isnan(input_returns)
|
|
297
|
+
if np.any(input_returns[present_returns] <= -1.0):
|
|
298
|
+
_raise_invalid(side, "column 'return' must be greater than -1.0 when present")
|
|
299
|
+
if np.any((weights != 0.0) & ~present_returns):
|
|
300
|
+
_raise_invalid(side, "contains a nonzero weight with a null return")
|
|
301
|
+
|
|
302
|
+
if "contribution" in normalized.columns:
|
|
303
|
+
normalized["contribution"] = _normalize_numeric(
|
|
304
|
+
normalized, "contribution", side, nullable=False
|
|
305
|
+
)
|
|
306
|
+
contributions = _float_array(normalized, "contribution")
|
|
307
|
+
invalid_undefined_returns = (
|
|
308
|
+
(weights == 0.0) & (contributions != 0.0) & present_returns
|
|
309
|
+
)
|
|
310
|
+
if np.any(invalid_undefined_returns):
|
|
311
|
+
_raise_invalid(
|
|
312
|
+
side,
|
|
313
|
+
"requires a null return when weight is zero and contribution is nonzero",
|
|
314
|
+
)
|
|
315
|
+
else:
|
|
316
|
+
contributions = np.zeros(len(normalized), dtype=np.float64)
|
|
317
|
+
np.multiply(weights, input_returns, out=contributions, where=present_returns)
|
|
318
|
+
normalized["contribution"] = contributions
|
|
319
|
+
|
|
320
|
+
effective_returns = np.zeros(len(normalized), dtype=np.float64)
|
|
321
|
+
nonzero_weights = weights != 0.0
|
|
322
|
+
np.divide(
|
|
323
|
+
contributions,
|
|
324
|
+
weights,
|
|
325
|
+
out=effective_returns,
|
|
326
|
+
where=nonzero_weights,
|
|
327
|
+
)
|
|
328
|
+
effective_returns[(weights == 0.0) & (contributions != 0.0)] = np.nan
|
|
329
|
+
if not np.isfinite(effective_returns[~np.isnan(effective_returns)]).all():
|
|
330
|
+
_raise_invalid(side, "produces a non-finite effective return")
|
|
331
|
+
|
|
332
|
+
normalized["input_return"] = input_returns
|
|
333
|
+
normalized["effective_return"] = effective_returns
|
|
334
|
+
_validate_period_structure(normalized, side)
|
|
335
|
+
return normalized.reset_index(drop=True)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _period_keys(frame: pd.DataFrame) -> pd.MultiIndex:
|
|
339
|
+
"""Return the distinct normalized reporting-period keys."""
|
|
340
|
+
periods = cast(
|
|
341
|
+
pd.DataFrame, frame[["from_date", "thru_date"]].drop_duplicates()
|
|
342
|
+
).sort_values(["thru_date", "from_date"], kind="stable")
|
|
343
|
+
return pd.MultiIndex.from_frame(periods)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _validate_matched_period(portfolio: pd.DataFrame, benchmark: pd.DataFrame) -> None:
|
|
347
|
+
"""Validate cross-side period, day-count, weight, and return contracts."""
|
|
348
|
+
portfolio_periods = _period_keys(portfolio)
|
|
349
|
+
benchmark_periods = _period_keys(benchmark)
|
|
350
|
+
if not portfolio_periods.equals(benchmark_periods):
|
|
351
|
+
raise AttributionError("portfolio and benchmark reporting periods must match exactly")
|
|
352
|
+
if len(portfolio_periods) != 1:
|
|
353
|
+
raise AttributionError(
|
|
354
|
+
"the 0.1.0a1 vertical slice supports exactly one reporting period"
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
portfolio_days = _int_scalar(portfolio, "quantity_of_days")
|
|
358
|
+
benchmark_days = _int_scalar(benchmark, "quantity_of_days")
|
|
359
|
+
if portfolio_days != benchmark_days:
|
|
360
|
+
raise AttributionError(
|
|
361
|
+
"portfolio and benchmark quantity_of_days must match for each period"
|
|
362
|
+
)
|
|
363
|
+
for side, frame in (("portfolio", portfolio), ("benchmark", benchmark)):
|
|
364
|
+
weight_sum = float(_float_array(frame, "weight").sum())
|
|
365
|
+
if not math.isclose(weight_sum, 1.0, rel_tol=_TOLERANCE, abs_tol=_TOLERANCE):
|
|
366
|
+
_raise_invalid(side, "weights must sum to 1.0 within tolerance")
|
|
367
|
+
period_return = float(_float_array(frame, "contribution").sum())
|
|
368
|
+
if period_return <= -1.0:
|
|
369
|
+
_raise_invalid(side, "period return must be greater than -1.0")
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _equalize_universe(portfolio: pd.DataFrame, benchmark: pd.DataFrame) -> pd.DataFrame:
|
|
373
|
+
"""Outer-join the two sides and synthesize neutral missing rows."""
|
|
374
|
+
key_columns = ["from_date", "thru_date", "identifier"]
|
|
375
|
+
side_columns = [
|
|
376
|
+
*key_columns,
|
|
377
|
+
"quantity_of_days",
|
|
378
|
+
"weight",
|
|
379
|
+
"input_return",
|
|
380
|
+
"effective_return",
|
|
381
|
+
"contribution",
|
|
382
|
+
]
|
|
383
|
+
portfolio_side = cast(pd.DataFrame, portfolio.loc[:, side_columns]).assign(
|
|
384
|
+
portfolio_present=True
|
|
385
|
+
)
|
|
386
|
+
benchmark_side = cast(pd.DataFrame, benchmark.loc[:, side_columns]).assign(
|
|
387
|
+
benchmark_present=True
|
|
388
|
+
)
|
|
389
|
+
equalized = portfolio_side.merge(
|
|
390
|
+
benchmark_side,
|
|
391
|
+
on=key_columns,
|
|
392
|
+
how="outer",
|
|
393
|
+
suffixes=("_portfolio", "_benchmark"),
|
|
394
|
+
validate="one_to_one",
|
|
395
|
+
sort=False,
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
for side in ("portfolio", "benchmark"):
|
|
399
|
+
missing = equalized[f"{side}_present"].isna()
|
|
400
|
+
for column in ("weight", "input_return", "effective_return", "contribution"):
|
|
401
|
+
equalized.loc[missing, f"{column}_{side}"] = 0.0
|
|
402
|
+
equalized["quantity_of_days"] = equalized[
|
|
403
|
+
"quantity_of_days_portfolio"
|
|
404
|
+
].fillna(equalized["quantity_of_days_benchmark"])
|
|
405
|
+
|
|
406
|
+
equalized = cast(
|
|
407
|
+
pd.DataFrame,
|
|
408
|
+
equalized.sort_values(["thru_date", "identifier"], kind="stable"),
|
|
409
|
+
).reset_index(drop=True)
|
|
410
|
+
return equalized
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _build_period_detail(equalized: pd.DataFrame) -> pd.DataFrame:
|
|
414
|
+
"""Calculate equalized single-period contributions and effects."""
|
|
415
|
+
values = {
|
|
416
|
+
"portfolio_weight": _float_array(equalized, "weight_portfolio"),
|
|
417
|
+
"benchmark_weight": _float_array(equalized, "weight_benchmark"),
|
|
418
|
+
"portfolio_return": _float_array(equalized, "effective_return_portfolio"),
|
|
419
|
+
"benchmark_return": _float_array(equalized, "effective_return_benchmark"),
|
|
420
|
+
"portfolio_contribution": _float_array(equalized, "contribution_portfolio"),
|
|
421
|
+
"benchmark_contribution": _float_array(equalized, "contribution_benchmark"),
|
|
422
|
+
}
|
|
423
|
+
benchmark_total_return = float(values["benchmark_contribution"].sum())
|
|
424
|
+
|
|
425
|
+
active_weight = values["portfolio_weight"] - values["benchmark_weight"]
|
|
426
|
+
active_return = np.full(len(equalized), np.nan, dtype=np.float64)
|
|
427
|
+
defined_active_return = ~np.isnan(values["portfolio_return"]) & ~np.isnan(
|
|
428
|
+
values["benchmark_return"]
|
|
429
|
+
)
|
|
430
|
+
np.subtract(
|
|
431
|
+
values["portfolio_return"],
|
|
432
|
+
values["benchmark_return"],
|
|
433
|
+
out=active_return,
|
|
434
|
+
where=defined_active_return,
|
|
435
|
+
)
|
|
436
|
+
active_contribution = (
|
|
437
|
+
values["portfolio_contribution"] - values["benchmark_contribution"]
|
|
438
|
+
)
|
|
439
|
+
allocation_effect = np.where(
|
|
440
|
+
np.isnan(values["benchmark_return"]),
|
|
441
|
+
0.0,
|
|
442
|
+
active_weight * (values["benchmark_return"] - benchmark_total_return),
|
|
443
|
+
)
|
|
444
|
+
total_effect = active_contribution - active_weight * benchmark_total_return
|
|
445
|
+
selection_effect = total_effect - allocation_effect
|
|
446
|
+
|
|
447
|
+
detail = pd.DataFrame(
|
|
448
|
+
{
|
|
449
|
+
"from_date": equalized["from_date"],
|
|
450
|
+
"thru_date": equalized["thru_date"],
|
|
451
|
+
"quantity_of_days": equalized["quantity_of_days"].astype("int64"),
|
|
452
|
+
"identifier": equalized["identifier"].astype("string[python]"),
|
|
453
|
+
"portfolio_weight": values["portfolio_weight"],
|
|
454
|
+
"portfolio_return": values["portfolio_return"],
|
|
455
|
+
"portfolio_contribution": values["portfolio_contribution"],
|
|
456
|
+
"benchmark_weight": values["benchmark_weight"],
|
|
457
|
+
"benchmark_return": values["benchmark_return"],
|
|
458
|
+
"benchmark_contribution": values["benchmark_contribution"],
|
|
459
|
+
"active_weight": active_weight,
|
|
460
|
+
"active_return": active_return,
|
|
461
|
+
"active_contribution": active_contribution,
|
|
462
|
+
"allocation_effect": allocation_effect,
|
|
463
|
+
"selection_effect": selection_effect,
|
|
464
|
+
"total_effect": total_effect,
|
|
465
|
+
"linked_portfolio_contribution": values[
|
|
466
|
+
"portfolio_contribution"
|
|
467
|
+
].copy(),
|
|
468
|
+
"linked_benchmark_contribution": values[
|
|
469
|
+
"benchmark_contribution"
|
|
470
|
+
].copy(),
|
|
471
|
+
"linked_active_contribution": active_contribution.copy(),
|
|
472
|
+
"linked_allocation_effect": allocation_effect.copy(),
|
|
473
|
+
"linked_selection_effect": selection_effect.copy(),
|
|
474
|
+
"linked_total_effect": total_effect.copy(),
|
|
475
|
+
},
|
|
476
|
+
columns=_PERIOD_DETAIL_COLUMNS,
|
|
477
|
+
)
|
|
478
|
+
return detail.reset_index(drop=True)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _column_sum(frame: pd.DataFrame, column: str) -> float:
|
|
482
|
+
"""Return a numeric result column's sum as an ordinary float."""
|
|
483
|
+
return float(_float_array(frame, column).sum())
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _build_period_summary(detail: pd.DataFrame) -> pd.DataFrame:
|
|
487
|
+
"""Summarize the one calculated reporting period."""
|
|
488
|
+
portfolio_return = _column_sum(detail, "portfolio_contribution")
|
|
489
|
+
benchmark_return = _column_sum(detail, "benchmark_contribution")
|
|
490
|
+
active_return = portfolio_return - benchmark_return
|
|
491
|
+
summary = pd.DataFrame(
|
|
492
|
+
{
|
|
493
|
+
"from_date": [detail.at[0, "from_date"]],
|
|
494
|
+
"thru_date": [detail.at[0, "thru_date"]],
|
|
495
|
+
"quantity_of_days": [_int_scalar(detail, "quantity_of_days")],
|
|
496
|
+
"portfolio_return": [portfolio_return],
|
|
497
|
+
"benchmark_return": [benchmark_return],
|
|
498
|
+
"active_return": [active_return],
|
|
499
|
+
"portfolio_contribution": [portfolio_return],
|
|
500
|
+
"benchmark_contribution": [benchmark_return],
|
|
501
|
+
"active_contribution": [_column_sum(detail, "active_contribution")],
|
|
502
|
+
"allocation_effect": [_column_sum(detail, "allocation_effect")],
|
|
503
|
+
"selection_effect": [_column_sum(detail, "selection_effect")],
|
|
504
|
+
"total_effect": [_column_sum(detail, "total_effect")],
|
|
505
|
+
"linked_portfolio_contribution": [
|
|
506
|
+
_column_sum(detail, "linked_portfolio_contribution")
|
|
507
|
+
],
|
|
508
|
+
"linked_benchmark_contribution": [
|
|
509
|
+
_column_sum(detail, "linked_benchmark_contribution")
|
|
510
|
+
],
|
|
511
|
+
"linked_active_contribution": [
|
|
512
|
+
_column_sum(detail, "linked_active_contribution")
|
|
513
|
+
],
|
|
514
|
+
"linked_allocation_effect": [
|
|
515
|
+
_column_sum(detail, "linked_allocation_effect")
|
|
516
|
+
],
|
|
517
|
+
"linked_selection_effect": [
|
|
518
|
+
_column_sum(detail, "linked_selection_effect")
|
|
519
|
+
],
|
|
520
|
+
"linked_total_effect": [_column_sum(detail, "linked_total_effect")],
|
|
521
|
+
},
|
|
522
|
+
columns=_PERIOD_SUMMARY_COLUMNS,
|
|
523
|
+
)
|
|
524
|
+
return summary.reset_index(drop=True)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _build_overall_detail(
|
|
528
|
+
equalized: pd.DataFrame, detail: pd.DataFrame
|
|
529
|
+
) -> pd.DataFrame:
|
|
530
|
+
"""Build single-period overall rows using supplied returns where required."""
|
|
531
|
+
portfolio_return = _float_array(equalized, "input_return_portfolio")
|
|
532
|
+
benchmark_return = _float_array(equalized, "input_return_benchmark")
|
|
533
|
+
active_return = np.full(len(equalized), np.nan, dtype=np.float64)
|
|
534
|
+
defined_active_return = ~np.isnan(portfolio_return) & ~np.isnan(benchmark_return)
|
|
535
|
+
np.subtract(
|
|
536
|
+
portfolio_return,
|
|
537
|
+
benchmark_return,
|
|
538
|
+
out=active_return,
|
|
539
|
+
where=defined_active_return,
|
|
540
|
+
)
|
|
541
|
+
overall = pd.DataFrame(
|
|
542
|
+
{
|
|
543
|
+
"from_date": detail["from_date"].copy(),
|
|
544
|
+
"thru_date": detail["thru_date"].copy(),
|
|
545
|
+
"identifier": detail["identifier"].copy(),
|
|
546
|
+
"portfolio_weight": detail["portfolio_weight"].copy(),
|
|
547
|
+
"portfolio_return": portfolio_return,
|
|
548
|
+
"linked_portfolio_contribution": detail[
|
|
549
|
+
"linked_portfolio_contribution"
|
|
550
|
+
].copy(),
|
|
551
|
+
"benchmark_weight": detail["benchmark_weight"].copy(),
|
|
552
|
+
"benchmark_return": benchmark_return,
|
|
553
|
+
"linked_benchmark_contribution": detail[
|
|
554
|
+
"linked_benchmark_contribution"
|
|
555
|
+
].copy(),
|
|
556
|
+
"active_weight": detail["active_weight"].copy(),
|
|
557
|
+
"active_return": active_return,
|
|
558
|
+
"linked_active_contribution": detail[
|
|
559
|
+
"linked_active_contribution"
|
|
560
|
+
].copy(),
|
|
561
|
+
"linked_allocation_effect": detail["linked_allocation_effect"].copy(),
|
|
562
|
+
"linked_selection_effect": detail["linked_selection_effect"].copy(),
|
|
563
|
+
"linked_total_effect": detail["linked_total_effect"].copy(),
|
|
564
|
+
},
|
|
565
|
+
columns=_OVERALL_DETAIL_COLUMNS,
|
|
566
|
+
)
|
|
567
|
+
return overall.reset_index(drop=True)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _build_cumulative(summary: pd.DataFrame) -> pd.DataFrame:
|
|
571
|
+
"""Build the identity cumulative result for one reporting period."""
|
|
572
|
+
values = {
|
|
573
|
+
"from_date": [summary.at[0, "from_date"]],
|
|
574
|
+
"thru_date": [summary.at[0, "thru_date"]],
|
|
575
|
+
"portfolio_return": [summary.at[0, "portfolio_return"]],
|
|
576
|
+
"benchmark_return": [summary.at[0, "benchmark_return"]],
|
|
577
|
+
"active_return": [summary.at[0, "active_return"]],
|
|
578
|
+
"cumulative_portfolio_return": [summary.at[0, "portfolio_return"]],
|
|
579
|
+
"cumulative_benchmark_return": [summary.at[0, "benchmark_return"]],
|
|
580
|
+
"cumulative_active_return": [summary.at[0, "active_return"]],
|
|
581
|
+
"linked_portfolio_contribution": [
|
|
582
|
+
summary.at[0, "linked_portfolio_contribution"]
|
|
583
|
+
],
|
|
584
|
+
"linked_benchmark_contribution": [
|
|
585
|
+
summary.at[0, "linked_benchmark_contribution"]
|
|
586
|
+
],
|
|
587
|
+
"linked_active_contribution": [summary.at[0, "linked_active_contribution"]],
|
|
588
|
+
"cumulative_portfolio_contribution": [
|
|
589
|
+
summary.at[0, "linked_portfolio_contribution"]
|
|
590
|
+
],
|
|
591
|
+
"cumulative_benchmark_contribution": [
|
|
592
|
+
summary.at[0, "linked_benchmark_contribution"]
|
|
593
|
+
],
|
|
594
|
+
"cumulative_active_contribution": [
|
|
595
|
+
summary.at[0, "linked_active_contribution"]
|
|
596
|
+
],
|
|
597
|
+
"linked_allocation_effect": [summary.at[0, "linked_allocation_effect"]],
|
|
598
|
+
"linked_selection_effect": [summary.at[0, "linked_selection_effect"]],
|
|
599
|
+
"linked_total_effect": [summary.at[0, "linked_total_effect"]],
|
|
600
|
+
"cumulative_allocation_effect": [summary.at[0, "linked_allocation_effect"]],
|
|
601
|
+
"cumulative_selection_effect": [summary.at[0, "linked_selection_effect"]],
|
|
602
|
+
"cumulative_total_effect": [summary.at[0, "linked_total_effect"]],
|
|
603
|
+
}
|
|
604
|
+
return pd.DataFrame(values, columns=_CUMULATIVE_COLUMNS).reset_index(drop=True)
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _reconciliation_row(
|
|
608
|
+
scope: str,
|
|
609
|
+
dates: tuple[pd.Timestamp, pd.Timestamp],
|
|
610
|
+
check: str,
|
|
611
|
+
actual: float,
|
|
612
|
+
expected: float,
|
|
613
|
+
) -> dict[str, object]:
|
|
614
|
+
"""Create one reconciliation record using the fixed numerical tolerance."""
|
|
615
|
+
return {
|
|
616
|
+
"scope": scope,
|
|
617
|
+
"from_date": dates[0],
|
|
618
|
+
"thru_date": dates[1],
|
|
619
|
+
"check": check,
|
|
620
|
+
"actual": actual,
|
|
621
|
+
"expected": expected,
|
|
622
|
+
"residual": actual - expected,
|
|
623
|
+
"tolerance": _TOLERANCE,
|
|
624
|
+
"passed": math.isclose(
|
|
625
|
+
actual, expected, rel_tol=_TOLERANCE, abs_tol=_TOLERANCE
|
|
626
|
+
),
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _build_reconciliation(
|
|
631
|
+
detail: pd.DataFrame, summary: pd.DataFrame
|
|
632
|
+
) -> pd.DataFrame:
|
|
633
|
+
"""Build positive period and overall financial reconciliation evidence."""
|
|
634
|
+
dates = (
|
|
635
|
+
cast(pd.Timestamp, detail.at[0, "from_date"]),
|
|
636
|
+
cast(pd.Timestamp, detail.at[0, "thru_date"]),
|
|
637
|
+
)
|
|
638
|
+
portfolio_return = _column_sum(summary, "portfolio_return")
|
|
639
|
+
benchmark_return = _column_sum(summary, "benchmark_return")
|
|
640
|
+
active_return = portfolio_return - benchmark_return
|
|
641
|
+
period_values = (
|
|
642
|
+
("portfolio_weight", _column_sum(detail, "portfolio_weight"), 1.0),
|
|
643
|
+
("benchmark_weight", _column_sum(detail, "benchmark_weight"), 1.0),
|
|
644
|
+
(
|
|
645
|
+
"portfolio_contribution",
|
|
646
|
+
_column_sum(detail, "portfolio_contribution"),
|
|
647
|
+
portfolio_return,
|
|
648
|
+
),
|
|
649
|
+
(
|
|
650
|
+
"benchmark_contribution",
|
|
651
|
+
_column_sum(detail, "benchmark_contribution"),
|
|
652
|
+
benchmark_return,
|
|
653
|
+
),
|
|
654
|
+
("active_contribution", _column_sum(detail, "active_contribution"), active_return),
|
|
655
|
+
(
|
|
656
|
+
"effect_components",
|
|
657
|
+
_column_sum(detail, "allocation_effect")
|
|
658
|
+
+ _column_sum(detail, "selection_effect"),
|
|
659
|
+
_column_sum(detail, "total_effect"),
|
|
660
|
+
),
|
|
661
|
+
("total_effect", _column_sum(detail, "total_effect"), active_return),
|
|
662
|
+
)
|
|
663
|
+
overall_values = (
|
|
664
|
+
(
|
|
665
|
+
"linked_portfolio_contribution",
|
|
666
|
+
_column_sum(detail, "linked_portfolio_contribution"),
|
|
667
|
+
portfolio_return,
|
|
668
|
+
),
|
|
669
|
+
(
|
|
670
|
+
"linked_benchmark_contribution",
|
|
671
|
+
_column_sum(detail, "linked_benchmark_contribution"),
|
|
672
|
+
benchmark_return,
|
|
673
|
+
),
|
|
674
|
+
(
|
|
675
|
+
"linked_active_contribution",
|
|
676
|
+
_column_sum(detail, "linked_active_contribution"),
|
|
677
|
+
active_return,
|
|
678
|
+
),
|
|
679
|
+
(
|
|
680
|
+
"linked_effect_components",
|
|
681
|
+
_column_sum(detail, "linked_allocation_effect")
|
|
682
|
+
+ _column_sum(detail, "linked_selection_effect"),
|
|
683
|
+
_column_sum(detail, "linked_total_effect"),
|
|
684
|
+
),
|
|
685
|
+
(
|
|
686
|
+
"linked_total_effect",
|
|
687
|
+
_column_sum(detail, "linked_total_effect"),
|
|
688
|
+
active_return,
|
|
689
|
+
),
|
|
690
|
+
)
|
|
691
|
+
rows = [
|
|
692
|
+
_reconciliation_row("period", dates, check, actual, expected)
|
|
693
|
+
for check, actual, expected in period_values
|
|
694
|
+
]
|
|
695
|
+
rows.extend(
|
|
696
|
+
_reconciliation_row("overall", dates, check, actual, expected)
|
|
697
|
+
for check, actual, expected in overall_values
|
|
698
|
+
)
|
|
699
|
+
reconciliation = pd.DataFrame(rows, columns=_RECONCILIATION_COLUMNS)
|
|
700
|
+
reconciliation["scope"] = reconciliation["scope"].astype("string[python]")
|
|
701
|
+
reconciliation["check"] = reconciliation["check"].astype("string[python]")
|
|
702
|
+
reconciliation["passed"] = reconciliation["passed"].astype("bool")
|
|
703
|
+
passed = cast(pd.Series, reconciliation["passed"])
|
|
704
|
+
if not bool(np.asarray(passed, dtype=np.bool_).all()):
|
|
705
|
+
failed = cast(
|
|
706
|
+
pd.Series, reconciliation.loc[~reconciliation["passed"], "check"]
|
|
707
|
+
)
|
|
708
|
+
failed_checks = ", ".join(
|
|
709
|
+
cast(pd.Series, failed.astype(str))
|
|
710
|
+
)
|
|
711
|
+
raise AttributionError(f"calculation reconciliation failed: {failed_checks}")
|
|
712
|
+
return reconciliation.reset_index(drop=True)
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def calculate_attribution(
|
|
716
|
+
portfolio: pd.DataFrame,
|
|
717
|
+
benchmark: pd.DataFrame,
|
|
718
|
+
) -> AttributionResult:
|
|
719
|
+
"""Calculate portable single-period Brinson-Fachler attribution.
|
|
720
|
+
|
|
721
|
+
Args:
|
|
722
|
+
portfolio: Prepared portfolio rows satisfying the portable input contract.
|
|
723
|
+
benchmark: Prepared benchmark rows for the same reporting period.
|
|
724
|
+
|
|
725
|
+
Returns:
|
|
726
|
+
Five new, caller-owned result frames containing period, overall, cumulative,
|
|
727
|
+
and reconciliation values.
|
|
728
|
+
|
|
729
|
+
Raises:
|
|
730
|
+
TypeError: If either input is not a pandas DataFrame.
|
|
731
|
+
AttributionError: If financial input is invalid, the current single-period
|
|
732
|
+
limitation is exceeded, or a reconciliation invariant fails.
|
|
733
|
+
|
|
734
|
+
Notes:
|
|
735
|
+
This first functional vertical slice accepts exactly one reporting period.
|
|
736
|
+
Selection is portfolio-weighted and absorbs interaction. Supplied
|
|
737
|
+
contribution is authoritative; otherwise contribution is derived as weight
|
|
738
|
+
multiplied by return.
|
|
739
|
+
"""
|
|
740
|
+
if not isinstance(portfolio, pd.DataFrame):
|
|
741
|
+
raise TypeError("portfolio must be a pandas DataFrame")
|
|
742
|
+
if not isinstance(benchmark, pd.DataFrame):
|
|
743
|
+
raise TypeError("benchmark must be a pandas DataFrame")
|
|
744
|
+
|
|
745
|
+
normalized_portfolio = _normalize_input(portfolio, "portfolio")
|
|
746
|
+
normalized_benchmark = _normalize_input(benchmark, "benchmark")
|
|
747
|
+
_validate_matched_period(normalized_portfolio, normalized_benchmark)
|
|
748
|
+
equalized = _equalize_universe(normalized_portfolio, normalized_benchmark)
|
|
749
|
+
period_detail = _build_period_detail(equalized)
|
|
750
|
+
period_summary = _build_period_summary(period_detail)
|
|
751
|
+
overall_detail = _build_overall_detail(equalized, period_detail)
|
|
752
|
+
cumulative = _build_cumulative(period_summary)
|
|
753
|
+
reconciliation = _build_reconciliation(period_detail, period_summary)
|
|
754
|
+
return AttributionResult(
|
|
755
|
+
period_detail=period_detail,
|
|
756
|
+
period_summary=period_summary,
|
|
757
|
+
overall_detail=overall_detail,
|
|
758
|
+
cumulative=cumulative,
|
|
759
|
+
reconciliation=reconciliation,
|
|
760
|
+
)
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
__all__ = ["AttributionError", "AttributionResult", "calculate_attribution"]
|
perfattr/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: perfattr
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Auditable portfolio performance attribution using pandas and NumPy.
|
|
5
|
+
Project-URL: Repository, https://github.com/JohnDReynolds/perfattr
|
|
6
|
+
Author: John Reynolds
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: attribution,brinson,finance,performance,portfolio
|
|
10
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
11
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Requires-Dist: numpy>=1.26
|
|
20
|
+
Requires-Dist: pandas>=2.2
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
23
|
+
Requires-Dist: pylint>=4.0; extra == 'dev'
|
|
24
|
+
Requires-Dist: pyright>=1.1.409; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: twine>=6.0; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# perfattr
|
|
30
|
+
|
|
31
|
+
`perfattr` is a small, auditable portfolio performance-attribution calculation
|
|
32
|
+
library built with pandas and NumPy.
|
|
33
|
+
|
|
34
|
+
The initial release will provide a reusable Brinson-Fachler calculation core for
|
|
35
|
+
prepared reporting-period data. Source loading, portfolio accounting, vendor schemas,
|
|
36
|
+
calendar logic, and presentation are intentionally outside the package boundary.
|
|
37
|
+
|
|
38
|
+
The first functional alpha slice calculates one prepared reporting period, including
|
|
39
|
+
input validation, universe equalization, Brinson-Fachler allocation and selection,
|
|
40
|
+
and financial reconciliation. Multi-period linking remains the next calculation
|
|
41
|
+
milestone. The governing roadmap is available in
|
|
42
|
+
[`_extras/perfattr_roadmap.md`](_extras/perfattr_roadmap.md), and the complete portable
|
|
43
|
+
calculation contract is defined in [`docs/specification.md`](docs/specification.md).
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from perfattr import calculate_attribution
|
|
47
|
+
|
|
48
|
+
result = calculate_attribution(portfolio, benchmark)
|
|
49
|
+
print(result.period_detail)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Development
|
|
53
|
+
|
|
54
|
+
Create and activate a virtual environment:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
python3 -m venv .venv
|
|
58
|
+
source .venv/bin/activate
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Install the package and development dependencies:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
python -m pip install --editable ".[dev]"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Run the initial checks:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
python -m pytest
|
|
71
|
+
python -m pylint src/perfattr tests
|
|
72
|
+
python -m pyright
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
`perfattr` is distributed under the MIT License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
perfattr/__init__.py,sha256=x4ycI6CTCrBVhO96ExgHu35RiCCXXQbI1iRJ3OAm_ds,310
|
|
2
|
+
perfattr/attribution.py,sha256=RMYykE8j_KPRProkpC4KLNddh6FusDuaPtsd8pOt-2U,30080
|
|
3
|
+
perfattr/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
4
|
+
perfattr-0.1.0a1.dist-info/METADATA,sha256=J3jGT8D0XLwbvujVdoOY5eZu3RkoEez8dMBfTMqu6Mg,2463
|
|
5
|
+
perfattr-0.1.0a1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
6
|
+
perfattr-0.1.0a1.dist-info/licenses/LICENSE,sha256=gupE58P8MWMDwzrvVztNkjwqWueqJQpuz1EnroX0wCE,1070
|
|
7
|
+
perfattr-0.1.0a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 John Reynolds
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|