qis.LinearModel¶
- class qis.LinearModel(x, y, loadings=None, x_covars=None, residual_vars=None)[source]¶
Bases:
objectA linear factor model for analyzing asset returns using multiple factors.
This class implements a linear factor model in which factors explain asset returns through time-varying loadings and an unexplained alpha component. The model supports factor attribution analysis, alpha calculation, model diagnostics, and performance evaluation.
- Variables:
x (pandas.DataFrame | pandas.Series) – Factor returns with dates as rows and factors as columns.
y (pandas.DataFrame | pandas.Series) – Asset returns with dates as rows and assets as columns.
loadings (Dict[str, pandas.DataFrame]) – Time-varying factor loadings keyed by factor name, in the order of the columns of
x. Each value is a dates-by-assets frame:loadings[q].loc[t, i]is the loading of assetion factorqestimated att.x_covars (Dict[pandas.Timestamp, pandas.DataFrame] | None) – Factor covariance matrices, factors by factors, keyed by estimation date.
residual_vars (pandas.DataFrame | None) – Asset residual variances (not volatilities), dates by assets.
- Parameters:
Note
Factor loadings are assumed to be pre-estimated. Inputs must use aligned datetime indices. Portfolio-level outputs are NaN where an asset with a non-zero weight has a missing loading or residual variance.
- Raises:
AssertionError – If loading keys do not match the factor columns in
x.- Parameters:
- __init__(x, y, loadings=None, x_covars=None, residual_vars=None)¶
Methods
__init__(x, y[, loadings, x_covars, ...])Compute factor-only active risk, excluding idiosyncratic risk.
compute_agg_factor_exposures(weights)Compute portfolio factor exposures
X[t, q] = sum_i B[t, i, q] * w[t, i].compute_factor_risk_contribution(weights[, ...])Compute factor risk contributions and their ratios for portfolio weights over time.
get_asset_factor_attribution([asset, add_total])Attribute an asset's return to factors with the loadings of the previous date.
get_asset_factor_betas([time_period, asset])Get the loadings of one asset, dates by factors, over an optional time period.
Get the dates-by-assets loadings of the first factor.
get_factor_alpha([x, y, lag, span])Compute the model residual
y[t] - sum_q B[t - lag, q] x[t, q]and the explained part.get_factor_loadings(factor)Get the dates-by-assets loadings of a specific factor.
get_loadings_at_date(date)Return the loadings in force at
date, factors by assets.get_model_ewm_r2([span, lag])Compute the exponentially weighted, uncentred R² of each asset.
get_model_residuals_corrs([span])Compute the EWM correlation matrix of the in-sample residuals at the last date.
plot_factor_loadings(factor[, var_format, ...])Plot factor loadings time series.
print()Print model components for debugging.
Attributes
- get_loadings_at_date(date)[source]¶
Return the loadings in force at
date, factors by assets.Each factor’s loadings are read as of
date: the last row dated at or before it.- Parameters:
date (Timestamp) – Evaluation date.
- Returns:
Loadings with factors as rows and assets as columns, the transpose
B'of the assets-by-factors matrix thatqis.RiskModel.factor_loadingsholds.- Raises:
ValueError – If the model has no loadings.
- Return type:
- compute_agg_factor_exposures(weights)[source]¶
Compute portfolio factor exposures
X[t, q] = sum_i B[t, i, q] * w[t, i].Loadings and weights are taken on the same date
tof each factor’s loading index. Weights are selected as of each loading date: the last weight row dated at or before it, so weight rows dated off the loading grid are not dropped. A missing weight inside a weight row means the asset is not held.- Parameters:
weights (DataFrame) – Portfolio weights, dates by assets.
- Returns:
Exposures, loading dates by factors. A date is NaN before the first weight row and wherever an asset with a non-zero weight has no loading, including the estimator warm-up rows; a portfolio of zero weights has exposure zero.
- Return type:
- get_asset_factor_betas(time_period=None, asset=None)[source]¶
Get the loadings of one asset, dates by factors, over an optional time period.
- Parameters:
time_period (TimePeriod)
asset (str)
- Return type:
- get_asset_factor_attribution(asset=None, add_total=True)[source]¶
Attribute an asset’s return to factors with the loadings of the previous date.
The contribution of factor
qattisB[t-1, asset, q] * x[t, q].- Parameters:
- Returns:
Contributions, dates by factors.
Totalis NaN on any date where a lagged loading or a factor return is missing, such as the warm-up rows.- Return type:
- get_factor_alpha(x=None, y=None, lag=1, span=None)[source]¶
Compute the model residual
y[t] - sum_q B[t - lag, q] x[t, q]and the explained part.Loadings are forward-filled onto the index of
xbefore the shift. The residual is called factor alpha, but it is the residual of a regression without an intercept, so it holds any intercept plus noise.- Parameters:
x (DataFrame | None) – Factor returns, dates by factors;
self.xwhen None.y (DataFrame | None) – Asset returns, dates by assets, on the same index as
x;self.ywhen None.lag (Literal[0, 1]) – 1 applies the loadings estimated on the previous date, a point-in-time step-ahead residual; 0 applies the same-date loadings, an in-sample fit.
span (int | None) – If given, the residual is smoothed by
qis.compute_ewmwith this span.
- Returns:
Tuple of (factor_alpha, explained_returns), both dates by assets.
- Raises:
AssertionError – If the indexes of
xandydiffer.- Return type:
- get_model_ewm_r2(span=52, lag=0)[source]¶
Compute the exponentially weighted, uncentred R² of each asset.
R2[t] = 1 - sum_m lambda^(t-m) e[m]^2 / sum_m lambda^(t-m) y[m]^2withlambda = 1 - 2 / (span + 1), whereeis the residual ofget_factor_alpha(lag)and both sums run over the same dates, those on which the residual and the return are finite, with decay counted over those dates only. The two moments therefore start together, after the warm-up, and no seed biases their ratio. The result is clipped to [0, 1].The R² is uncentred: both moments are about zero, not about a mean, which matches the regression through the origin that
EwmLinearModel.fitruns by default. With the defaultlag=0the loadings datedtexplain the return datedt, which they were estimated from, so it is an in-sample fit;lag=1gives the point-in-time, step-ahead R².
- get_model_residuals_corrs(span=52)[source]¶
Compute the EWM correlation matrix of the in-sample residuals at the last date.
The correlation comes from EWM second moments about zero of the lag-0 residuals of
get_factor_alpha, seeded at zero, evaluated at the last date only.- Parameters:
span (int) – EWM span of the second moments.
- Returns:
the assets-by-assets correlation matrix and, per asset, the mean of its correlations with the other assets.
avg_corris NaN for a single asset.- Return type:
Tuple of (corr, avg_corr)
- compute_factor_risk_contribution(weights, factor_var_name='Systematic', idiosyncratic_var_name='Idiosyncratic')[source]¶
Compute factor risk contributions and their ratios for portfolio weights over time.
Calculates the contribution of each factor to portfolio risk using factor loadings, covariance matrices, and residual variances. This method performs risk decomposition by computing how much each systematic factor and idiosyncratic risk contribute to the total portfolio variance.
For each date of
x_covars, the weights, the loadings and the residual variances are each read as of that date: the last row dated at or before it. With exposuresx = B' w(Bassets by factors), the systematic variance isx' F xand the residual variancesum_i psi_i w_i^2. A missing weight means the asset is not held.- Parameters:
weights (DataFrame) – Portfolio weights DataFrame with dates as index and assets as columns. Each row represents portfolio weights at a specific date.
factor_var_name (str) – Name for the factor risk column in output. Defaults to ‘Systematic’.
idiosyncratic_var_name (str) – Name for the idiosyncratic risk column in output. Defaults to ‘Idiosyncratic’. Must not match a factor contribution column.
- Returns:
Tuple containing total-risk contribution ratios, factor contributions normalized by total variance, factor contributions normalized by systematic variance, and the systematic and idiosyncratic portfolio variance panel. A date is NaN when an asset with a non-zero weight has a missing loading or residual variance, or when no residual variances are dated at or before it. A factor of
x_covarsthat no asset loads on has exposure zero.- Raises:
ValueError – If factor covariance matrices or residual variances are unavailable, or the idiosyncratic label conflicts with a factor contribution column.
- Return type:
- compute_active_factor_risk(portfolio_weights, benchmark_weights)[source]¶
Compute factor-only active risk, excluding idiosyncratic risk.
This legacy method forms portfolio, benchmark, and active factor exposures, then multiplies active exposures by their factor-covariance marginal risks. It does not include an idiosyncratic term. Use
RiskModel.compute_tre_decomposition_at_datefor systematic/residual tracking error orRiskModel.compute_marginal_tre_at_datefor Euler tracking-error contributions.- Parameters:
- Returns:
Dictionary of portfolio, benchmark, and active factor exposures, marginal factor risks, absolute factor risk contributions, and normalized factor contributions.
- Warns:
DeprecationWarning – On every direct call; the method remains available in this release with its body unchanged.
- Return type: