qis.LinearModel

class qis.LinearModel(x, y, loadings=None, x_covars=None, residual_vars=None)[source]

Bases: object

A 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 asset i on factor q estimated at t.

  • 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)
Parameters:
Return type:

None

Methods

__init__(x, y[, loadings, x_covars, ...])

compute_active_factor_risk(...)

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_factor1_loadings()

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

x: DataFrame | Series
y: DataFrame | Series
loadings: Dict[str, DataFrame] = None
x_covars: Dict[Timestamp, DataFrame] | None = None
residual_vars: DataFrame | None = None
print()[source]

Print model components for debugging.

get_factor1_loadings()[source]

Get the dates-by-assets loadings of the first factor.

Return type:

DataFrame

get_factor_loadings(factor)[source]

Get the dates-by-assets loadings of a specific factor.

Parameters:

factor (str)

Return type:

DataFrame

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 that qis.RiskModel.factor_loadings holds.

Raises:

ValueError – If the model has no loadings.

Return type:

DataFrame

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 t of 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:

DataFrame

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:
Return type:

DataFrame

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 q at t is B[t-1, asset, q] * x[t, q].

Parameters:
  • asset (str) – Asset column; the first asset of y when None.

  • add_total (bool) – Prepend a Total column with the sum of the factor contributions.

Returns:

Contributions, dates by factors. Total is NaN on any date where a lagged loading or a factor return is missing, such as the warm-up rows.

Return type:

DataFrame

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 x before 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.x when None.

  • y (DataFrame | None) – Asset returns, dates by assets, on the same index as x; self.y when 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_ewm with this span.

Returns:

Tuple of (factor_alpha, explained_returns), both dates by assets.

Raises:

AssertionError – If the indexes of x and y differ.

Return type:

Tuple[DataFrame, DataFrame]

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]^2 with lambda = 1 - 2 / (span + 1), where e is the residual of get_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.fit runs by default. With the default lag=0 the loadings dated t explain the return dated t, which they were estimated from, so it is an in-sample fit; lag=1 gives the point-in-time, step-ahead R².

Parameters:
  • span (int) – EWM span of both second moments.

  • lag (Literal[0, 1]) – Loading lag passed to get_factor_alpha: 0 in sample, 1 point in time.

Returns:

R², dates by assets, NaN before the first finite residual.

Return type:

DataFrame

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_corr is 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 exposures x = B' w (B assets by factors), the systematic variance is x' F x and the residual variance sum_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_covars that 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:

Tuple[DataFrame, DataFrame, DataFrame, DataFrame]

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_date for systematic/residual tracking error or RiskModel.compute_marginal_tre_at_date for Euler tracking-error contributions.

Parameters:
  • portfolio_weights (DataFrame) – Dated portfolio weights by asset.

  • benchmark_weights (DataFrame) – Dated benchmark weights by asset.

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:

Dict[str, DataFrame]

plot_factor_loadings(factor, var_format='{:,.2f}', time_period=None, ax=None, **kwargs)[source]

Plot factor loadings time series.

Parameters:
Return type:

None