Brinson-Fachler#
Abstract interface and PyArrow implementation of the Brinson-Fachler attribution methodology (see Attribution Methodology for the conceptual background), plus the PyArrow table-reshaping utilities, segment aggregation, implied cash and the benchmark cross-check used by the pipeline.
Abstract interface for Brinson-Fachler return attribution using PyArrow Tables.
Defines the contract that concrete Brinson-Fachler implementations must satisfy: computing single-period attribution for a given date and aggregating single-period results into a time series.
- class BrinsonFachlerArrowInterface(returns_investable_assets: Table | None = None, complete_portfolio_weights: Table | None = None, complete_benchmark_weights: Table | None = None)[source]#
Bases:
objectAbstract interface for Brinson-Fachler attribution using PyArrow Tables.
Defines the contract for computing single-period and multi-period Brinson-Fachler return attribution, decomposing active return into allocation, selection, and interaction effects.
- Parameters:
returns_investable_assets (pa.Table, optional) – Asset (or group) returns with a date column and one float64 column per asset. Implementations may take separate portfolio and benchmark returns instead.
complete_portfolio_weights (pa.Table) – Portfolio weights with a date column and one float64 column per asset. Required;
Noneraises.complete_benchmark_weights (pa.Table) – Benchmark weights with a date column and one float64 column per asset. Required;
Noneraises.
- Raises:
AttributionArgumentError – If a weights table is missing (also a
ValueError).
- abstractmethod brinson_fachler_model(date: object) tuple[Table, Table][source]#
Calculate the Brinson-Fachler attribution model for a single date.
Decomposes the active return (portfolio minus benchmark) into allocation, selection, and interaction effects for each asset.
- Parameters:
date (object) – The date to attribute. For a table whose date column is a date or timestamp type: a
datetime.date,datetime.datetime,pd.Timestamp,np.datetime64,pa.Scalaror ISO-8601 string, converted to that table’s own date type (a number is not a date); otherwise a value of the column (e.g. astrfor string columns). A date absent from a table gives zero weights / missing returns there.- Returns:
detail_table (pa.Table) – Per-group attribution with columns:
asset,portfolio_weights,benchmark_weights,returns_data(portfolio-side group return),benchmark_returns_data(benchmark-side group return),portfolio_returns,benchmark_returns,alpha,allocation,selection,interaction.totals_table (pa.Table) – Single-row summary with columns:
date,portfolio_returns,benchmark_returns,alpha,allocation,selection,interaction.
- abstractmethod compute_cumulative_indexes() Table[source]#
Accumulate the per-period attribution totals over time.
Pure computation over the time series produced by
time_series_calculation: every numeric attribution column is replaced by its cumulative value (linked, or a running sum, per the implementation’s linking method). Implementations must not plot or produce any other side effect here.- Returns:
Cumulative attribution indexes keyed by
date, with columnsportfolio_returns,benchmark_returns,alpha,allocation,selection,interaction.- Return type:
pa.Table
- abstractmethod time_series_calculation() None[source]#
Calculate the Brinson-Fachler attribution across all available dates.
Attributes every date of the portfolio weights that the benchmark weights and the returns also hold (each date converted to every table’s own date type, as in
brinson_fachler_model), computing the single-period model for each, and concatenates the totals into a time-series table.Implementations store the totals time series (columns
date,portfolio_returns,benchmark_returns,alpha,allocation,selection,interaction) and the per-date detail tables on the instance; nothing is returned.
Concrete Brinson-Fachler return attribution implementation using PyArrow.
Implements BrinsonFachlerArrowInterface by decomposing active
portfolio return into allocation, selection, and interaction effects for each
period, then aggregating across time.
Two decomposition formulas are supported, selected via the formula
constructor argument:
"legacy"(deprecated, alias"custom")The historical asset-level variant used by this project. It assumes a single shared per-asset return series and computes:
r_p = w_p * r r_b = w_b * r alpha = r_p - r_b allocation = (w_p - w_b) * r_b selection = alpha * w_p interaction = alpha - allocation - selection
"textbook"(default)Standard single-period Brinson-Fachler. It supports separate portfolio and benchmark per-group returns (needed once per-asset weights are aggregated into per-sector groups, where the group’s return differs between portfolio and benchmark because the constituents differ):
R_b = sum_i w_b_i * R_b_i (total benchmark return) allocation_i = (w_p_i - w_b_i) * (R_b_i - R_b) selection_i = w_b_i * (R_p_i - R_b_i) interaction_i = (w_p_i - w_b_i) * (R_p_i - R_b_i) active_i = allocation_i + selection_i + interaction_i
with the additivity identity
sum_i active_i == R_p - R_b(exact when the portfolio and benchmark weights each sum to 1 on the date).Missing returns: a group the portfolio does not hold takes
R_p_i := R_b_i(no selection or interaction); a group the benchmark does not hold takesR_b_i := R_p_i(its excess is allocation); a group missing on both sides counts as 0 and is logged.
- class BrinsonFachlerArrowAttribution(returns_investable_assets: Table | None = None, complete_portfolio_weights: Table | None = None, complete_benchmark_weights: Table | None = None, date_column: str = 'date', *, portfolio_returns: Table | None = None, benchmark_returns: Table | None = None, formula: BrinsonFachlerFormula | str = BrinsonFachlerFormula.TEXTBOOK, linking: LinkingMethod | str | None = None)[source]#
Bases:
BrinsonFachlerArrowInterfaceBrinson-Fachler return attribution implementation using PyArrow.
Decomposes active portfolio return into allocation, selection, and interaction effects for every group (asset or sector) on each period, then aggregates across time.
- Parameters:
returns_investable_assets (pa.Table, optional) – Shared per-group returns with a
date_columnand one float64 column per group. Provide this or theportfolio_returns/benchmark_returnspair, not both. When given, the portfolio and benchmark returns of a group are assumed identical (asset level).complete_portfolio_weights (pa.Table) – Portfolio weights with a
date_columnand one float64 column per group. Rows should sum to 1.0 for each date.complete_benchmark_weights (pa.Table) – Benchmark weights with a
date_columnand one float64 column per group. Rows should sum to 1.0 for each date.date_column (str, default
"date") – Name of the date column common to all input tables. The tables may store their dates in different date or timestamp types (date32,date64,timestampin any unit):brinson_fachler_modelandtime_series_calculationconvert each date to every table’s own type, exactly.portfolio_returns (pa.Table, optional) – Portfolio-side per-group returns (same schema as
benchmark_returns). Requiresformula="textbook"and must be provided together withbenchmark_returns.benchmark_returns (pa.Table, optional) – Benchmark-side per-group returns. See
portfolio_returns.formula ({"textbook", "legacy"} or BrinsonFachlerFormula, default "textbook") – Which decomposition to apply.
"textbook"is standard single-period Brinson-Fachler."legacy"(alias"custom") reproduces the asset-level numbers of 0.3.x and earlier and is deprecated. Separate portfolio/benchmark returns require"textbook".linking ({"carino", "grap", "none"} or LinkingMethod, optional) – How
compute_cumulative_indexescombines periods. Default: “carino” for the textbook formula, “none” for legacy (0.3.x numbers).main()never links legacy, though the class accepts an explicitlinkingfor it.
- Variables:
formula (BrinsonFachlerFormula) – The active decomposition mode.
linking (LinkingMethod) – The multi-period linking method of the cumulative indexes.
detail_table (pa.Table) – Per-group detail from the most recent
brinson_fachler_modelcall.totals (pa.Table) – Single-row totals from the most recent
brinson_fachler_modelcall.df (pa.Table) – Concatenated totals time series after
time_series_calculation.output_dict (dict) – Mapping of date (as the portfolio weights store it) to per-group detail table after
time_series_calculation.brinson_fachler_indexes (pa.Table) – Cumulative attribution indexes after
compute_cumulative_indexes(also set as a side effect ofattribution_plots).
- Raises:
AttributionArgumentError – If a weights table is missing, the return tables are passed in an unsupported combination, or formula or linking is unknown (also a
ValueError).LicenseError – If this process holds no licence grant and
validate_license()cannot make one (one of its four subclasses). The methods that compute the attribution check the licence too.
- attribution_plots() None[source]#
Plot cumulative Brinson-Fachler attribution effects.
Calls
compute_cumulative_indexes()and then produces a 3-panel figure:Cumulative portfolio vs benchmark returns.
Cumulative alpha.
Cumulative allocation, selection, and interaction effects.
Must be called after
time_series_calculation.Sets Attributes#
- brinson_fachler_indexespa.Table
Cumulative attribution indexes keyed by date (see
compute_cumulative_indexes()).
- brinson_fachler_model(date: object) tuple[Table, Table][source]#
Calculate the Brinson-Fachler attribution for a single date.
Decomposes the active return into allocation, selection, and interaction effects for every group, then sums to produce portfolio-level totals. The formula used depends on
self.formula.- Parameters:
date (object) – The date to attribute. It is converted to the date type of each input table separately (portfolio weights, benchmark weights, portfolio returns, benchmark returns), so the tables may store their dates differently (
date32,date64ortimestampin any unit). Accepted for a date or timestamp column: adatetime.date, adatetime.datetime, apd.Timestamp, anp.datetime64, apa.Scalarof a date, timestamp or string type, or an ISO-8601 string ("2024-01-02", or with a time,"2024-01-02 15:30:00", for timestamp columns only). A date without a time means midnight. A number is not a date: anintsuch as20240102, afloator aboolis rejected. With any other column type (e.g. strings or integers) date is not converted and must equal the column’s values. A date absent from a table gives zero weights / missing returns there.- Returns:
detail_table (pa.Table) – Per-group breakdown with columns:
asset,portfolio_weights,benchmark_weights,returns_data,benchmark_returns_data,portfolio_returns,benchmark_returns,alpha,allocation,selection,interaction. In textbook modereturns_data/benchmark_returns_datahold the returns after the missing-return conventions, so a segment the portfolio does not hold shows the benchmark’s return (and vice versa).totals_table (pa.Table) – Single-row aggregate with columns:
date,portfolio_returns,benchmark_returns,alpha,allocation,selection,interaction.
- Raises:
DateConversionError – If a table’s date column is a date or timestamp type and date cannot be converted to it exactly (also a
ValueError): date is a number or another value that is not a date; it isNone,NaTor a null scalar; it is a string Arrow cannot parse as ISO-8601; it has a time of day and the column is a date, or more precision than the column’s unit; it is outside the column’s range; or only one of date and the column has a time zone.PortfolioValidationError – Textbook: if the weights do not sum to 1 on date.
PerformanceAttributionError – Textbook: if a resolved return is non-finite or the effects do not reconcile.
Notes
The totals’
dateis date as the portfolio weights store it.
- compute_cumulative_indexes() Table[source]#
Build the cumulative Brinson-Fachler attribution indexes.
Pure computation on the per-period totals in
self.df; no plotting, no other side effects. Must be called aftertime_series_calculation.With
linking“carino” or “grap”, portfolio and benchmark returns are compounded and the effects linked. At every dateallocation + selection + interaction == alpha(to float precision), andalpha == portfolio_returns - benchmark_returns(compounded) up to the per-period reconciliation residuals (bounded by the weight-sum tolerance). With “none” every column is a plain running sum (no linking, the behaviour before this release).- Returns:
Cumulative
portfolio_returns,benchmark_returns,alpha,allocation,selectionandinteractionkeyed bydate. The same table is also stored onself.brinson_fachler_indexes.- Return type:
pa.Table
- Raises:
PerformanceAttributionError – If a per-period return or effect is non-finite, a return is at or below -100%, or compounding overflows (see
link_cumulative).
Notes
Sets
brinson_fachler_indexes(pa.Table) to the returned cumulative-index table.
- time_series_calculation() None[source]#
Run Brinson-Fachler attribution across all common dates.
Attributes every date of the portfolio weights that the benchmark weights and both return tables also hold, vectorized over blocks of dates (
_DATE_BLOCK), in date order (the first failing date raises). Each date is converted to the date type of every other table with the rules ofbrinson_fachler_model, so the tables may store their dates differently (date32,date64ortimestampin any unit): the conversion is exact or raises, never a silently empty result. ISO-8601 string dates of the portfolio weights convert to date or timestamp columns; a date column of any other type (e.g. strings or integers) matches only a column of the same type, value for value. A null date never matches.Sets Attributes#
- dfpa.Table
Concatenated totals time series with columns:
date,portfolio_returns,benchmark_returns,alpha,allocation,selection,interaction.- output_dictdict
Mapping of each date to its per-group
pa.Tabledetail.- detail_table, totalspa.Table
Detail and single-row totals of the last date (left unchanged when there is no date).
- raises DateConversionError:
If another table’s date column has a type other than the portfolio weights’ and cannot take their dates exactly (also a
ValueError): it is not a date or timestamp type; the portfolio weights’ dates are not dates, timestamps or ISO-8601 strings (e.g. numbers); a date has a time of day and the column is a date, or more precision than the column’s unit; it is outside the column’s range; a string does not parse; or only one of the two types has a time zone. Checked for every portfolio-weights date, whether or not the other tables hold it, in the order benchmark weights, portfolio returns, benchmark returns.- raises PortfolioValidationError:
Textbook: if a date’s weights do not sum to 1.
- raises PerformanceAttributionError:
Textbook: if a resolved return is non-finite or the effects do not reconcile.
Notes
The totals’
datecolumn and theoutput_dictkeys hold the dates as the portfolio weights store them.
- RECONCILIATION_TOLERANCE = 1e-10#
Float slack on
abs(sum(A + S + I) - (R_p - R_b))per date, on top of the weight-drift bound.The drift bound
2 * WEIGHT_SUM_TOLERANCE * abs(R_b)covers every legitimate residual, so this only absorbs float error (~1e-17 on typical data).
Conversion utilities for reshaping PyArrow tables into the format expected by the Brinson-Fachler Arrow attribution engine.
Every operation stays in PyArrow (no pandas round trip).
- WIDE_DATE_FORMATS = ('%Y-%m-%d', '%d/%m/%Y', '%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S')#
Formats tried, in order, for the date headers of a wide table; one format must parse every header.
- column_to_float64(column: ChunkedArray | Array) ChunkedArray | Array[source]#
Cast a numeric column to float64, decimals exactly.
Decimal columns go through a string cast so each value equals
float(Decimal)(the correctly rounded double); a direct decimal-to-float cast differs by 1 ulp in some cells.- Parameters:
column (pyarrow.ChunkedArray or pyarrow.Array) – Numeric column (decimal, integer or floating).
- Returns:
The
float64column, nulls kept.- Return type:
pyarrow.ChunkedArray or pyarrow.Array
- Raises:
pyarrow.ArrowInvalid, pyarrow.ArrowNotImplementedError – If the column cannot be cast to float64.
- compute_returns_from_prices_arrow(prices_table: Table, date_column: str) ReturnsTable[source]#
Compute percentage returns from a prices table.
Equivalent to
prices_df.pct_change(fill_method=None)— the first row is kept with null values so the date range stays aligned with the original prices table (and therefore with the weights tables).- Parameters:
prices_table (pyarrow.Table) – Prices table containing a date column and one or more numeric asset price columns.
date_column (str) – Name of the column in prices_table containing the dates. It’s passed through unchanged and always renamed to
"date"in the output, regardless of its original name.
- Returns:
Wrapper around a table with the same columns and row count as prices_table, where each asset column holds period-over-period percentage returns and the first row is null.
- Return type:
- portfolio_table_to_arrow(table: Table) PortfolioWeights[source]#
Transpose a wide portfolio/benchmark weights table into attribution format.
This is the PyArrow equivalent of
portfolio_table_to_pandas, which doesset_index("Ticker").T.- Parameters:
table (pyarrow.Table) – Wide-format weights table with columns
[Ticker, date1, date2, ...], one row per ticker and one column per date. Date column names are parsed with the first ofWIDE_DATE_FORMATSthat parses them all (DataLoadingErrorotherwise).- Returns:
Wrapper around a table with columns
[date, asset1, asset2, ...], i.e. one row per date and one column per ticker.- Return type:
- pyarrow_prices_to_attribution_format(table: Table, date_column: str) Table[source]#
Reshape a prices table into the attribution format.
The date column is cast to a
timestamptype and all remaining (numeric) columns are cast tofloat64.- Parameters:
table (pyarrow.Table) – Prices table containing a date column and one or more numeric asset price columns.
date_column (str) – Name of the column in table containing the dates. It’s cast from a
"%Y-%m-%d"string (if not already a timestamp type) and always renamed to"date"in the output, regardless of its original name.
- Returns:
Table with columns
[date, asset1, asset2, ...], wheredateis oftimestamp("ns")type and every asset column isfloat64.- Return type:
pyarrow.Table
- returns_table_to_arrow(table: Table) ReturnsTable[source]#
Transpose a wide returns table into attribution format.
Same transpose logic as
portfolio_table_to_arrow(), but wraps the result in aReturnsTable(no weight constraints).- Parameters:
table (pyarrow.Table) – Wide-format returns table with columns
[Ticker, date1, date2, ...], one row per ticker and one column per date. Date column names are parsed with the first ofWIDE_DATE_FORMATSthat parses them all (DataLoadingErrorotherwise).- Returns:
Wrapper around a table with columns
[date, asset1, asset2, ...], i.e. one row per date and one column per ticker.- Return type:
Aggregate asset-level weights and returns into Brinson-Fachler segments.
A segment’s weight is the sum of its assets’ weights; its return is the weight-averaged return of those assets. Portfolio and benchmark are aggregated separately, so a segment’s return differs between the two when they hold different names inside it, which is what the textbook selection effect needs.
Notes
The segment map is static: a ticker keeps one segment for the whole window. A held asset with a null return on a date contributes 0 to its segment that day while its weight still counts (one warning per call reports how many). A held asset with an infinite return is rejected, since it would silently poison the segment return. A weights date with no row in returns has a null segment return, never 0. A segment whose long and short weights net to ~0 but whose P&L does not is rejected: its return is undefined, and a null would drop that P&L from the attribution.
- NET_PNL_TOLERANCE = 1e-10#
Max
abs(P&L)of a net-zero segment on a date that is treated as float noise rather than lost P&L.
- aggregate_to_segments(weights: Table, returns: Table, segment_map: Mapping[str, str], date_column: str = 'date') tuple[Table, Table][source]#
Aggregate one side’s asset weights and returns into segments.
- Parameters:
weights (pa.Table) – Start-of-day weights: date_column plus one float64 column per ticker.
returns (pa.Table) – Asset returns: date_column plus one float64 column per ticker. Must contain every ticker in weights. Rows are matched to weights by date.
segment_map (Mapping[str, str]) – Ticker to segment. Must cover every ticker in weights.
date_column (str, default
"date") – Date column name in both tables.
- Returns:
Segment weights and segment returns, both keyed by the dates of weights, one float64 column per segment (sorted). A segment whose net weight is zero (
abs(w) <= NET_WEIGHT_TOLERANCE) on a date has a null return that date, as does every segment on a date with no row in returns. A net-zero segment is only accepted when its P&L (sum of weight * return) is also ~0, so the null loses nothing.- Return type:
tuple[pa.Table, pa.Table]
- Raises:
DataValidationError – If a weighted ticker has no segment or no return column, the date columns have different types, returns has duplicate dates, a weight is NaN/null/infinite, a ticker has an infinite return on a date where its weight is non-zero, or a segment’s net weight is ~0 while its P&L is not (
abs(P&L) > NET_PNL_TOLERANCE; split its long and short legs into separate segments). Null/NaN returns are allowed and contribute 0; an infinite return on a date with zero weight is ignored.
- load_segment_map(path: Path) dict[str, str][source]#
Read a
ticker,segmentCSV into a mapping.- Parameters:
path (Path) – CSV file with a header row containing
tickerandsegment.- Returns:
Ticker to segment, both stripped.
- Return type:
dict[str, str]
- Raises:
MissingColumnError – If the header lacks
tickerorsegment.DataValidationError – If a row has an empty ticker or segment, or a ticker is assigned to two different segments.
Weight normalization for attribution inputs.
Brinson-Fachler needs each side’s weights to sum to 1 on every date. Files written with truncated decimals, or books that hold cash implicitly, sum below 1; the remainder is cash. A book above 1 is leveraged, which F1 does not attribute.
The over-allocation guard applies to NET weights (the plain sum per date). Long/short books pass as long as the net sum is at most 1 (e.g. +1.3 / -0.5 nets to 0.8 and gets cash = 0.2); gross leverage is not checked.
- append_zero_return_column(returns: ReturnsTable, ticker: str) ReturnsTable[source]#
Add a column of zero returns for ticker unless it already exists.
A row on which every other asset return is null (the first price date, where
pct_changehas no prior price) gets a null cash return too, so that date stays without a portfolio return instead of looking flat.- Parameters:
returns (ReturnsTable) – Asset returns.
ticker (str) – Column to add (the cash ticker).
- Returns:
returns itself if the column exists, otherwise a new entity.
- Return type:
- fill_implied_cash(weights: PortfolioWeights, cash_ticker: str) PortfolioWeights[source]#
Top up each date’s weights to 1 with cash_ticker.
The over-allocation guard is on NET weights: negative (short) weights offset long ones, so a long/short book such as +1.3 / -0.5 passes and receives cash = 1 - net. Gross leverage is not checked.
- Parameters:
weights (PortfolioWeights) – Start-of-day weights.
cash_ticker (str) – Column that receives the remainder. Created if absent, added to if present.
- Returns:
weights itself when every date already sums to 1 within
WEIGHT_SUM_TOLERANCE; otherwise a new entity with the cash column.- Return type:
- Raises:
PortfolioValidationError – If any weight is NaN or infinite, or if any date’s net weights sum above
1 + WEIGHT_SUM_TOLERANCE.
Cross-checks between attribution outputs and independent inputs.
They warn instead of raising: a holdings-based benchmark return differs from a published index return for legitimate reasons (pricing source, intraday rebalances, fees). A large gap usually means the benchmark weights do not cover the whole benchmark.
- compare_benchmark_returns(holdings_returns: Table, reported_returns: Table, date_column: str = 'date', tolerance: float = 0.0001) float | None[source]#
Compare the holdings-based benchmark return with the reported series.
Null and non-finite (NaN, inf) values on either side are skipped.
- Parameters:
holdings_returns (pa.Table) – Brinson-Fachler per-date totals with date_column and
benchmark_returns.reported_returns (pa.Table) – Reported benchmark returns: date_column plus exactly one return column.
date_column (str, default
"date") – Date column name in both tables.tolerance (float, default
BENCHMARK_RETURN_TOLERANCE) – Absolute daily difference above which a date counts as divergent.
- Returns:
Largest absolute daily difference over dates where both values exist; None when the reported table is unusable or no date overlaps.
- Return type:
float or None
Notes
Inputs are expected to be validated upstream (date column present, numeric return column; in main() the reported table is a ReturnsTable).