Factor Model#

Abstract interface and PyArrow implementation of the factor-model attribution methodology (see Attribution Methodology for the conceptual background), plus the factor-returns loaders that feed it, the log-to-simple restatement, the cumulative totals and the active (portfolio minus benchmark) decomposition.

class FactorModelArrowAttributionInterface(daily_portfolio_weights: Table, by_factor_factor_returns: dict[str, Table], asset_returns: Table, portfolio_returns: Table | None = None, benchmark_returns: Table | None = None)[source]#

Bases: object

Abstract interface for multi-factor model attribution using PyArrow Tables.

Defines the contract for decomposing portfolio returns into contributions from individual risk factors (style, industry, etc.) using factor return data and portfolio weights.

Parameters:
  • daily_portfolio_weights (pa.Table) – Daily portfolio weights with a date column and one float64 column per asset ticker.

  • by_factor_factor_returns (dict[str, pa.Table]) – Mapping of factor name to a pa.Table of per-asset factor returns. Each table has a date column and one float64 column per asset.

  • asset_returns (pa.Table) – Total asset returns with a date column and one float64 column per asset ticker.

  • portfolio_returns (pa.Table, optional) – Pre-computed portfolio-level returns with columns date and portfolio_returns. If None, computed internally from weights and asset returns.

  • benchmark_returns (pa.Table, optional) – Benchmark-level returns with a date column and a returns column.

abstractmethod multifactor_attribution() → None[source]#

Calculate the multi-factor attribution model across all dates.

For each date, computes the weighted sum of each factor’s per-asset returns using portfolio weights, producing a time series of daily factor contributions.

Returns:

Results are stored in self.portfolio_attribution_ts as a pa.Table with a date column and one float64 column per factor.

Return type:

None

class FactorModelArrowAttribution(daily_portfolio_weights: Table, by_factor_factor_returns: dict[str, Table], asset_returns: Table, portfolio_returns: Table | None = None, benchmark_returns: Table | None = None, date_column: str = 'date', linking: LinkingMethod | str = LinkingMethod.CARINO, side: str = 'portfolio')[source]#

Bases: FactorModelArrowAttributionInterface

Multi-factor model attribution implementation using PyArrow.

Decomposes portfolio returns into contributions from style factors, industry factors, and an idiosyncratic residual using portfolio weights and per-asset factor return tables.

Parameters:
  • daily_portfolio_weights (pa.Table) – Daily portfolio weights with a date_column and one float64 column per asset ticker, in any row order: they are sorted by date (see the attribute of the same name).

  • by_factor_factor_returns (dict[str, pa.Table]) – Mapping of factor name (e.g. "f_momentum") to a pa.Table of per-asset factor contributions (each cell: the asset’s exposure x the factor return), each with a date_column and one float64 column per asset. Matched to the weights by date, so the row order does not matter.

  • asset_returns (pa.Table) – Total asset returns with a date_column and one float64 column per asset ticker. Matched to the weights by date.

  • portfolio_returns (pa.Table, optional) – Pre-computed portfolio returns with columns date and portfolio_returns, matched to the weights by date. Computed from weights and asset returns if not provided.

  • benchmark_returns (pa.Table, optional) – Benchmark returns table.

  • date_column (str, default "date") – Name of the date column common to all input tables.

  • linking (LinkingMethod or str, default LinkingMethod.CARINO) – How cumulative contributions and shares combine periods: "carino", "grap", or "none" (plain running sums, no linking).

  • side (str, default "portfolio") – Which weights these are ("portfolio" or "benchmark"), named in the factor-coverage log line.

Variables:
  • daily_portfolio_weights (pa.Table) – The weights in ascending date order, the order of every derived table (portfolio_attribution_ts, a computed portfolio_returns, simulated_rets, pct_df_returns, cumulative_totals()) and the order linking compounds in, so no result depends on the input row order. The sort is stable: the rows of a repeated date keep their order. String dates sort as text, which is date order for ISO-8601 (YYYY-MM-DD). Rows with a null date are dropped, with a warning. Weights already sorted, without null dates, are kept as given (the same table).

  • portfolio_attribution_ts (pa.Table) – Daily factor contribution time series after multifactor_attribution.

  • simulated_rets (pa.Table) – Cumulative (linked, unless linking="none") factor contributions after time_series_calculation.

  • pct_df_returns (pa.Table) – Daily percentage decomposition after calc_pct_area.

Raises:
  • AttributionArgumentError – If linking is unknown (also a ValueError).

  • LicenseError – If this process holds no licence grant and validate_license() cannot make one (one of its four subclasses). The methods that compute the attribution check the licence too.

attribution_plots(title: str | None = None) → None[source]#

Plot cumulative multi-factor attribution in a 3-panel figure.

Panels show: (1) the model’s cumulative portfolio / factor / idiosyncratic return, plus carry / dividends when supplied (cumulative_totals), (2) style and other factors (every factor that is not an industry or a return component, known style names first), (3) industry factors with a non-zero value. Files in AGGREGATE_FACTOR_COLUMNS are never drawn. Requires time_series_calculation to have been run.

Parameters:

title (str, optional) – Overall figure title. Currently unused by the plot layout.

calc_pct_area() → None[source]#

Compute daily percentage decomposition of returns by factor.

Divides each factor’s daily contribution by the total portfolio return to get the fraction attributable to that factor. An idiosyncratic residual column (f_idio_returns) captures the portion of the portfolio return not explained by the factors; files in AGGREGATE_FACTOR_COLUMNS are not factors. The return components (COMPONENT_COLUMNS: f_carry, f_dividends) get their own share column and are taken out of the residual like the factors. NaN and Inf values are forward-filled.

Sets Attributes#

pct_df_returnspa.Table

Daily percentage attribution with the same date column and one float64 column per factor plus f_idio_returns.

cumulative_pct_decomp() → dict[str, float][source]#

Compute the cumulative percentage decomposition over the attribution window.

The window is the set of dates present in both portfolio_attribution_ts and portfolio_returns with a non-null portfolio return. With linking (default Carino, b = 0) the total is the portfolio’s compounded return over that window and each factor’s amount is its linked cumulative contribution; with linking="none" the total is the sum of daily portfolio returns and each amount the sum of daily contributions. Either way idio_returns takes the remainder, so the shares sum to one. Attribution dates without a portfolio return are excluded and reported with a warning (once per instance). Dates with a non-zero portfolio return but no factor attribution (no factor data, or no non-zero weight) are outside the window too, so the total then differs from the portfolio’s own return over all its dates; another warning (once per instance) counts them and names the first. calc_pct_area uses the same per-day portfolio return: the daily view is a per-day ratio, while this cumulative view is a ratio of window amounts, so the two need not match numerically. Files named in AGGREGATE_FACTOR_COLUMNS are never counted as factors. The return components (f_carry, f_dividends) are keys of their own and are taken out of idio_returns.

Returns:

Mapping of factor name (plus "idio_returns") to its share of the total cumulative portfolio return. Empty if the window has no dates.

Return type:

dict[str, float]

Notes

The total is the portfolio’s total (not excess) return. If the factor files hold excess-of-cash returns, the cash return lands in idio_returns.

cumulative_totals() → Table[source]#

Cumulative portfolio, factor, component and idiosyncratic return from the model.

The window is the attribution dates that have a portfolio return. portfolio_returns is the running total of the portfolio return over that window (a date with a non-zero portfolio return but no factor attribution is outside it, reported by one warning per instance), factor_returns the sum of the cumulative contributions of every factor (files in AGGREGATE_FACTOR_COLUMNS and the return components in COMPONENT_COLUMNS excluded), carry_returns / dividends_returns those of the components when supplied, and idiosyncratic_returns the remainder.

With linking (carino/grap) portfolio_returns is compounded and the window and factor values are those of simulated_rets, so factor_returns equals the sum of its factor columns (neither aggregates nor components).

With linking none every column is an arithmetic running sum, so portfolio_returns differs from the compounded Total Return of the summary statistics. simulated_rets then also covers attribution dates without a portfolio return (e.g. the first price date) while this table does not, so factor_returns need not equal the sum of the simulated_rets columns.

Derived from simulated_rets (see modules.factor_totals.cumulative_totals_from_contributions), so the contributions are not linked again; time_series_calculation runs first if it has not.

Returns:

Columns date, portfolio_returns, factor_returns, then carry_returns / dividends_returns when those components were supplied, then idiosyncratic_returns. factor_returns excludes the components. Empty (with those columns) when the window has no dates.

Return type:

pa.Table

Raises:

PerformanceAttributionError – If linking fails (see time_series_calculation).

decompose() → None[source]#

Daily factor contributions and portfolio returns, without cumulative linking.

Runs multifactor_attribution and computes portfolio_returns when they were not given. The active factor attribution uses it on the benchmark side, whose cumulative effects are linked against the active return rather than on their own.

Raises:

AttributionArgumentError – If asset_returns is None (also a ValueError).

last_day_decomposition(title: str) → None[source]#

Plot a horizontal bar chart of cumulative factor decomposition.

Shows each factor’s percentage contribution to total cumulative return at the final date, colored green (positive) or red (negative). The residual is labelled “Idiosyncratic” and the return components “Carry” / “Dividends”, as in the dashboard.

Parameters:

title (str) – Chart title. Currently overridden internally to "Factor Contributions to Strategy Returns".

multifactor_attribution() → None[source]#

Calculate multi-factor attribution across all dates.

For each date in daily_portfolio_weights, in ascending order, computes the portfolio-weighted sum of each factor’s per-asset returns. Logs average factor coverage across the portfolio.

Sets Attributes#

portfolio_attribution_tspa.Table

Daily factor contributions with a date column and one float64 column per factor.

plot_stacked_weights_normalized(figsize: tuple[int, int] = (14, 7), title: str = 'Return Attribution by Factor Over Time', y_label: str = 'Share of Total Return', date_fmt: str = '%Y-%m', legend_loc: LegendLocType = 'upper left', days_of_smoothing: int = 5) → None[source]#

Plot a normalized stacked area chart of factor contributions.

Each factor’s absolute contribution is divided by the sum of all absolute contributions to show relative importance over time, smoothed with a trailing rolling mean that uses a partial window at the start, so the chart begins at the first date. The residual (f_idio_returns) is labelled “Idiosyncratic” and the return components “Carry” / “Dividends”, as in the dashboard.

Parameters:
  • figsize (tuple[int, int], default (14, 7)) – Matplotlib figure size in inches.

  • title (str, default "Return Attribution by Factor Over Time") – Chart title. A rolling-window suffix is appended automatically.

  • y_label (str, default "Share of Total Return") – Y-axis label.

  • date_fmt (str, default "%Y-%m") – Date format string for the x-axis.

  • legend_loc (str, default "upper left") – Matplotlib legend location.

  • days_of_smoothing (int, default 5) – Rolling window size in trading days for smoothing.

run() → None[source]#

Execute the full attribution pipeline.

Runs decompose (daily contributions and, if not provided, portfolio returns), then time_series_calculation.

Raises:

AttributionArgumentError – If asset_returns is None (also a ValueError).

time_series_calculation() → None[source]#

Compute cumulative factor contributions over time.

With linking (default Carino) the table covers only dates with a portfolio return and each column is the factor’s linked cumulative contribution (b = 0), so at every date the linked factors plus the linked residual equal the compounded portfolio return; with "none" it is the plain running sum over all attribution dates (no linking).

Sets Attributes#

simulated_retspa.Table

Cumulative factor contributions with the same columns as portfolio_attribution_ts.

raises PerformanceAttributionError:

If linking fails: a portfolio return <= -100% or a non-finite value (the message names the date), or cumulative growth overflow/underflow. Dates without a portfolio return are dropped with a warning (logged once per instance).

Notes

Dates with a non-zero portfolio return but no factor attribution (no factor data, or no non-zero weight) are not in the table either; one warning per instance counts them and names the first.

Loaders for per-factor returns files, keyed by factor name.

Provides a pandas-based loader (load_by_factor_returns_csv) and a PyArrow-based loader (load_by_factor_returns_arrow) that read one CSV file per factor from a directory, restrict columns to the portfolio’s assets, and optionally slice the result to a date range.

list_factor_return_files(path: str) → list[str][source]#

List the factor-return CSV files in a directory.

Only regular files whose suffix is .csv (case-insensitive) are returned, sorted by name; anything else (README.md, .DS_Store, .gitkeep, sub-folders, names starting with . such as AppleDouble ._x.csv files, and Excel lock files starting with ~$) is skipped and reported once at INFO level. Aggregate vendor files (a name in AGGREGATE_FACTOR_COLUMNS: f_total_factor_returns, f_total_excess_returns, f_idyo_returns, whatever the case of the file name) hold totals, not factors: they are not listed, so they are never loaded and never bound the date window, and one INFO line names them. The totals come from the portfolio’s own returns.

Parameters:

path (str) – Directory containing one CSV file per factor.

Returns:

File names (with extension) of the factor files, sorted.

Return type:

list[str]

load_by_factor_returns_arrow(path: str, available_factors: list[str], portfolio_weights: PortfolioWeights, start_date: date | None = None, end_date: date | None = None, benchmark_weights: PortfolioWeights | None = None) → dict[str, FactorReturns][source]#

Load per-factor returns CSV files into a dict of FactorReturns.

Arrow-based equivalent of load_by_factor_returns_csv. Each file in available_factors is read from path with only the date column and the portfolio’s asset columns retained, dates are parsed (trying %Y-%m-%d then %d/%m/%Y), and the result is sliced from the portfolio’s first weighted day onward before being validated and wrapped in a FactorReturns entity.

Parameters:
  • path (str) – Directory containing one CSV file per factor.

  • available_factors (list[str]) – File names (with extension) to load from path. Entries equal to ".gitkeep" are ignored.

  • portfolio_weights (PortfolioWeights) – Portfolio weights entity; its first date lower-bounds the returned data and its asset names determine which factor-return columns are read and validated against.

  • start_date (datetime.date or None) – If given, the earliest date to keep. Raises if earlier than the data’s minimum date.

  • end_date (datetime.date or None) – If given, the latest date to keep. Silently clamped to the data’s maximum date if later.

  • benchmark_weights (PortfolioWeights or None, default None) – When given (active factor attribution), its tickers are read too, after the portfolio’s, so the benchmark side has factor data. Its dates do not bound the data.

Returns:

Mapping of factor name (derived from the file name; a return component file gets its canonical name f_carry / f_dividends whatever its case, see _factor_names) to its FactorReturns entity.

Return type:

dict[str, FactorReturns]

Raises:
  • DateRangeError – If start_date is before the earliest available date in a factor’s file.

  • DataValidationError – If two files have the same factor name, a factor’s asset columns are not a subset of the portfolio’s tickers (plus the benchmark’s, when given), or the resulting table is empty.

  • MissingColumnError – If a factor’s file is missing its date column.

  • EntityTypeError – If a factor’s date or asset columns have an unexpected type.

load_by_factor_returns_csv(path: str, available_factors: list[str], portfolio_weights: DataFrame, start_date: date | None = None, end_date: date | None = None) → dict[str, DataFrame][source]#

Load per-factor returns CSV files into a dict of DataFrames.

Each file in available_factors is read from path, restricted to the columns present in portfolio_weights, and sliced from the portfolio’s first weighted day onward.

Parameters:
  • path (str) – Directory containing one CSV file per factor.

  • available_factors (list[str]) – File names (with extension) to load from path. Entries equal to ".gitkeep" are ignored.

  • portfolio_weights (pd.DataFrame) – Portfolio weights, dates as index and assets as columns; the columns determine which factor-return columns are read, and the index’s first date lower-bounds the returned data.

  • start_date (datetime.date or None) – If given, the earliest date to keep. Raises if earlier than the data’s minimum date.

  • end_date (datetime.date or None) – If given, the latest date to keep. Silently clamped to the data’s maximum date if later.

Returns:

Mapping of factor name (derived from the file name, see _factor_names) to its returns DataFrame, indexed by date with one column per asset.

Return type:

dict[str, pd.DataFrame]

Raises:

Immutable entity for per-asset factor return time-series.

This module provides FactorReturns, a frozen dataclass that wraps a pa.Table of per-asset returns for a single risk factor (e.g. momentum, size, an industry sector). Schema validation runs on construction; an additional validate_asset_coverage() method verifies that all asset columns are a subset of the portfolio’s tickers.

class FactorReturns(table: Table, factor_name: str)[source]#

Bases: object

Immutable wrapper around a PyArrow table of per-asset factor returns.

The expected schema is:

[date: timestamp(ns), ASSET1: float64, ASSET2: float64, ...]

Asset columns must be a subset of the portfolio’s tickers — partial coverage is allowed because the factor-model attribution engine handles missing assets via its daily-coverage logic. Return values may be negative.

Validation performed automatically on construction:

  • The table must contain at least one row.

  • A "date" column of type timestamp(ns) must be present.

  • Every non-date column must be float64.

Parameters:
  • table (pa.Table) – PyArrow table whose first column is a timestamp(ns) date column named "date" and whose remaining columns hold per-asset factor returns as float64.

  • factor_name (str) – Human-readable name of the factor (e.g. "f_momentum"). Used in error messages and logging.

Raises:

Examples

>>> import pyarrow as pa
>>> tbl = pa.table({
...     "date": pa.array(["2024-01-02", "2024-01-03"]).cast(pa.timestamp("ns")),
...     "AAPL": pa.array([0.003, -0.001], type=pa.float64()),
... })
>>> fr = FactorReturns(table=tbl, factor_name="f_momentum")
>>> fr.asset_names
['AAPL']
property asset_names: list[str]#

Return the list of asset column names (excludes "date").

Returns:

Ordered list of asset ticker names present in the table.

Return type:

list[str]

factor_name: str#
table: Table#
validate_asset_coverage(portfolio_tickers: set[str]) → None[source]#

Validate that all asset columns exist in the portfolio’s ticker set.

This check ensures that the factor file does not contain columns for assets that are absent from the portfolio. It does not require that every portfolio ticker is covered — partial coverage is acceptable and handled by the factor-model attribution engine.

Parameters:

portfolio_tickers (set[str]) – Set of ticker symbols present in the portfolio.

Raises:

DataValidationError – If any asset column name is not found in portfolio_tickers.

Restate log factor contributions as simple returns.

A factor model built in log space splits each stock-day’s log return exactly into per-factor pieces. Attribution sums simple returns, so feeding it log pieces makes the factors look too small and pushes the gap into the residual. For each stock and day the factor total TF = sum_k a_k is restated as expm1(TF) and shared out in proportion to the original pieces: a_k * expm1(TF) / TF (scale 1 when TF == 0). Each factor keeps its share of the day’s factor return and the pieces still add up exactly.

The return components (COMPONENT_COLUMNS: f_carry, f_dividends) are simple returns: they are passed through unchanged and are not part of TF.

convert_log_factor_returns_to_simple(factor_tables: Mapping[str, Table], date_column: str = 'date') → dict[str, Table][source]#

Restate per-factor log contributions as simple returns, proportionally.

Parameters:
  • factor_tables (Mapping[str, pa.Table]) – Factor name to a table of date_column plus one float64 column per asset, in log returns. Dates must be unique within each table and of the same type across tables. Null and NaN values mean “missing”.

  • date_column (str, default "date") – Date column name.

Returns:

The atomic factors with the same dates and columns, restated, followed by the return components (COMPONENT_COLUMNS) unchanged (same table objects). Nulls stay null. Files in AGGREGATE_FACTOR_COLUMNS are dropped: the totals come from the portfolio’s own returns. The components are validated like the factors (unique dates, a common date type, finite values) but never restated.

Return type:

dict[str, pa.Table]

Raises:

DataValidationError – If a factor or component table has duplicate dates, if the date column type differs between tables, or if any value is infinite.

Cumulative portfolio / factor / component / idiosyncratic totals of the factor model.

Derived from the cumulative factor contributions the model already produced (FactorModelArrowAttribution.simulated_rets), so the contributions are not linked a second time, and shared by the model and by the dashboard (which gets only the result tables).

cumulative_totals_from_contributions(cumulative_contributions: Table, portfolio_returns: Table, linking: LinkingMethod | str, date_column: str = 'date') → Table[source]#

Cumulative portfolio, factor, component and idiosyncratic return over the attribution window.

The window is the dates of cumulative_contributions that have a non-null portfolio return. factor_returns is the sum of the cumulative contributions of every factor: columns in AGGREGATE_FACTOR_COLUMNS and the return components in COMPONENT_COLUMNS are excluded. Each component present (f_carry, f_dividends) gets its own column (carry_returns, dividends_returns); an absent component gets no column, rather than zeros that would claim a measured zero. portfolio_returns is the running portfolio return and idiosyncratic_returns what the factors and components leave of it.

Parameters:
  • cumulative_contributions (pa.Table) – Cumulative contribution per factor, as simulated_rets: date_column plus one float column per factor. With linking (carino/grap) the linked values on the window dates; with none plain running sums, which may also cover dates without a portfolio return.

  • portfolio_returns (pa.Table) – date_column and portfolio_returns (nulls are not periods; on a repeated date the last row wins).

  • linking (LinkingMethod or str) – The linking method cumulative_contributions was built with. With linking, portfolio_returns is compounded; with none every column is an arithmetic running sum over the window, so the contributions of dates without a portfolio return are taken out of each total.

  • date_column (str, default "date") – Name of the date column in both tables.

Returns:

Columns date_column (same type as in cumulative_contributions), portfolio_returns, factor_returns, then carry_returns and dividends_returns when those components are present, then idiosyncratic_returns. Empty (with those columns) when the window has no dates.

Return type:

pa.Table

Raises:

ValueError – If linking is not a known linking method.

Active factor attribution: the portfolio’s factor decomposition minus the benchmark’s.

The factor model runs twice, on the portfolio’s and on the benchmark’s constituent weights (holdings basis). Per date, each factor’s and each return component’s active contribution is the portfolio’s minus the benchmark’s, and the active idiosyncratic residual is the active return r_p - r_b minus all of them, so a date’s active effects add up to r_p - r_b exactly.

Cumulative effects are linked with the portfolio return as r and the holdings benchmark return as b (see modules.linking). With Carino or GRAP they add up to the compounded R_p - R_b on every date; with none they are running sums that add up to the running sum of r_p - r_b.

RESIDUAL_COLUMN = 'f_idio_returns'#

Active residual column; named like the residual of FactorModelResult.daily_shares.

active_factor_attribution(portfolio_contributions: Table, portfolio_returns: Table, benchmark_contributions: Table, benchmark_returns: Table, linking: LinkingMethod | str, date_column: str = 'date') → ActiveFactorResult[source]#

Active (portfolio minus benchmark) factor attribution from two factor decompositions.

Parameters:
  • portfolio_contributions (pa.Table) – Each side’s daily contributions, as FactorModelArrowAttribution.portfolio_attribution_ts: date_column (unique dates) plus one float column per factor or return component.

  • benchmark_contributions (pa.Table) – Each side’s daily contributions, as FactorModelArrowAttribution.portfolio_attribution_ts: date_column (unique dates) plus one float column per factor or return component.

  • portfolio_returns (pa.Table) – Each side’s return, as FactorModelArrowAttribution.portfolio_returns: date_column and portfolio_returns (null where the side has none).

  • benchmark_returns (pa.Table) – Each side’s return, as FactorModelArrowAttribution.portfolio_returns: date_column and portfolio_returns (null where the side has none).

  • linking (LinkingMethod or str) – "carino", "grap" or "none".

  • date_column (str, default "date") – Date column of every table.

Returns:

Tables over the window: the portfolio contribution dates with a portfolio return that also have benchmark contributions and a benchmark return. Portfolio return dates left out are counted in one warning. Columns: factors (sorted), then components, then f_idio_returns.

Return type:

ActiveFactorResult

Raises:
  • ValueError – If linking is not a known linking method.

  • PerformanceAttributionError – If a portfolio or benchmark return on the window is not finite or is at or below -100%, or an active contribution is not finite (each naming the date), or linking overflows.

warn_unpriced_holdings(weights: Table, asset_returns: Table, side: str, date_column: str = 'date') → int[source]#

Warn once when weighted tickers have no return on a date the side has a return.

The factor model’s return is sum w * r over the tickers with a return, so a weighted ticker without one counts as 0 that day. Only dates with a returns row on which at least one weighted ticker has a return are checked; on the others the side has no return and the date is dropped.

Parameters:
  • weights (pa.Table) – Start-of-day weights: date_column plus one column per ticker. Null and 0.0 weights are not holdings.

  • asset_returns (pa.Table) – date_column plus one return column per ticker (null = no return). A weighted ticker without a column has no return on any date.

  • side (str) – Named in the message (e.g. "benchmark").

  • date_column (str, default "date") – Date column of both tables.

Returns:

Number of weighted ticker-dates without a return (0: nothing logged).

Return type:

int

warn_weight_sums(weights: Table, side: str, dates: Iterable | None = None, date_column: str = 'date') → int[source]#

Warn once when the side’s net weights do not sum to 1 on the checked dates.

The factor model’s return is sum w * r over the weights as given, so a sum below 1 leaves the remainder as cash that earns 0 and has no factor exposure, and a sum above 1 is used as given. Adding an explicit zero-return cash weight would change no number; the weights have to be completed or rescaled by whoever knows the benchmark. Nothing is raised.

Parameters:
  • weights (pa.Table) – Start-of-day weights: date_column plus one column per ticker. A null weight is not a holding and counts as 0.

  • side (str) – Named in the message (e.g. "benchmark").

  • dates (Iterable or None, default None) – Dates to check, as date_column holds them (the dates the side is attributed on). None checks every row.

  • date_column (str, default "date") – Date column of weights.

Returns:

Number of checked dates whose net weights differ from 1 by more than WEIGHT_SUM_TOLERANCE (0: nothing logged).

Return type:

int