跳转至

Factor-analysis API

fincore.alphalens is the source-shaped strict façade. For new code, prefer the enhanced fincore.factor_analysis API: prepare factor data once, analyze the resulting clean table once, and render returned artifacts explicitly.

Plotting is optional and resolved only when a renderer runs. Install fincore[alphalens] for rendering; compute-only enhanced workflows use fincore[factor-analysis].

Enhanced API

fincore.factor_analysis

Enhanced factor-analysis contracts and standalone Task 3 data kernel.

FactorFunctionSpec(module, public_name, introspection_signature, source_signature, implementation, profile, optional_extra=None, adapter=None, result_projection=None) dataclass

One named function contract on a factor-analysis compatibility surface.

FactorWorkflowSpec(public_name, introspection_signature, source_signature, model_ref, renderer_ref, optional_extra=None, result_projection='legacy_none_show', by_group_variants=()) dataclass

A deferred tear-sheet workflow, including its future renderer lifecycle.

FactorLossReport(input_count, finite_factor_count, forward_returns_count, binning_count, factor_input_loss, forward_returns_loss, binning_loss, total_loss) dataclass

A transparent breakdown of rows removed during factor preparation.

legacy_forward_returns_loss property

Loss wording used by the pinned strict facade's stdout projection.

PreparedFactorData(data, loss_report, calendar) dataclass

Prepared factor table, loss accounting, and inferred trading calendar.

EnhancedNonMatchingTimezoneError

Bases: FactorDataError

Factor and price timestamps use different timezone conventions.

FactorDataError

Bases: ValueError

Base class for invalid factor-analysis inputs.

FactorLossExceededError(message='', report=None)

Bases: FactorDataError

The enhanced kernel dropped more input rows than the accepted limit.

MaxLossExceededError(message='', report=None)

Bases: Exception

Pinned strict identity for a rejected cleaning-loss budget.

NonMatchingTimezoneError

Bases: Exception

Pinned strict identity for a factor/prices timezone mismatch.

EventAnalysisModel(event_windows, mean_returns, return_distribution, quantile_average_returns, aggregate_quantile_average_returns) dataclass

Frozen event-window values, averages, and distribution inputs.

__post_init__()

Own independent event data rather than caller-visible work buffers.

FactorAnalysisConfig(long_short=True, group_neutral=False, equal_weight=False, by_group=False, periods=(), event_before=None, event_after=None, turnover_periods=(1,), time_aggregation=('M',), include_pyfolio=True, pyfolio_capital=None, pyfolio_benchmark_period='1D') dataclass

Every typed option that can alter an :class:FactorAnalysisModel.

__post_init__()

Normalize public options before computing the frozen config digest.

FactorAnalysisModel(config, factor_data, forward_periods, quantile_statistics, factor_weights, factor_returns, factor_cumulative_returns, legacy_quantile_cumulative_returns, factor_positions, alpha_beta, mean_returns_by_quantile, std_error_by_quantile, mean_returns_by_date, std_error_by_date, aggregate_mean_returns_by_quantile, aggregate_std_error_by_quantile, aggregate_mean_returns_by_date, aggregate_std_error_by_date, aggregate_mean_return_spread, aggregate_mean_return_spread_std, mean_return_spread, mean_return_spread_std, information_coefficient, mean_information_coefficient, aggregate_information_coefficient, aggregate_mean_information_coefficient, summary_information_coefficient, quantile_turnover, rank_autocorrelation, grouped_results, time_aggregated_results, aggregate_time_aggregated_results, pyfolio_inputs, event_input_snapshot, event_returns=None, result_fingerprint='') dataclass

One compute-once analytical snapshot consumed by later renderers.

__post_init__()

Store private canonical snapshots for every renderer-facing field.

to_serializable()

Return a JSON-compatible, renderer-free representation of this model.

FactorGroupAnalysis(group, quantile_statistics, factor_weights, factor_returns, mean_returns_by_quantile, std_error_by_quantile, information_coefficient, mean_information_coefficient, quantile_turnover, rank_autocorrelation) dataclass

Typed, per-group analytical data used by grouped tables and charts.

__post_init__()

Own independent group data rather than caller-visible work buffers.

PyfolioFactorInputs(returns, positions, benchmark_rets) dataclass

Typed, enhanced representation of the three inputs expected by Pyfolio.

as_legacy_tuple()

Return the immutable container's legacy Alphalens tuple projection.

FactorTearSheetArtifacts(model, figures, tables) dataclass

Caller-owned figures and renderer-ready tables for one workflow.

Enhanced workflows do not display or close these figures by default. The strict Alphalens facade uses the same artifact object internally, then applies its legacy show-and-close projection at the public boundary.

GridFigure(rows, cols)

One lazily-created figure with the pinned row/cell grid primitives.

create_new_figure()

Return the one figure owned by this grid for explicit ownership checks.

next_row()

Allocate the next full-width row using the source cursor grammar.

next_cell()

Allocate the next cell, advancing to a new row when necessary.

close()

Close only this grid's own figure and release its layout references.

analyze_factor(factor_data, *, long_short=True, group_neutral=False, equal_weight=False, by_group=False, periods=None, turnover_periods=(1,), time_aggregation=('M',), include_pyfolio=True, pyfolio_capital=None, pyfolio_benchmark_period='1D', event_returns=None, event_before=None, event_after=None)

Compute one immutable, renderer-ready model from already-clean data.

The enhanced public contract always requires positive, unique turnover lags. Source-compatible tear-sheet oddities are intentionally kept in a private assembly bridge so they cannot weaken this API's validation.

add_custom_calendar_timedelta(input, timedelta, freq)

Add a timedelta while counting whole days through a trading calendar.

backshift_returns_series(series, N)

Move a backward-looking MultiIndex return series N sessions earlier.

diff_custom_calendar_timedeltas(start, end, freq)

Return end - start with whole-day components measured by freq.

get_forward_returns_columns(columns, require_exact_day_multiple=False)

Return columns matching the pinned forward-return timedelta grammar.

infer_trading_calendar(factor_idx, prices_idx)

Infer active weekdays and missing-session holidays from two date indexes.

Both inputs are copied into a normalized DatetimeIndex first, so the function has no side effect on caller-owned index frequency metadata.

timedelta_strings_to_integers(sequence)

Return the whole-day portion of each forward-return label.

timedelta_to_string(timedelta)

Format a Timedelta using the pinned forward-return label grammar.

compute_forward_returns(factor, prices, periods=(1, 5, 10), filter_zscore=None, cumulative_returns=True)

Compute forward percentage returns aligned exactly to a factor MultiIndex.

prepare_factor_data(factor, prices, *, groupby=None, quantiles=5, bins=None, periods=(1, 5, 10), max_loss=0.35, binning_by_group=False, filter_zscore=None, groupby_labels=None, zero_aware=False, cumulative_returns=True)

Normalize factor/prices and return a cleaned factor table with loss detail.

prepare_factor_data_from_forward_returns(factor, forward_returns, *, groupby=None, binning_by_group=False, quantiles=5, bins=None, groupby_labels=None, max_loss=0.35, zero_aware=False)

Prepare a factor table when forward returns have already been computed.

quantize_factor(factor_data, quantiles=5, bins=None, by_group=False, no_raise=False, zero_aware=False)

Assign one period-wise quantile/bin label per finite factor observation.

average_cumulative_return_by_quantile(factor_data, returns, periods_before=10, periods_after=15, demeaned=True, group_adjust=False, by_group=False)

Average cumulative event returns for each factor quantile (and group).

common_start_returns(factor, returns, before, after, cumulative=False, mean_by_date=False, demean_by=None)

Align return windows around each factor date on a shared integer offset index.

compute_mean_returns_spread(mean_returns, upper_quant, lower_quant, std_err=None)

Compute the upper-minus-lower quantile mean-return spread and error.

cumulative_returns(returns)

Compound simple returns from one, treating missing observations as zero.

This is the local, profile-free equivalent of the pinned Alphalens empyrical.cum_returns(..., starting_value=1) boundary. It must not use fincore's validation-wrapped metric dispatcher because legacy factor return streams intentionally allow missing observations.

factor_alpha_beta(factor_data, returns=None, demeaned=True, group_adjust=False, equal_weight=False)

Estimate annualized intercept and market beta from factor returns.

The enhanced kernel uses a small NumPy least-squares projection. The strict facade separately verifies the optional statsmodels boundary before delegating here, so importing this module remains optional-dependency free.

factor_information_coefficient(factor_data, group_adjust=False, by_group=False)

Compute per-date Spearman IC values for every forward-return period.

factor_rank_autocorrelation(factor_data, period=1)

Compute cross-sectional rank autocorrelation after a date-period shift.

factor_returns(factor_data, demeaned=True, group_adjust=False, equal_weight=False, by_asset=False)

Compute weighted forward returns, optionally retaining individual assets.

The aggregate path deliberately uses pandas' default sum projection: an all-missing weighted period becomes 0.0 for the date, matching the pinned strict surface and keeping the enhanced kernel profile-free.

factor_weights(factor_data, demeaned=True, group_adjust=False, equal_weight=False)

Build date-wise factor weights with optional group-neutral normalization.

mean_information_coefficient(factor_data, group_adjust=False, by_group=False, by_time=None)

Aggregate IC by optional time and group dimensions.

mean_return_by_quantile(factor_data, by_date=False, by_group=False, demeaned=True, group_adjust=False)

Return mean forward returns and standard errors by factor quantile.

quantile_turnover(quantile_factor, quantile, period=1)

Return the fraction of names newly entering one quantile per date.

create_pyfolio_input(factor_data, period, capital=None, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None, benchmark_period='1D')

Build typed daily returns, positions, and optional benchmark for Pyfolio.

The enhanced builder is independent of external Pyfolio. It merely emits data in the workflow's canonical shape; rendering stays in :mod:fincore.pyfolio and remains lazily optional.

factor_cumulative_returns(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None)

Simulate and compound a filtered factor portfolio for one return period.

factor_positions(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None)

Simulate gross-normalized asset positions for a filtered factor portfolio.

positions(weights, period, freq=None)

Build gross-normalized active positions for overlapping factor trades.

period may include an intraday remainder (for example "1D3h"). Whole session days advance with the supplied trading calendar while the remainder stays at its wall-clock time. The output includes every trade and expiry timestamp, with a zero row after the final holding expires.

close_owned_figures(artifacts)

Close exactly the figures returned by an enhanced workflow.

create_event_returns_tear_sheet(model, *, std_bar=True, by_group=None, show=False, plotter=None, _include_returns_tables=True)

Render aggregate and optional group event-window return sections.

create_event_study_tear_sheet(model, *, avgretplot=None, rate_of_ret=True, n_bars=50, show=False, plotter=None)

Render event distribution, optional event returns, and quantile-return sections.

create_full_tear_sheet(model, *, by_group=None, show=False, legacy_projection=False, plotter=None)

Compose the returns, information, and turnover artifacts from one model.

create_information_tear_sheet(model, *, by_group=None, show=False, legacy_projection=False, plotter=None)

Render IC time-series, distributions, Q-Q, monthly, and group sections.

create_returns_tear_sheet(model, *, by_group=None, show=False, legacy_projection=False, plotter=None)

Render portfolio, quantile, spread, and optional group returns sections.

create_summary_tear_sheet(model, *, show=False, legacy_projection=False, plotter=None)

Render the compact returns, information, and turnover sections from one model.

create_turnover_tear_sheet(model, *, turnover_periods=None, show=False, legacy_projection=False, plotter=None)

Render stored quantile-turnover and rank-autocorrelation sections.

show_owned_figures(artifacts)

Display exactly the figures returned by one enhanced workflow.

Strict utilities

fincore.alphalens.utils

Strict Alphalens utility facade backed by the Task 3 factor-data kernel.

MaxLossExceededError(message='', report=None)

Bases: Exception

Pinned strict identity for a rejected cleaning-loss budget.

NonMatchingTimezoneError

Bases: Exception

Pinned strict identity for a factor/prices timezone mismatch.

rethrow(exception, additional_message)

Re-raise exception after appending strict-source context to args.

non_unique_bin_edges_error(func)

Decorate a quantization callable with the pinned duplicate-edge guidance.

demean_forward_returns(factor_data, grouper=None)

Return copied forward returns demeaned by date or the supplied grouping.

print_table(table, name=None, fmt=None)

Display one strict-source table lazily through IPython's display hook.

rate_of_return(period_ret, base_period)

Convert a named forward-return period to a named base-period rate.

std_conversion(period_std, base_period)

Scale a named forward-period standard deviation to base_period.

quantize_factor(*args, **kwargs)

Bind the source signature while retaining the legacy decorator signature.

Strict performance

fincore.alphalens.performance

Strict Alphalens performance facade backed by characterized kernels.

positions(weights, period, freq=None)

Project the standalone active-position kernel through the strict facade.

factor_cumulative_returns(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None)

Return the source-projected cumulative factor portfolio curve.

factor_positions(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None)

Project simulated factor positions through the strict facade.

create_pyfolio_input(factor_data, period, capital=None, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None, benchmark_period='1D')

Return the strict legacy 3-tuple from the enhanced typed bridge.

Strict tear sheets

fincore.alphalens.tears

Strict, lazy Alphalens tear-sheet projection backed by model workflows.

GridFigure(rows, cols)

One lazily-created figure with the pinned row/cell grid primitives.

create_new_figure()

Return the one figure owned by this grid for explicit ownership checks.

next_row()

Allocate the next full-width row using the source cursor grammar.

next_cell()

Allocate the next cell, advancing to a new row when necessary.

close()

Close only this grid's own figure and release its layout references.

create_summary_tear_sheet(factor_data, long_short=True, group_neutral=False)

Render the pinned summary workflow from a single compute-once model.

create_returns_tear_sheet(factor_data, long_short=True, group_neutral=False, by_group=False)

Render the pinned returns workflow and preserve its show/close lifecycle.

create_information_tear_sheet(factor_data, group_neutral=False, by_group=False)

Render the pinned information workflow using the same model snapshot.

create_turnover_tear_sheet(factor_data, turnover_periods=None)

Render source-shaped turnover periods from their stored model results.

create_full_tear_sheet(factor_data, long_short=True, group_neutral=False, by_group=False)

Compose the three legacy sections from one shared model snapshot.

create_event_returns_tear_sheet(factor_data, returns, avgretplot=(5, 15), long_short=True, group_neutral=False, std_bar=True, by_group=False)

Render source event-return sections from one model-bound event window.

create_event_study_tear_sheet(factor_data, returns, avgretplot=(5, 15), rate_of_ret=True, n_bars=50)

Render the legacy event-study composition from a typed event model.