跳转至

fincore.attribution

Brinson Attribution

fincore.attribution.brinson

Brinson attribution analysis for portfolio performance.

Decomposes portfolio excess returns into: - Allocation effect: returns from overweighting/underweighting sectors - Selection effect: returns from stock selection within sectors - Interaction effect: returns from interaction of allocation and selection

BrinsonAttribution(sector_mapping=None)

Brinson attribution calculator with sector mapping support.

Provides convenient interface for multi-period Brinson attribution with sector/asset classification.

Initialize Brinson attribution calculator.

参数:

名称 类型 描述 默认
sector_mapping dict

Mapping from sector name to a list of asset column names. Example: {'Technology': ['AAPL', 'MSFT'], 'Financial': ['JPM']}

None

calculate(returns, benchmark_returns=None, weights=None, method='brinson')

Calculate Brinson attribution for returns DataFrame.

参数:

名称 类型 描述 默认
returns DataFrame

Asset returns (T x N assets). Columns should be asset names.

必需
benchmark_returns DataFrame

Benchmark returns. If None, uses equal-weighted benchmark.

None
weights DataFrame

Portfolio weights. If None, uses equal weights.

None
method str

Attribution method. Options: 'brinson', 'brinson_hood'.

"brinson"

返回:

类型 描述
DataFrame

Attribution results by period.

brinson_attribution(portfolio_returns, benchmark_returns, portfolio_weights, benchmark_weights)

Calculate Brinson attribution for a single period.

参数:

名称 类型 描述 默认
portfolio_returns Series or ndarray

Portfolio returns for the period.

必需
benchmark_returns Series or ndarray

Benchmark returns for the period.

必需
portfolio_weights DataFrame

Portfolio weights by sector/asset for the period. benchmark_weights : pd.DataFrame Benchmark weights by sector/asset for the period.

必需

返回:

类型 描述
dict

Dictionary with attribution breakdown: - 'allocation': Allocation effect - 'selection': Selection effect - 'interaction': Interaction effect - 'total': Total active return - 'portfolio_return': Portfolio return - 'benchmark_return': Benchmark return

示例:

>>> import pandas as pd
>>> import numpy as np
>>> portfolio_returns = np.array([0.05, 0.03, -0.02, 0.04])
>>> benchmark_returns = np.array([0.03, 0.02, -0.01, 0.03])
>>> portfolio_weights = pd.DataFrame({
...     'Sector_A': [0.4, 0.3, 0.2, 0.1],
...     'Sector_B': [0.3, 0.3, 0.3, 0.1],
... })
>>> benchmark_weights = pd.DataFrame({
...     'Sector_A': [0.5, 0.3, 0.1, 0.1],
...     'Sector_B': [0.3, 0.3, 0.3, 0.1],
... })
>>> result = brinson_attribution(
...     portfolio_returns, benchmark_returns,
...     portfolio_weights, benchmark_weights
... )
>>> print(f"Allocation: {result['allocation']:.2%}")

brinson_results(portfolio_returns, benchmark_returns, portfolio_weights, benchmark_weights, periods=None)

Calculate Brinson attribution over multiple periods.

参数:

名称 类型 描述 默认
portfolio_returns Series or ndarray

Portfolio returns (T periods).

必需
benchmark_returns Series or ndarray

Benchmark returns (T periods).

必需
portfolio_weights DataFrame

Portfolio weights for each period (T x sectors).

必需
benchmark_weights DataFrame

Benchmark weights for each period (T x sectors).

必需
periods list of str

Period labels. If None, uses integer indices.

None

返回:

类型 描述
DataFrame

DataFrame with attribution results for each period. Columns: period, allocation, selection, interaction, total, portfolio_return, benchmark_return

brinson_cumulative(portfolio_returns, benchmark_returns, portfolio_weights, benchmark_weights)

Calculate cumulative Brinson attribution.

This aggregates per-period Brinson effects (arithmetic sum across periods). It also reports geometric cumulative portfolio/benchmark returns computed from per-period weighted returns.

参数:

名称 类型 描述 默认
portfolio_returns Series or ndarray

Portfolio returns.

必需
benchmark_returns Series or ndarray

Benchmark returns.

必需
portfolio_weights DataFrame

Portfolio weights (final weights for cumulative).

必需
benchmark_weights DataFrame

Benchmark weights (final weights for cumulative).

必需

返回:

类型 描述
dict

Cumulative attribution breakdown.

Fama-French

fincore.attribution.fama_french

Fama-French multi-factor model implementation.

Provides factor model estimation and attribution using the Fama-French multi-factor framework: - 3-Factor model: Market (MKT), Size (SMB), Value (HML) - 5-Factor model: MKT, SMB, HML, Profitability (RMW), Investment (CMA) - Momentum: Fama-French-Carhart 4-factor model

FamaFrenchFitResult

Bases: TypedDict

Result of Fama-French factor model regression.

属性:

名称 类型 描述
alpha float

Intercept (alpha) of the regression.

betas dict[str, float]

Factor loadings for each factor.

r_squared float

R-squared of the regression.

std_errors ndarray

Standard errors of coefficients.

p_values ndarray

P-values for coefficient significance tests.

residuals ndarray

Residuals from the regression.

FamaFrenchModel(model_type='5factor', risk_free_rate=0.0)

Fama-French multi-factor model estimator.

Supports OLS regression with Newey-West standard errors and various factor model specifications.

Initialize Fama-French model.

参数:

名称 类型 描述 默认
model_type str

Factor model specification. Options: '3factor', '5factor', '4factor_mom'

"5factor"
risk_free_rate float

Risk-free rate for excess returns calculation.

0.0

fit(returns, factor_data, method='ols', newey_west_lags=1)

Estimate factor model using OLS regression.

参数:

名称 类型 描述 默认
returns Series or DataFrame

Asset or portfolio returns to explain.

必需
factor_data DataFrame

Factor returns with columns matching factor definitions.

必需
method str

Estimation method. Options: 'ols', 'wls', 'gls'.

"ols"
newey_west_lags int

Number of lags for Newey-West standard errors.

1

返回:

类型 描述
dict

Dictionary containing: - 'alpha': Intercept (alpha) - 'betas': Factor loadings - 'r_squared': R-squared of regression - 'std_errors': Standard errors (Newey-West if lags > 0) - 'p_values': P-values for coefficients - 'residuals': Regression residuals

predict(factor_data)

Predict returns using estimated model.

参数:

名称 类型 描述 默认
factor_data DataFrame

Factor returns with columns matching factor definitions.

必需

返回:

类型 描述
ndarray

Predicted returns.

get_factor_exposures(returns, factor_data, rolling_window=None)

Calculate rolling factor exposures (betas).

参数:

名称 类型 描述 默认
returns DataFrame

Asset returns (T x N).

必需
factor_data DataFrame

Factor returns (T x K factors).

必需
rolling_window int

Rolling window size. If None, full sample.

None

返回:

类型 描述
DataFrame

Rolling factor exposures (T x K).

attribution_decomposition(returns, factor_data)

Decompose returns using factor model.

参数:

名称 类型 描述 默认
returns Series

Portfolio returns to attribute.

必需
factor_data DataFrame

Factor returns.

必需

返回:

类型 描述
dict

Factor attribution breakdown.

FamaFrenchProvider

Bases: Protocol

Protocol for Fama-French factor data providers.

A provider function that takes date range and library name, and returns a DataFrame of factor returns.

__call__(start, end, library)

Fetch Fama-French factor data.

参数:

名称 类型 描述 默认
start str

Start date (YYYY-MM-DD format).

必需
end str

End date (YYYY-MM-DD format).

必需
library str

Data library identifier.

必需

返回:

类型 描述
DataFrame

Factor returns with columns for each factor.

fetch_ff_factors(start, end, library='french', *, provider=None, copy=True)

Fetch Fama-French factors.

.. note::

A concrete data provider must be configured before calling this function. Pass a provider that implements the FamaFrenchProvider protocol, or set a module-level provider via :func:set_ff_provider.

参数:

名称 类型 描述 默认
start str

Start date (YYYY-MM-DD).

必需
end str

End date (YYYY-MM-DD).

必需
library str

Data source. Options: 'french', 'chinese'.

"french"

返回:

类型 描述
DataFrame

DataFrame with factor returns. Columns depend on library.

引发:

类型 描述
NotImplementedError

Raised when no provider is configured.

set_ff_provider(provider)

Set the module-level Fama-French factor provider and clear cache.

clear_ff_factor_cache()

Clear the in-process factor cache used by :func:fetch_ff_factors.

calculate_idiosyncratic_risk(returns, factor_data, model=None)

Calculate idiosyncratic volatility (asset-specific risk).

Measures risk that cannot be diversified away: VAR(asset) - cov(asset, market) * var(market) / cov(market, market)

参数:

名称 类型 描述 默认
returns DataFrame

Asset returns (N assets x T).

必需
factor_data DataFrame

Market factor returns (T x K).

必需
model FamaFrenchModel

Pre-fitted model. If None, fits new model.

None

返回:

类型 描述
Series

Idiosyncratic volatility for each asset.

Style Analysis

fincore.attribution.style

Style analysis for portfolio returns.

Analyzes portfolio returns by style characteristics: - Size (large-cap, mid-cap, small-cap) - Value (value, growth) Momentum (winner, loser) Volatility (high, low)

StyleResult(exposures, returns_by_style, overall_returns)

Container for style analysis results.

Initialize style result.

参数:

名称 类型 描述 默认
exposures DataFrame

Style exposures (N assets x S styles).

必需
returns_by_style DataFrame

Returns for each style (styles x 1).

必需
overall_returns Series

Overall portfolio returns.

必需

style_summary property

Get summary of style returns.

__contains__(key)

Support key in result syntax.

__getitem__(key)

Support result[key] syntax.

to_dict()

Convert results to dictionary.

style_analysis(returns, market_caps=None, book_to_price=None, momentum_window=252, size_quantiles=None, value_scores=None)

Perform comprehensive style analysis on portfolio returns.

参数:

名称 类型 描述 默认
returns DataFrame

Asset returns (T x N). Columns should be asset names.

必需
market_caps Series

Market capitalizations for size classification. If None, market_cap weighted returns used.

None
book_to_price Series

Book-to-price ratios for value classification. If None, assumes all equity.

None
momentum_window int

Lookback period for momentum calculation.

252
size_quantiles list of float

Quantiles for size classification.

[0.5, 0.5]
value_scores Series

Fundamental value scores for value classification. If provided, used instead of book_to_price.

None

返回:

类型 描述
StyleResult

Style analysis results with exposures and returns by style.

calculate_style_tilts(returns, factor_returns=None, window=252)

Calculate rolling style exposures (size, value, momentum).

参数:

名称 类型 描述 默认
returns DataFrame

Asset returns (T x N).

必需
factor_returns DataFrame

Factor returns for calculating style relative to factor. If None, uses cross-sectional ranking.

None
window int

Rolling window size.

252

返回:

类型 描述
DataFrame

Time series of style exposures for each asset. Index: dates, Columns: {asset}_{style} format.

calculate_regression_attribution(portfolio_returns, style_returns=None, style_exposures=None)

Attribute portfolio returns using style exposures.

If style_returns and style_exposures are not provided, they are derived automatically by running :func:style_analysis on portfolio_returns (which must be a DataFrame of asset returns in that case).

参数:

名称 类型 描述 默认
portfolio_returns Series or DataFrame

Portfolio returns (Series) or asset returns (DataFrame). If DataFrame and style_returns/style_exposures are None, a style analysis is run automatically.

必需
style_returns DataFrame

Returns for each style factor (T x S).

None
style_exposures DataFrame

Style exposures (N x S) or (T x S).

None

返回:

类型 描述
dict

Attribution by style factor, including 'residual'.

analyze_performance_by_style(returns, style_exposures=None)

Analyze performance metrics grouped by style.

If style_exposures is not provided, it is derived automatically by running :func:style_analysis.

参数:

名称 类型 描述 默认
returns DataFrame

Asset returns (T x N).

必需
style_exposures DataFrame

Style exposures (N x S). If None, derived from style_analysis.

None

返回:

类型 描述
DataFrame

Performance metrics by style (columns: {style}_return).

fetch_style_factors(tickers, factors=None, library='us')

Fetch style factor data.

.. note::

A concrete data provider must be configured before calling this function. Pass pre-fetched factor data directly to :func:style_analysis or :func:calculate_style_tilts.

参数:

名称 类型 描述 默认
tickers list of str

Asset tickers.

必需
factors list of str

Style factors to fetch.

["size", "value", "momentum"]
library str

Data source library. Options: 'us', 'chinese'.

"us"

返回:

类型 描述
DataFrame

Factor data with MultiIndex (date, factor).

引发:

类型 描述
NotImplementedError

Always raised until a data provider is configured.