qis.RiskModel¶
- class qis.RiskModel(covar, factor_loadings=None, factor_covar=None, residual_vars=None, factor_groups=None, factor_return_types=None)[source]¶
Bases:
objectDated covariance matrices with an optional point-in-time factor block.
The covariance at each date is authoritative for both the asset universe and total-risk computations. The optional factor block enables factor exposures and systematic/residual decompositions; it never replaces or rebuilds the supplied covariance.
Orientation:
factor_loadings[date]is assets by factors (B, rows the covariance assets), so exposures areB' w.LinearModelandEwmLinearModelstore loadings per factor as dates-by-assets frames andLinearModel.get_loadings_at_datereturns factors by assets; transpose such a snapshot before passing it here.An asset whose variance is NaN on a date, for example before its first return in
qis.estimate_rolling_ewma_covar, is unavailable on that date: its row and column may be NaN. Results that do not weight it ignore it; results that weight it are NaN, and its own benchmark-beta loading is NaN.- Variables:
covar (Dict[pandas.Timestamp, pandas.DataFrame]) – Covariance matrices by date, with matching asset index and columns.
factor_loadings (Dict[pandas.Timestamp, pandas.DataFrame] | None) – Optional asset-by-factor loading matrices by date.
factor_covar (Dict[pandas.Timestamp, pandas.DataFrame] | None) – Optional factor-by-factor covariance matrices by date.
residual_vars (Dict[pandas.Timestamp, pandas.Series] | None) – Optional asset residual variances (not volatilities) by date, one Series indexed by asset per date.
factor_groups (Dict[str, qis.portfolio.risk.factor_groups.FactorGroupSpec] | None) – Optional provider-neutral family membership and bump weights.
factor_return_types (Dict[str, qis.perfstats.config.ReturnTypes] | None) – Optional exact factor-to-ReturnTypes mapping. Omitted means legacy LOG. DIFFERENCE loadings are response log return per native point; factor covariance must use those same coordinates.
- Raises:
ValueError – If the covariance or factor data are incomplete, non-finite (outside the rows and columns of unavailable assets), misaligned, non-unique, non-square, non-symmetric, not positive semi-definite, or have negative residual variances, each beyond a rounding tolerance (
COVAR_PSD_TOLrelative to the matrix scale).- Parameters:
- __init__(covar, factor_loadings=None, factor_covar=None, residual_vars=None, factor_groups=None, factor_return_types=None)¶
- Parameters:
- Return type:
None
Methods
__init__(covar[, factor_loadings, ...])compute_benchmark_beta_at_date(...[, strict])Compute ex-ante portfolio beta to a weighted benchmark.
compute_benchmark_beta_history(...[, strict])Compute ex-ante benchmark beta on the covariance date grid.
Compute per-asset loadings to a weighted benchmark.
compute_exposures_at_date(portfolio_weights, ...)Compute factor exposures on one covariance date.
compute_exposures_history(portfolio_weights)Compute factor exposures on the covariance date grid.
Report family exposure sums separately from allocated bump sensitivities.
compute_marginal_tre_at_date(...[, ...])Compute canonical Euler marginal tracking-error contributions.
compute_tre_at_date(benchmark_weights, ...)Compute ex-ante tracking error on one covariance date.
compute_tre_by_group_loadings_at_date(...[, ...])Compute ex-ante tracking error for fractional or overlapping group loadings.
compute_tre_decomposition_at_date(...[, strict])Decompose tracking error into factor and residual components.
compute_tre_decomposition_history(...[, strict])Compute factor/residual tracking-error decomposition through time.
compute_tre_history(benchmark_weights, ...)Compute ex-ante tracking error on the covariance date grid.
Attributes
Sorted covariance date grid.
- factor_groups: Dict[str, FactorGroupSpec] | None = None¶
- factor_return_types: Dict[str, ReturnTypes] | None = None¶
- compute_factor_group_exposures_at_date(portfolio_weights, date, strict=True)[source]¶
Report family exposure sums separately from allocated bump sensitivities.
- Parameters:
- Returns:
Family-indexed table with exposure_sum and split_bump_exposure. The latter is a local derivative, not finite-scenario P&L. Both inherit the units of portfolio_weights.
- Return type:
- property dates: DatetimeIndex¶
Sorted covariance date grid.
- Returns:
Covariance dates in increasing order.
- compute_tre_at_date(benchmark_weights, portfolio_weights, date, group_data=None, total_column='Total', strict=True, *, lookthrough_matrix=None)[source]¶
Compute ex-ante tracking error on one covariance date.
For active weights
d = w_p - w_b, tracking error issqrt(d' Sigma d). When groups are requested, each group result zeroes active weights outside that group before applying the full covariance. These standalone sleeve risks are not additive and are not forced to sum to total tracking error. No annualisation is applied.- Parameters:
benchmark_weights (Series) – Benchmark weights indexed by asset.
portfolio_weights (Series) – Portfolio weights indexed by asset.
date (Timestamp) – Exact covariance-grid date.
group_data (Series | None) – Optional group label per asset. Missing labels become
'Unassigned'.total_column (str) – Label for total tracking error when groups are returned. Must differ from the aligned group labels, including
'Unassigned'.strict (bool) – If True, reject material weights outside the covariance universe.
lookthrough_matrix (DataFrame | None) – Optional strict static accounting partition; omitted rows use group_data. Does not alter generic group_loadings semantics.
- Returns:
Total tracking error as a float, or total and standalone group tracking errors as a Series.
- Raises:
KeyError – If
dateis not an exact covariance-grid date.ValueError – If weights or model data violate the alignment policy, or
total_columnduplicates an aligned group label.
- Return type:
- compute_tre_by_group_loadings_at_date(benchmark_weights, portfolio_weights, date, group_loadings, total_column='Total', strict=True)[source]¶
Compute ex-ante tracking error for fractional or overlapping group loadings.
For active weights
d = w_p - w_band an asset-by-group loading matrixL, groupghas standalone tracking errorsqrt((d * L_g)' Sigma (d * L_g)). Loadings may be fractional, overlapping, or signed and need not sum to one. Group tracking errors are not additive and are not forced to sum to total tracking error. Missing covariance-universe rows and loading NaNs become zero; extra loading rows are ignored. No annualisation is applied.- Parameters:
benchmark_weights (Series) – Benchmark weights indexed by asset.
portfolio_weights (Series) – Portfolio weights indexed by asset.
date (Timestamp) – Exact covariance-grid date.
group_loadings (DataFrame) – Asset-by-group loading matrix. Column order defines result order.
total_column (str) – Label for total tracking error.
strict (bool) – If True, reject material weights outside the covariance universe.
- Returns:
Series containing total and standalone group tracking errors.
- Raises:
KeyError – If
dateis not an exact covariance-grid date.ValueError – If weights or group loadings violate the alignment policy, loading labels are duplicated, values are nonnumeric or infinite, or
total_columnduplicates a group label.
- Return type:
- compute_tre_history(benchmark_weights, portfolio_weights, group_data=None, total_column='Total', strict=True, *, lookthrough_matrix=None)[source]¶
Compute ex-ante tracking error on the covariance date grid.
Dated weights are selected as-of each covariance date using forward fill; dates before the first weight observation receive zero weights. The mathematics and group convention are those of
compute_tre_at_date(). No annualisation is applied.- Parameters:
benchmark_weights (Series | DataFrame) – Static Series or dated DataFrame of benchmark weights.
portfolio_weights (Series | DataFrame) – Static Series or dated DataFrame of portfolio weights.
group_data (Series | None) – Optional group label per asset. Missing labels become
'Unassigned'.total_column (str) – Label for total tracking error when groups are returned. Must differ from the aligned group labels, including
'Unassigned'.strict (bool) – If True, reject material weights outside the covariance universe.
lookthrough_matrix (DataFrame | None) – Optional strict static accounting partition; omitted rows use group_data. Does not alter generic group_loadings semantics.
- Returns:
A Series named
'Tracking error', or a DataFrame containing total and standalone group tracking errors.- Raises:
ValueError – If weights or model data violate the alignment policy, or
total_columnduplicates an aligned group label.- Return type:
- compute_exposures_at_date(portfolio_weights, date, strict=True)[source]¶
Compute factor exposures on one covariance date.
Loadings
Bhave shape assets x factors and exposure isB' w. The construction-time alignment guarantee is retained: the method does not reindex or relax the loadings matrix.- Parameters:
- Returns:
Factor exposure Series indexed by factor.
- Raises:
KeyError – If
dateis not an exact covariance-grid date.ValueError – If
factor_loadingsis missing or weights violate the alignment policy.
- Return type:
- compute_exposures_history(portfolio_weights, strict=True)[source]¶
Compute factor exposures on the covariance date grid.
Dated weights are selected as-of each covariance date using forward fill; dates before the first weight observation receive zero weights. At every date the exposure is
B_t' w_tfor asset-by-factor loadingsB_t.- Parameters:
- Returns:
DataFrame with covariance dates as rows and factors as columns.
- Raises:
ValueError – If
factor_loadingsis missing or weights violate the alignment policy.- Return type:
- compute_benchmark_beta_at_date(benchmark_weights, portfolio_weights, date, strict=True)[source]¶
Compute ex-ante portfolio beta to a weighted benchmark.
For portfolio weights
w_p, benchmark weightsw_b, and covarianceSigma, beta is(w_p' Sigma w_b) / (w_b' Sigma w_b). The factor block is not required.- Parameters:
- Returns:
Scalar ex-ante portfolio beta to the benchmark.
- Raises:
KeyError – If
dateis not an exact covariance-grid date.ValueError – If weights violate the alignment policy or benchmark variance is nonpositive.
- Return type:
- compute_benchmark_beta_history(benchmark_weights, portfolio_weights, strict=True)[source]¶
Compute ex-ante benchmark beta on the covariance date grid.
Dated weights are selected as-of each covariance date using forward fill; dates before the first weight observation receive zero weights. At every date beta is
(w_p' Sigma w_b) / (w_b' Sigma w_b).- Parameters:
- Returns:
Series named
'Benchmark beta'on the covariance date grid. Dates with nonpositive benchmark variance contain NaN.- Raises:
ValueError – If weights violate the alignment policy.
- Warns:
UserWarning – If benchmark variance is nonpositive on one or more dates.
- Return type:
- compute_benchmark_beta_loadings_at_date(benchmark_weights, date, strict=True)[source]¶
Compute per-asset loadings to a weighted benchmark.
The loading vector is
c = Sigma w_b / (w_b' Sigma w_b), so the beta of any aligned portfolio is the linear formc' w_p. The factor block is not required.- Parameters:
- Returns:
Benchmark-beta loading Series indexed by covariance asset. An unavailable asset (NaN variance) has a NaN loading.
- Raises:
KeyError – If
dateis not an exact covariance-grid date.ValueError – If weights violate the alignment policy or benchmark variance is nonpositive.
- Return type:
- compute_tre_decomposition_at_date(benchmark_weights, portfolio_weights, date, strict=True)[source]¶
Decompose tracking error into factor and residual components.
For active weights
d = w_p - w_b, asset-by-factor loadingsB, factor covarianceSigma_x, and diagonal residual varianceD, the components areTE_f^2 = (B' d)' Sigma_x (B' d)andTE_r^2 = d' D d. The returned tracking error issqrt(TE_f^2 + TE_r^2). It equals covariance tracking error only when the supplied covariance satisfiesSigma = B Sigma_x B' + D; inconsistent views are not reconciled silently.- Parameters:
- Returns:
Series with
tracking_error,factor_te, andresidual_te.- Raises:
KeyError – If
dateis not an exact covariance-grid date.ValueError – If the factor block is missing or weights violate the alignment policy.
- Return type:
- compute_tre_decomposition_history(benchmark_weights, portfolio_weights, strict=True)[source]¶
Compute factor/residual tracking-error decomposition through time.
Dated weights are selected as-of each covariance date using forward fill. Each row uses the factor-block formulas documented by
compute_tre_decomposition_at_date(); no annualisation is applied.- Parameters:
- Returns:
DataFrame with
tracking_error,factor_te, andresidual_tecolumns.- Raises:
ValueError – If the factor block is missing or weights violate the alignment policy.
- Return type:
- compute_marginal_tre_at_date(benchmark_weights, portfolio_weights, date, group_data=None, strict=True, *, lookthrough_matrix=None)[source]¶
Compute canonical Euler marginal tracking-error contributions.
With active weights
d = w_p - w_bandTE = sqrt(d' Sigma d), each asset contribution ismcte_i = d_i (Sigma d)_i / TEand the contributions sum to TE. At TE equal to zero, all contributions are defined as zero.When a complete factor block is present, systematic and residual columns use
B Sigma_x B' dandD drespectively. They sum to total per asset whenSigma = B Sigma_x B' + D; inconsistent supplied views are shown without silent reconciliation. Group rows aggregate asset contributions additively and therefore differ from the standalone, non-additive group risks returned bycompute_tre_*.- Parameters:
benchmark_weights (Series) – Benchmark weights indexed by asset.
portfolio_weights (Series) – Portfolio weights indexed by asset.
date (Timestamp) – Exact covariance-grid date.
group_data (Series | None) – Optional group label per asset. Missing labels become
'Unassigned'.strict (bool) – If True, reject material weights outside the covariance universe.
lookthrough_matrix (DataFrame | None) – Optional strict static accounting partition; omitted rows use group_data. Does not alter generic group_loadings semantics.
- Returns:
Per-asset DataFrame, or a DataFrame with
Totaland group rows. Columnmcteis always present; a complete factor block addsmcte_systematicandmcte_residual. Unknown tracking error stays missing in every group andTotal.- Raises:
KeyError – If
dateis not an exact covariance-grid date.ValueError – If weights or model data violate the alignment policy, or an aligned group label is
'Total'.
- Return type: