Model-layer attribution: risk-layer, signal-layer, and integration alpha¶
Author: Artur Sepp / First recorded: 2026-08-29
Implemented in qis — Quantitative Investment Strategies. Software citation: CITATION.cff.
Model-layer attribution decomposes a portfolio model’s log returns into benchmark exposure, risk-layer alpha, signal-layer alpha and an integration residual. In qis these components reconstruct every observed full-model return. Full-sample OLS and endpoint EWMA regressions also attach confidence intervals to alpha; a separate lagged-beta estimator measures realised alpha using beta information available before each return.
Overview¶
A layered allocation model combines a risk estimate, signals and an optimiser subject to constraints. Running the risk and signal layers separately produces useful counterfactuals, but their effects need not sum to the integrated result. The integration term records that difference on a stated benchmark basis. Annualised mean log-return contributions add exactly; they are not additive compounded returns.
The estimators are derived in Regression and HAC inference and Exponentially weighted estimators. This chapter adds the layer definitions, the exact return bridge, the contrasts between layers and feature runs, and the result objects.
Start with the exact return bridge, then choose full-sample inference, lagged realised alpha, or a current endpoint estimate. The worked example provides both arithmetic and seeded examples.
Choose the object that matches the question¶
Question |
Method and output |
|---|---|
What did each layer add over the full sample? |
OLS/HAC: alpha, beta, intervals and exact return components |
How did alpha accrue under previously estimated betas? |
Lagged EWMA: realised components and cumulative paths |
What is the current estimate with recency weights? |
Endpoint EWMA-WLS: weighted estimates and HAC intervals |
How did the current estimate evolve? |
Expanding-prefix fits: descriptive alpha history |
How much return per unit of risk did each component add? |
Common-denominator contributions: additive full-sample or EWMA ratios |
Which model changes explain the difference? |
Feature attribution: factorial and Shapley effects |
For a single strategy’s ex-post TE or IR, use tracking-error analytics.
For ex-ante active risk from a covariance model, use qis.RiskModel. Neither replaces the
counterfactual layer NAVs required here.
Inputs, notation, and assumptions¶
Convention |
This article |
|---|---|
Return basis |
Log returns of the supplied layer NAVs; no cash or risk-free return is subtracted |
Sampling grid |
|
Annualisation |
Linear, \(\mathrm{af}\,\hat\alpha\) and \(\mathrm{af}\) times mean components; Sharpe-contribution volatilities scale by \(\sqrt{\mathrm{af}}\); betas and \(R^2\) are not annualised |
Mean adjustment |
OLS and WLS fit an intercept; lagged betas use point-in-time EWMA means ( |
Timing |
Full-sample and endpoint fits are descriptive; lagged EWMA betas are applied |
Output units |
Annualised log-return contributions; dimensionless betas; periodic HAC standard errors |
qis default |
|
Symbol or input |
Meaning |
Units and convention |
|---|---|---|
\(V_{L,t}\) |
Positive NAV of layer \(L\) at \(t\) |
Common currency, dates and valuation basis |
\(B,R,S,F,F^{\mathrm{net}}\) |
Benchmark, risk layer, signal layer, gross and net full model |
Supplied NAVs; \(F^{\mathrm{net}}\) is optional |
\(I\), \(C\) |
Integration and trading-cost drag |
Return differences, not supplied NAVs |
\(\ell_{L,t}\) |
Log return of layer \(L\) over \((t-1,t]\) |
Decimal per period of |
\(\bar\ell_L\), \(\bar\ell^{\,\omega}_L\) |
Sample mean and \(\omega\)-weighted mean of \(\ell_{L,t}\) |
Per period |
\(\alpha_L,\beta_L,\varepsilon_{L,t}\) |
Intercept, benchmark slope and residual of layer \(L\) |
\(\alpha\) per period; \(\beta\) dimensionless |
\(a_{L,t}\) |
Alpha component of layer \(L\) in a return bridge |
Periodic log return |
\(\mathcal{A}_{L,t}\) |
Cumulative alpha component \(\sum_{t'\le t}a_{L,t'}\) |
Log-return points, not a wealth index |
\(\hat\beta_{L,t}\), \(b_{L,t}\), \(\beta_0\), \(h\) |
EWM beta after return \(t\); beta applied to return \(t\); prior; lag |
\(b_{L,t}=\hat\beta_{L,t-h}\) or \(\beta_0\); |
\(N,\lambda\) |
EWM span and decay, \(\lambda=1-2/(N+1)\) |
|
\(\mathcal{E}_t[z]\) |
EWM of a series \(z\) through \(t\), seeded at its first row |
Same span as the betas |
\(\omega_t\), \(T_{\mathrm{eff}}\) |
Geometric WLS weight \(\lambda^{T-1-t}\); Kish effective sample size |
Latest row has weight one |
\(T,\mathrm{af}\) |
Retained observations and periods per year |
|
\(q\), \(\gamma\), \(z_{\gamma}\) |
Bartlett lag count, confidence level, normal quantile \(\Phi^{-1}((1+\gamma)/2)\) |
|
\(\hat\Sigma_{\alpha}\), \(c\), \(x_t\) |
Joint HAC covariance of layer alphas; contrast vector; regressor row \((1,\ell_{B,t})^{\top}\) |
Ordered \((F,R,S)\) |
\(\hat\mu_K\), \(\pi_K\), \(\sigma_B\), \(\sigma_{F^{*}}\) |
Annualised mean of bridge component \(K\), its Sharpe contribution; benchmark and endpoint-model volatility |
\(K\in\{\mathrm{sys},R,S,I,C\}\); \(F^{*}\) is \(F^{\mathrm{net}}\) when supplied, else \(F\) |
\(\ell^{(0)}_{L,t}\), \(\ell^{(1)}_{L,t}\), \(\Delta_{L,t}\) |
Layer return without and with one feature; their difference |
Log return of a NAV ratio |
\(\mathcal{M}\), \(n\); \(\mathcal{C}\), \(\mathcal{D}\); \(\ell^{\mathcal{C}}_{L,t}\), \(d^{\mathcal{C}}_{L,t}\), \(\phi_{f,L,t}\) |
Feature set and its size; coalitions; coalition return, Harsanyi dividend, Shapley effect of feature \(f\) |
\(\varnothing\) is production; periodic log returns |
Frequency and annualisation must describe the NAVs supplied. Full-sample attribution defaults to quarter-end; the endpoint EWMA regression defaults to month-end. The examples explicitly choose month-end. A quarterly lag is not a monthly lag.
Inputs and the common sample¶
The inputs are four NAV series and an optional fifth:
The benchmark \(B\).
The risk-layer model \(R\) (the full model run with every alpha signal set to zero).
The signal layer \(S\) (a separately specified portfolio built from the signals alone).
The full model \(F\).
Optionally, the full model net of trading costs \(F^{\mathrm{net}}\).
Each layer \(L\) is converted at frequency freq to log returns,
The residual definition below makes the within-period bridge exact. Log returns additionally sum across time, so cumulative contributions and their annualised means reconcile on the same scale. This does not make the log return of an arbitrary portfolio a weighted sum of its sleeves’ log returns. Reported annualised means are not compounded annual growth rates; exponentiating each component separately destroys additivity.
The common valid NAV range is set before any resampling: the NAVs are trimmed between the latest
first valid observation and the earliest last valid observation, then converted to returns at
freq. A layer that starts later or ends earlier therefore shortens the range for every layer;
no layer contributes flat forward-filled returns outside its own history.
Filling follows the native price-sampling policy,
not an unconditional preprocessing step. If the input index’s inferred frequency exactly matches
freq, missing NAV levels are preserved. For example, with month-end input and freq='ME', an
isolated interior missing NAV leaves both adjacent monthly returns undefined rather than creating
a zero return and a catch-up return. Actual resampling forward-fills missing levels before and
after reindexing. Any date with a non-finite periodic return in any layer is dropped for all layers.
Definition (integration return and cost drag). The integration return is the log-return residual of the full model against the sum of the risk and signal layers run on their own, and the trading-cost drag is the difference between the net and gross full models,
Methodology¶
Full-sample OLS layer regressions¶
Definition (layer regression). For each layer \(L\in\{R,S,I,F,F^{\mathrm{net}}\}\),
qis.compute_model_layer_alpha_beta_attribution fits
by ordinary least squares with an intercept on the common sample, so \(\hat\alpha_L=\bar\ell_L-\hat\beta_L\bar\ell_B\). The integration return is regressed as a layer of its own. The benchmark row of the table is fixed at \(\hat\alpha_B=0\) and \(\hat\beta_B=1\) rather than estimated. Alpha is annualised linearly, \(\mathrm{af}\,\hat\alpha_L\), because a mean log return scales with the number of periods; beta, \(R^2\) and the periodic standard error are not annualised.
The exact return bridge¶
Definition (return bridge). The gross full-model return is separated into the systematic return \(\hat\beta_F\,\ell_{B,t}\) and three alpha components, risk \(a_{R,t}\), signal \(a_{S,t}\) and integration \(a_{I,t}\):
Identity (exact bridge). In every period,
Proof. The first equation rearranges the definition of \(a_{I,t}\); the second rearranges the definition of \(\ell_{C,t}\). \(\square\)
Three properties turn this bookkeeping into an estimator.
Linearity: the integration term is an estimated alpha¶
Proposition (integration coefficients). On the common sample,
Proof. All layer regressions share one design \([\mathbf{1},\ell_B]\), because they share the common sample, and OLS coefficients and residuals are linear in the response. Applied to \(\ell_I=\ell_F-\ell_R-\ell_S\) this gives the first two equations and \(\hat\varepsilon_I=\hat\varepsilon_F-\hat\varepsilon_R-\hat\varepsilon_S\). Substituting the bridge definitions gives \(a_{I,t}=\ell_{I,t}-(\hat\beta_F-\hat\beta_R-\hat\beta_S)\,\ell_{B,t}\), which is \(\ell_{I,t}-\hat\beta_I\,\ell_{B,t}=\hat\alpha_I+\hat\varepsilon_{I,t}\). \(\square\)
This is why the function regresses the integration return as an additional layer and reports its beta, alpha and interval on the same footing as the observed layers. The integration alpha is not an unexplained plug. It is the OLS alpha of the log-return series \(\ell_F-\ell_R-\ell_S\).
Bar heights are OLS alphas¶
Identity (bar heights). The annualised sample mean of each alpha component equals the annualised OLS alpha of its layer, and the four annualised components add to the annualised mean full-model return:
Proof. \(a_{L,t}=\hat\alpha_L+\hat\varepsilon_{L,t}\) for \(L\in\{R,S\}\) by the definition of the residual, and for \(L=I\) by the previous proposition. OLS residuals have zero sample mean when the regression includes an intercept, which gives the first equation. By linearity \(\hat\alpha_R+\hat\alpha_S+\hat\alpha_I=\hat\alpha_F=\bar\ell_F-\hat\beta_F\bar\ell_B\), which gives the second. \(\square\)
The return bridge and the regression table are therefore one object: the bars of a bridge chart are the annualised alphas, and the whiskers on them are the intervals of those same alphas.
Invariance to the excess-return basis¶
qis does not subtract a risk-free rate in this attribution. State whether the supplied NAVs represent funded total returns or an already specified excess-return strategy. The algebra below concerns subtracting the benchmark log return, not an arbitrary risk-free series. Those are different transformations; the latter need not leave regression alphas unchanged.
Proposition (benchmark-excess invariance). Replace the signal-layer return by its excess over the benchmark, \(\ell'_{S,t}=\ell_{S,t}-\ell_{B,t}\). Every alpha, residual, HAC standard error, confidence bound and p-value is unchanged, and two betas move, with their \(R^2\): \(\hat\beta'_S=\hat\beta_S-1\) and \(\hat\beta'_I=\hat\beta_I+1\). The same holds for the risk layer.
Proof. The benchmark regressed on itself has intercept 0, slope 1 and zero residuals. By linearity, subtracting \(\ell_B\) from a response subtracts 0 from its alpha, 1 from its beta and nothing from its residuals, and the integration response \(\ell_F-\ell_R-\ell'_S\) gains \(\ell_B\). The HAC covariance depends on the regressor and the residuals only. \(\square\)
Insight
The invariance settles how to read the integration beta. A fully invested signal layer carries a benchmark beta near one, as does the risk layer. Adding the two as total returns doubles the benchmark exposure, so the integration beta is near \(-1\) by construction, for example \(0.85-1.05-1.00=-1.20\). On the excess basis for the signal layer the same integration term has beta near \(-0.20\), with identical alphas and intervals. The integration term is a log-return residual, not a tradeable portfolio.
Additive cumulative alpha with fixed full-sample betas¶
The annualised alpha table answers how much each component contributed on average. The same
component_returns output also shows when the contribution accumulated.
Identity (additive cumulative alpha). Let \(\mathcal{A}_{L,t}=\sum_{t'=1}^{t}a_{L,t'}\) for \(L\in\{R,S,I\}\), and let the cumulative total model alpha be \(\mathcal{A}_{F,t}=\sum_{t'=1}^{t}\big(\ell_{F,t'}-\hat\beta_F\,\ell_{B,t'}\big)\). Then at every date
Proof. Sum the exact bridge over \(t'\le t\). \(\square\)
No new regression is run for this chart: the full-sample OLS betas behind Risk Layer Alpha,
Signal Layer Alpha and Integration Alpha stay fixed, and the chart cumulatively sums those
exact periodic components. The runnable workflow below produces percentage-point paths with an
explicit 0% origin one attribution period before the first return. The vertical axis is
cumulative log-return contribution, not a wealth index, and the paths are descriptive because
their betas are full-sample estimates; they are not point-in-time alpha forecasts.
Pitfall
Do not plot 100 * exp(cumsum(alpha)) for an additive alpha-attribution chart.
That construction is a compounded pseudo-NAV: its components reconcile multiplicatively,
whereas the alpha bridge is defined and interpreted additively.
Lagged no-look-ahead EWMA-beta realised and cumulative alpha¶
Use the rolling estimator when the question is how alpha accumulated under betas that were available before each realised return.
Here those betas are estimated from each layer NAV, not from current instrument holdings. The following prior and example warm-up are specific to this model-layer API; for the factsheet’s span-length warm-up without a beta prior, see the holdings comparison.
Definition (lagged realised components). For \(L\in\{R,S,F\}\), let \(\hat\beta_{L,t}\) be the
EWM beta of \(\ell_L\) on \(\ell_B\) after observing return \(t\), with span \(N\) (beta_span, default
36), and let \(b_{L,t}=\hat\beta_{L,t-h}\) be the beta applied to return \(t\), with lag \(h\)
(beta_lag, default 1) and the prior \(\beta_0\) (beta_init_value, default 1) substituted while
that estimate is missing. The realised components are
and with a net NAV the net total alpha is \(a_{F,t}+\ell_{C,t}\), on the unchanged gross-model beta.
Identity (lagged bridge). In every period \(\ell_{F,t}=b_{F,t}\,\ell_{B,t}+a_{R,t}+a_{S,t}+a_{I,t}\), and \(b_{L,t}\) uses returns up to \(t-h\) only.
Proof. The first statement rearranges the definitions of \(a_{F,t}\) and \(a_{I,t}\). The second holds because \(\hat\beta_{L,t-h}\) comes from EWM recursions over rows up to \(t-h\) with point-in-time seeds and centring, and \(\beta_0\) is a constant. \(\square\)
Thus return \(t\) may update \(\hat\beta_{L,t}\), but it cannot change the beta applied to itself.
The betas are those of qis.compute_ewm_beta_alpha_forecast with
mean_adj_type=MeanAdjType.EWMA and init_type=InitType.X0: ratios of EWM moments about
point-in-time EWMA means of the same span, derived in
point-in-time EWM regressions and
mean adjustment. MeanAdjType.INSAMPLE is rejected because
a full-sample mean looks ahead. Under the X0 seed the first centred return is zero, so the first
estimated beta is deliberately missing; a missing estimate after the first finite one raises.
Pitfall
The prior is more than a fallback. It replaces the first informative observation
and seeds both moment recursions, so the first finite
estimate equals \(\beta_0\) exactly and the prior is the whole state of both moments on that
date. It keeps weight \(\lambda^{k}\) in the estimate \(k\) returns later, as much as
\((N+1)/2=18.5\) ordinary returns of its date and above 5% for about \(1.5N=54\) returns at \(N=36\),
so early realised alpha depends on beta_init_value.
The expanding annualised estimate through \(t\) is \(\mathrm{af}\,t^{-1}\sum_{t'\le t}a_{L,t'}\). The
post-warm-up exhibit is the unannualised cumulative sum of \(a_{L,t'}\) after a chosen base date,
with an explicit zero row on that date; with a one-period lag qis checks that the first accrued
return uses the beta available on the base date. The current estimate is
\(\mathrm{af}\,\mathcal{E}_t[a_L]\), the same-span
EWM of the step-ahead residuals seeded with
InitType.X0. It is a point-in-time EWMA of realised
out-of-sample alpha, not the contemporaneous EWM alpha of the lower-level beta routine and
not a refitted 36-observation regression, and linearity keeps it additive across layers. It is a
point estimate, not a confidence interval, and its
effective sample size is
the span.
estimated_betas records estimates after each return; applied_betas records the betas actually
used for each return, which is the audit for the lag. The runnable workflow below uses a 36-month
EWMA beta, lags it by one month, allows 12 monthly returns for estimator warm-up, and accumulates
realised alpha from the next month.
Current endpoint geometric EWMA-WLS regression¶
Use compute_model_layer_ewma_regression_attribution when the question is the current
recency-weighted decomposition rather than a historical sequence of investable beta estimates.
This is an endpoint descriptive regression: every return in the sample is used to estimate the
single alpha and beta shown at the final date. It must therefore not be substituted for the
lagged-beta realised attribution above.
Definition (endpoint EWMA-WLS attribution). On common-sample log returns (monthly at the
default freq='ME'), qis constructs \(\ell_I=\ell_F-\ell_R-\ell_S\) and fits
\(\ell_{L,t}=\alpha_L+\beta_L\,\ell_{B,t}+\varepsilon_{L,t}\) for \(L\in\{R,S,I,F\}\), and
\(F^{\mathrm{net}}\) when supplied, jointly with qis.estimate_ewma_alpha_beta_hac: weighted least
squares with the common weights \(\omega_t=\lambda^{T-1-t}\) on returns \(t=0,\ldots,T-1\) from oldest
to newest, so that the latest has weight one, and a stacked-score Bartlett HAC covariance.
The normal equations, the weighted \(R^2\), the statsmodels \(T/(T-2)\) correction and the Kish (1965)
effective sample size \(T_{\mathrm{eff}}=N(1-\lambda^{T})/(1+\lambda^{T})\) are derived in
weighted least squares with geometric weights.
At \(N=36\), \(\lambda=35/37\simeq0.9459\), and the 240 monthly returns of the simulated example give
effective_nobs 35.9999. A value displayed as 36.0 does not mean a hard 36-month window, since all
\(T\) returns enter, and it is not the degrees of freedom of the correction. Three layer-specific
properties follow.
Integration is a contrast. With fixed weights the linearity argument above carries over, and the integration-variance proposition holds with weighted scores. Fitting the precomputed integration response is algebraically equivalent to the contrast but avoids cancellation when the component equations are nearly collinear or returns use very small units.
Bars are the WLS alphas. The WLS normal equations with an intercept give \(\sum_t\omega_t\hat\varepsilon_{L,t}=0\), so the \(\omega\)-weighted mean of each alpha component is its WLS alpha, exactly the midpoint of its own confidence interval up to rounding.
The covariances are stored.
annualised_alpha_covarianceholds the \(\mathrm{af}^2\)-scaled joint covariance of the risk, signal and integration alphas, andparameter_covariancethe periodic alpha and beta covariance of the directly observed layers.
The endpoint return bridge remains exact in every period: systematic return is
\(\hat\beta_F\,\ell_{B,t}\), risk and signal contributions are their beta-adjusted returns, and
integration is the residual required to reconstruct \(\ell_{F,t}\). Its displayed annualised bars are
\(\omega\)-weighted means of those periodic log-return components. Supplying full_model_net_nav
adds the realised trading-cost drag and a net endpoint; it does not estimate a fee inside qis.
The final endpoint bar makes that regression identity visible. It starts with gross-model
systematic return \(\mathrm{af}\,\hat\beta_F\bar\ell^{\,\omega}_B\), applies realised trading-cost
drag when a net NAV is present, and then adds gross total alpha \(\mathrm{af}\,\hat\alpha_F\). The
label above the bar is gross return without a net NAV and net return with one. The black
gross-alpha interval is translated by the systematic and cost segments, so its midpoint is the
displayed endpoint. The beta and \(R^2\) rows under this bar therefore come from the gross
Full Model regression, as do its alpha and interval. The risk, signal and integration alpha
bars also show their own regression \(R^2\) below beta. The standalone Systematic bar uses that same
gross Full Model regression \(R^2\): it reports the fit of the observed full model to the
benchmark, not the tautological \(R^2=1\) obtained by regressing the constructed series
\(\hat\beta_F\,\ell_B\) back on \(\ell_B\).
An EWMA interval is not guaranteed to be narrower than its full-sample OLS/HAC counterpart. Recency weighting usually reduces effective information, and the weighted residual variance, serial dependence and cross-equation covariance can all change. EWMA answers a different question more responsively; it is not a mechanical confidence-band shrinkage method.
Rolling descriptive EWMA-WLS alpha¶
compute_model_layer_rolling_ewma_regression_alpha repeats the same geometric EWMA-WLS fit on
every expanding prefix for which the joint regression is nonsingular. At date \(t\), it uses only
returns through \(t\), with weights \(\omega_{t',t}=\lambda^{t-t'}\) for \(t'\le t\). It returns
annualised Total Model Alpha, Risk Layer Alpha, Signal Layer Alpha, and Integration Alpha, plus
Total Model Net Alpha when the supplied attribution has a net NAV. Linearity gives
at every plotted date. Its final gross row is checked directly against the Full Model,
Risk Layer, Signal Layer, and Integration rows of the current regression table. This path is
descriptive and contemporaneous: unlike lagged-beta realised attribution, return \(t\) participates
in the regression displayed at \(t\). Accordingly, the generic qis plot title calls this an
annualised model-layer alpha path, not an out-of-sample alpha estimate.
plot_model_layer_rolling_ewma_regression_alpha(..., start_date=...) still estimates every
expanding prefix from the complete history and only then clips the displayed path. Its avg and
last legend statistics therefore describe the displayed date range without resetting EWMA state.
Common-denominator EWMA Sharpe contributions¶
Definition (common-denominator contributions).
compute_model_layer_ewma_sharpe_contributions divides the annualised means \(\hat\mu_K\) of the
current EWMA return bridge by one common endpoint-model volatility,
\(\pi_K=\hat\mu_K/\sigma_{F^{*}}\), and the benchmark reference by benchmark volatility,
\(\mathrm{SR}_B=\hat\mu_B/\sigma_B\). Here \(K\) runs over the systematic return, the risk, signal
and integration alphas and the optional cost drag \(C\), and \(F^{*}\) is the net model when supplied
and the gross model otherwise.
Identity (additive Sharpe bridge). \(\sum_K\pi_K=\hat\mu_{F^{*}}/\sigma_{F^{*}}=\mathrm{SR}_{F^{*}}\), and each alpha contribution has the sign of its alpha.
Proof. By the exact bridge the numerators add to \(\hat\mu_{F^{*}}\), and every model term has the same positive denominator. \(\square\)
These are contribution ratios, not standalone sleeve Sharpes. Both volatilities are the final row
of qis.compute_ewm_vol with the attribution span, MeanAdjType.EWMA and InitType.ZERO,
annualised by \(\sqrt{\mathrm{af}}\) (EWM volatility).
For IID returns EWMA centring makes them about 4% low at \(N=36\)
(mean adjustment), which raises every ratio alike and leaves
additivity intact.
The older compute_model_layer_ewma_stage_sharpes remains available as a separate diagnostic. It
computes the EWMA Sharpe path after adding risk, signal and integration returns sequentially. Its
deltas are order-dependent: a positive signal alpha can produce a negative stage-Sharpe increment
when it adds enough volatility or covariance. The public bridge plot uses the additive
common-denominator measure instead.
compute_model_layer_in_sample_sharpe_contributions uses the identical two-denominator
construction with the exact full-sample alpha-attribution numerators and full-sample annualised
log-return volatilities, \(\sigma=\sqrt{\mathrm{af}}\,s(\ell)\). It therefore reports full-history
realised return per unit of full-history realised risk, with no EWMA window in either numerator or
denominator. The endpoint bar in both public Sharpe plots is split into systematic, optional
realised cost, and combined alpha contributions.
The return and Sharpe bridges use the final endpoint, while the rolling-alpha figure shows every
displayed estimable prefix. The return-bridge, rolling-alpha, EWMA-Sharpe and in-sample-Sharpe
plot functions accept detailed_mode=False for a clean export without title, subtitle or
methodology footnote.
Full-sample OLS/HAC inference¶
Alpha inference in compute_model_layer_alpha_beta_attribution uses the Bartlett HAC covariance
of HAC covariance of the OLS coefficients:
\(q\) lags (hac_lags, default 3, capped at \(T-1\)), the statsmodels use_correction=True factor
\(T/(T-2)\), a normal reference distribution, and a two-sided interval at level \(\gamma\)
(confidence_level, default 0.95). Each layer, integration included, is its own regression; the
table reports the periodic \(\mathrm{se}(\hat\alpha_L)\) as Alpha HAC SE, the two-sided normal
p-value, and the annualised interval
with \(z_{\gamma}=1.960\) at the default level. The estimator is the internal
qis.utils.regression.estimate_ols_alpha_beta_hac, which src/qis/utils/tests/regression_test.py
checks against a hand-rolled Newey and West matrix calculation. The default of three lags is
fixed for any frequency; the internal qis.utils.regression.newey_west_lag_rule(nobs) returns the
rule of thumb associated with Newey and West (1994), four for the 240 monthly returns of the
simulated example. The result records freq, hac_lags and confidence_level, so a table or a
footnote can quote the settings that produced it.
Proposition (integration variance). Let \(\hat\Sigma_{\alpha}\) be the joint HAC covariance of \((\hat\alpha_F,\hat\alpha_R,\hat\alpha_S)\) built from the stacked scores with the same kernel and correction. The HAC variance of \(\hat\alpha_I\) from its own regression is
and the same holds for the endpoint EWMA-WLS fit with weighted scores.
Proof. By the integration-coefficients proposition the integration scores \(x_t\hat\varepsilon_{I,t}\), with \(x_t=(1,\ell_{B,t})^{\top}\), are the combination \(c\) of the three layer scores. The HAC estimator is a quadratic form in the scores with a shared bread and correction, so this is the variance of a linear contrast with unit weights for OLS. \(\square\)
A wide integration interval is a statement about the joint estimation error of three layers, not
a computational artefact; adding three marginal variances instead would ignore the cross-layer
covariances. The three intervals on a bridge chart are marginal intervals. They are not
independent, and their widths do not add. The interval of the total alpha
\(\mathrm{af}\,\hat\alpha_F\) is the Full Model row of the table.
The kernel follows Newey and West (1987); the correction and lag-rule convention follow the statsmodels HAC implementation.
Measuring the impact of a model feature¶
The same bridge isolates the effect of one model feature on the risk side and on the signal side. With superscripts \((0)\) and \((1)\) for the model without and with the feature, the feature return of layer \(L\in\{R,S,F\}\) is \(\Delta_{L,t}=\ell^{(1)}_{L,t}-\ell^{(0)}_{L,t}\), the log return of the NAV ratio \(V^{(1)}_{L,t}/V^{(0)}_{L,t}\).
Proposition (feature decomposition). On a common sample, regressing \(\Delta_L\) on the benchmark gives \(\hat\alpha_{\Delta L}=\hat\alpha^{(1)}_L-\hat\alpha^{(0)}_L\) and \(\hat\beta_{\Delta L}=\hat\beta^{(1)}_L-\hat\beta^{(0)}_L\), with the HAC interval of the difference from a single regression, and the feature’s total effect decomposes exactly into a risk-side, a signal-side and an integration effect,
Proof. Linearity in the response on one design gives the differences of coefficients. The decomposition is the integration-coefficients proposition applied to the responses \(\Delta_R\), \(\Delta_S\) and \(\Delta_F\). \(\square\)
In code this is one call with the benchmark NAV and the three ratio NAVs in place of the layer
NAVs; the Integration row then gives \(\hat\alpha_{\Delta I}\). Two conditions apply. The two
models of each layer must share the same date index, because a date missing from one NAV makes the
ratio missing there and the forward fill then replaces a return difference by a level jump. And
the identity between the ratio regression and the difference of two separate attributions holds
only when both land on the same common sample. A feature that changes only the covariance
estimator has \(\Delta_{S,t}\equiv0\), and its effect is read from the risk and integration rows. A
feature that changes only a signal has \(\Delta_{R,t}\equiv0\).
Pitfall
Subtracting two regression tables is not a substitute for the ratio regression: the standard-error and interval columns of a table difference have no meaning, because the standard error of a difference is not a difference of standard errors.
Alpha/beta attribution by multiple model features¶
qis.compute_model_feature_alpha_beta_attribution extends the single-feature ratio analysis to a
complete factorial experiment. A scenario is keyed by the frozenset of features enabled in that
run; the empty coalition is the production baseline. For \(n\) features, all \(2^n\) coalitions must be
supplied, and every coalition must use the same benchmark path. The scenario NAVs are aligned on
the intersection of their dates, without forward filling, and rebased to one; a benchmark that
differs by more than \(10^{-10}\) between coalitions raises.
Definition (factorial and Shapley effects). Let \(\mathcal{M}\) be the set of the \(n\) features and \(\ell^{\mathcal{C}}_{L,t}\) the log return of layer \(L\) in the run with coalition \(\mathcal{C}\subseteq\mathcal{M}\) enabled, \(\ell^{\varnothing}_{L,t}\) being production. For a non-empty \(\mathcal{C}\) the Harsanyi dividend is the factorial effect, and for a feature \(f\) the Shapley value is its order-free feature effect:
Singleton dividends are direct effects and larger coalitions interactions. qis forms each effect as a product of scenario NAVs raised to these coefficients, so its log return is the stated combination at every observation.
Proposition (reconstruction of the joint effect). At every date,
Proof. The dividends are the Möbius transform of \(\mathcal{C}\mapsto\ell^{\mathcal{C}}_{L,t}\), whose inverse gives \(\ell^{\mathcal{M}}_{L,t}=\sum_{\mathcal{C}\subseteq\mathcal{M}}d^{\mathcal{C}}_{L,t}\) with \(d^{\varnothing}_{L,t}=\ell^{\varnothing}_{L,t}\). The Shapley value splits each dividend equally among the members of its coalition, \(\phi_{f,L,t}=\sum_{\mathcal{C}\ni f}d^{\mathcal{C}}_{L,t}/\lvert\mathcal{C}\rvert\), so the Shapley effects sum to the same total, the efficiency property of Shapley (1952). \(\square\)
For two features \(f\) and \(g\) the dividend representation gives \(\phi_{f,L,t}=d^{\{f\}}_{L,t}+\tfrac12\,d^{\{f,g\}}_{L,t}\), the average of the feature’s effect without and with the other feature: each feature receives half of the interaction.
Each Shapley path is passed to compute_model_layer_alpha_beta_attribution; its alpha, beta and
HAC interval are therefore estimated from one effect-return series rather than by subtracting two
regression tables, and by the feature-decomposition proposition its total alpha splits exactly
into risk, signal and integration effects. The return rows of the summary have no regressor; their
intervals are Bartlett HAC intervals of a mean with the \(T/(T-1)\) correction (the internal
qis.utils.regression.estimate_hac_mean, a special case in
HAC covariance).
When net full-model NAVs are supplied, they must be present in every coalition. The summary then includes both gross and net total-return intervals and the net-model regression. Scenario construction remains outside qis: the caller decides what enabling a feature means and supplies the resulting NAVs. Interactions are calculated for the supplied experiment.
Worked example¶
A four-month arithmetic example¶
Let benchmark log returns be −2%, 1%, 3% and 0%, with risk-layer alpha 0.1% and beta 1.1, signal-layer alpha 0.2% and beta 0.9, and full-model alpha 0.25% and beta 0.8 each month. There is no noise in this arithmetic example. Integration alpha is −0.05% per month and integration beta is −1.2. Multiplying means by 12 gives these log-return contributions.
Component |
Annualised mean log return |
|---|---|
Systematic |
4.8% |
Risk-layer alpha |
1.2% |
Signal-layer alpha |
2.4% |
Integration alpha |
−0.6% |
Full model |
7.8% |
These are decomposition checks, not estimated investment opportunities. The exact linear data give essentially zero residual uncertainty and cannot illustrate realistic confidence intervals.
import numpy as np
import pandas as pd
import qis
dates = pd.date_range('2024-01-31', periods=5, freq='ME')
benchmark = np.array([-0.02, 0.01, 0.03, 0.00])
def nav(log_returns):
return pd.Series(np.exp(np.r_[0.0, np.cumsum(log_returns)]), index=dates)
attribution = qis.compute_model_layer_alpha_beta_attribution(
benchmark_nav=nav(benchmark),
risk_layer_nav=nav(0.001 + 1.1 * benchmark),
signal_layer_nav=nav(0.002 + 0.9 * benchmark),
full_model_nav=nav(0.0025 + 0.8 * benchmark),
freq='ME',
hac_lags=0,
)
components = ['Systematic Return', 'Risk Layer Alpha',
'Signal Layer Alpha', 'Integration Alpha']
np.testing.assert_allclose(
attribution.annualised_components.loc[components],
[0.048, 0.012, 0.024, -0.006], atol=1e-12,
)
np.testing.assert_allclose(
attribution.component_returns[components].sum(axis=1),
attribution.periodic_returns['Full Model'], atol=1e-12,
)
assert np.isclose(attribution.annualised_components['Full Model Return'], 0.078)
Runnable layer and feature workflow¶
From a checkout, this block uses the canonical teaching simulation below. It creates every input it needs and uses monthly log returns throughout. The fixed-beta, lagged-beta and endpoint estimates answer different questions; their alpha values need not match.
import numpy as np
import pandas as pd
import qis
from examples.portfolios.model_layer_attribution_simulated import (
simulate_layer_navs, simulate_feature_scenarios,
)
navs = simulate_layer_navs(seed=169)
full_sample_attribution = qis.compute_model_layer_alpha_beta_attribution(
**navs, freq='ME', hac_lags=3, confidence_level=0.95,
)
alpha_columns = ['Risk Layer Alpha', 'Signal Layer Alpha', 'Integration Alpha']
alpha_paths = full_sample_attribution.component_returns[alpha_columns].cumsum().mul(100)
alpha_paths.insert(0, 'Total model alpha', alpha_paths.sum(axis=1))
origin = alpha_paths.index[0] - pd.tseries.frequencies.to_offset('ME')
alpha_paths = pd.concat([
pd.DataFrame(0.0, index=[origin], columns=alpha_paths.columns), alpha_paths,
])
rolling = qis.compute_model_layer_ewma_alpha_attribution(
**navs, freq='ME', beta_span=36, beta_lag=1, beta_init_value=1.0,
mean_adj_type=qis.MeanAdjType.EWMA,
)
post_warmup = qis.compute_model_layer_cumulative_alpha_after_warmup(
attribution=rolling, base_date=rolling.periodic_returns.index[11],
warmup_periods=12,
)
current_ewma_alpha = rolling.current_ewma_annualised_alpha
current = qis.compute_model_layer_ewma_regression_attribution(
**navs, freq='ME', span=36, hac_lags=3, confidence_level=0.95,
)
rolling_alpha = qis.compute_model_layer_rolling_ewma_regression_alpha(current)
sharpe_contributions = qis.compute_model_layer_ewma_sharpe_contributions(current)
in_sample_sharpe_contributions = qis.compute_model_layer_in_sample_sharpe_contributions(
attribution=full_sample_attribution,
)
np.testing.assert_allclose(
rolling.component_returns[alpha_columns].sum(axis=1),
rolling.component_returns['Total Model Alpha'], atol=1e-12,
)
np.testing.assert_allclose(
rolling.applied_betas.to_numpy(),
rolling.estimated_betas.shift(1).fillna(1.0).to_numpy(), atol=1e-12,
)
scenarios = simulate_feature_scenarios(navs, seed=170)
decomposition = qis.compute_model_feature_alpha_beta_attribution(
scenario_layer_navs=scenarios, freq='ME', hac_lags=3,
)
feature_table = decomposition.summary.loc['Shapley']
risk_span = decomposition.feature_attributions['beta_span']
pair_interaction = decomposition.factorial_effect_attributions[
frozenset({'beta_span', 'signal_horizon'})
]
risk_span_alpha_paths = risk_span.component_returns[alpha_columns].cumsum().mul(100)
risk_span_alpha_paths.insert(0, 'Total feature alpha', risk_span_alpha_paths.sum(axis=1))
assert np.max(np.abs(decomposition.identity_errors.to_numpy())) < 1e-10
Simulated example¶
The example below simulates 240 monthly log returns for a benchmark (6% mean, 10% volatility), a risk layer (beta 1.05, alpha 1% per year), a signal layer (beta 1.00, alpha 3% per year) and a full model that runs at beta 0.85, keeps all of the risk-layer alpha and 60% of the signal-layer alpha, and carries its own residual. Residuals are AR(1) with autocorrelation 0.3, so the HAC intervals differ from OLS intervals. By construction the population integration alpha is \(-0.4 \times 3\% = -1.2\%\) per year: the constrained model gives up 40% of the signal-layer alpha. The fixed seed is 169, with 170 for the feature experiment. NAVs start on 2005-12-31; the 240 month-end returns cover January 2006 through December 2025. The seed is a teaching choice whose realised values are close to the design values; it is not a random model-selection study. Residual volatility parameters scale AR(1) innovations, not unconditional residual volatility. The script uses core qis dependencies and no data service.
Ordinary source: model_layer_attribution_simulated.py. Run this plotting script from a C-local source export on the maintainer’s host:
python -m examples.portfolios.model_layer_attribution_simulated
1"""Illustrate model-layer attribution on a simulated four-layer model, offline and seeded.
2
3The simulation builds monthly log returns for a benchmark ``B``, a risk layer ``R`` (beta 1.05,
4alpha 1% per year), a signal layer ``S`` (beta 1.00, alpha 3% per year), and a full
5model ``F`` that runs at beta 0.85, keeps all of the risk-layer alpha and 60% of the signal-layer
6alpha, and carries its own residual. A net NAV subtracts a proportional trading cost. Residuals
7are AR(1) so that the Bartlett HAC intervals differ from OLS intervals.
8
9The example prints the regression table and the annualised components, checks the three
10identities of the method (linearity of the integration coefficients, bar heights equal to OLS
11alphas, invariance of alphas and intervals to an excess-return definition of the signal layer),
12reports how the interval half-widths move when the lag count follows the Newey-West rule
13instead of the default three, and draws three exhibits: the return bridge, additive cumulative
14alpha, and a controlled two-feature Shapley sensitivity analysis with 95% HAC(3) intervals.
15
16Run from the repository root: ``python -m examples.portfolios.model_layer_attribution_simulated``.
17"""
18# packages
19import numpy as np
20import pandas as pd
21import matplotlib.pyplot as plt
22from matplotlib.ticker import PercentFormatter
23from pathlib import Path
24from enum import Enum
25from typing import Optional
26# qis
27import qis
28from qis.portfolio.attribution.model_layer import (
29 ALPHA_AN_CI_LOW_COLUMN,
30 ALPHA_AN_CI_HIGH_COLUMN,
31 ALPHA_HAC_SE_COLUMN,
32)
33from qis.utils.regression import newey_west_lag_rule
34
35FREQ = 'ME'
36PERIODS_PER_YEAR = 12.0
37START, END = '2005-12-31', '2025-12-31' # 240 monthly log returns
38SEED = 169
39
40BENCHMARK_MEAN, BENCHMARK_VOL = 0.06, 0.10 # per year
41RISK_ALPHA, RISK_BETA, RISK_RESIDUAL_VOL = 0.01, 1.05, 0.02 # per year
42SIGNAL_ALPHA, SIGNAL_BETA, SIGNAL_RESIDUAL_VOL = 0.03, 1.00, 0.04 # per year
43FULL_BETA, FULL_RISK_SHARE, FULL_SIGNAL_SHARE, FULL_RESIDUAL_VOL = 0.85, 1.0, 0.6, 0.02
44RESIDUAL_AR1 = 0.3
45TRADING_COST = 0.0015 # per year, proportional drag on the net NAV
46
47BETA_SPAN_FEATURE = 'beta_span'
48SIGNAL_HORIZON_FEATURE = 'signal_horizon'
49FEATURE_LABELS = {
50 BETA_SPAN_FEATURE: 'Beta-estimation span x2',
51 SIGNAL_HORIZON_FEATURE: 'Signal horizon x2',
52}
53REPORT_BACKGROUND = '#F7F5EF'
54REPORT_TEXT = '#23313B'
55REPORT_GRID = '#D8D4CB'
56TOTAL_ALPHA_COLOR = '#126B52'
57RISK_ALPHA_COLOR = '#5B9A91'
58SIGNAL_ALPHA_COLOR = '#D99D1E'
59INTEGRATION_ALPHA_COLOR = '#8A6F3D'
60FEATURE_COLORS = {
61 BETA_SPAN_FEATURE: '#3B5F7A',
62 SIGNAL_HORIZON_FEATURE: SIGNAL_ALPHA_COLOR,
63}
64
65
66def simulate_ar1(n_periods: int, rho: float, sigma: float, rng: np.random.Generator) -> np.ndarray:
67 """Return an AR(1) series with autocorrelation ``rho`` and innovation volatility ``sigma``."""
68 innovations = sigma * rng.standard_normal(n_periods)
69 series = np.zeros(n_periods)
70 for t in range(1, n_periods):
71 series[t] = rho * series[t - 1] + innovations[t]
72 return series
73
74
75def simulate_layer_navs(seed: int = SEED) -> dict[str, pd.Series]:
76 """Simulate monthly log returns of the four layers and the net model, and return their NAVs."""
77 rng = np.random.default_rng(seed)
78 dates = pd.date_range(START, END, freq=FREQ)
79 n_periods = len(dates) - 1
80 monthly_vol = 1.0 / np.sqrt(PERIODS_PER_YEAR)
81 r_b = (
82 BENCHMARK_MEAN / PERIODS_PER_YEAR
83 + BENCHMARK_VOL * monthly_vol * rng.standard_normal(n_periods)
84 )
85 risk_residual = simulate_ar1(n_periods, RESIDUAL_AR1, RISK_RESIDUAL_VOL * monthly_vol, rng)
86 signal_residual = simulate_ar1(n_periods, RESIDUAL_AR1, SIGNAL_RESIDUAL_VOL * monthly_vol, rng)
87 full_residual = simulate_ar1(n_periods, RESIDUAL_AR1, FULL_RESIDUAL_VOL * monthly_vol, rng)
88 r_r = RISK_ALPHA / PERIODS_PER_YEAR + RISK_BETA * r_b + risk_residual
89 r_s = SIGNAL_ALPHA / PERIODS_PER_YEAR + SIGNAL_BETA * r_b + signal_residual
90 r_f = (FULL_BETA * r_b
91 + FULL_RISK_SHARE * (r_r - RISK_BETA * r_b)
92 + FULL_SIGNAL_SHARE * (r_s - SIGNAL_BETA * r_b)
93 + full_residual)
94 r_f_net = r_f - TRADING_COST / PERIODS_PER_YEAR
95
96 def to_nav(log_returns: np.ndarray, name: str) -> pd.Series:
97 return pd.Series(
98 np.exp(np.concatenate([[0.0], np.cumsum(log_returns)])),
99 index=dates,
100 name=name,
101 )
102
103 return dict(benchmark_nav=to_nav(r_b, 'Benchmark'),
104 risk_layer_nav=to_nav(r_r, 'Risk Layer'),
105 signal_layer_nav=to_nav(r_s, 'Signal Layer'),
106 full_model_nav=to_nav(r_f, 'Full Model'),
107 full_model_net_nav=to_nav(r_f_net, 'Full Model Net'))
108
109
110def _orthogonal_feature_return(
111 annual_mean: float,
112 annual_vol: float,
113 benchmark_returns: np.ndarray,
114 rng: np.random.Generator,
115) -> np.ndarray:
116 """Simulate a centred AR(1) feature effect orthogonal to the benchmark in sample."""
117 residual = simulate_ar1(
118 n_periods=len(benchmark_returns),
119 rho=RESIDUAL_AR1,
120 sigma=annual_vol / np.sqrt(PERIODS_PER_YEAR),
121 rng=rng,
122 )
123 residual = residual - residual.mean()
124 benchmark_centred = benchmark_returns - benchmark_returns.mean()
125 projection = np.dot(residual, benchmark_centred) / np.dot(
126 benchmark_centred,
127 benchmark_centred,
128 )
129 residual = residual - projection * benchmark_centred
130 return annual_mean / PERIODS_PER_YEAR + residual
131
132
133def simulate_feature_scenarios(
134 navs: dict[str, pd.Series],
135 seed: int = SEED + 1,
136) -> dict[frozenset[str], qis.ModelLayerNavs]:
137 """Create the complete two-feature experiment used by the Shapley illustration."""
138 rng = np.random.default_rng(seed)
139 dates = navs['benchmark_nav'].index
140 layer_fields = (
141 'risk_layer_nav',
142 'signal_layer_nav',
143 'full_model_nav',
144 'full_model_net_nav',
145 )
146 base_returns = {
147 field: np.log(navs[field]).diff().dropna().to_numpy()
148 for field in layer_fields
149 }
150 benchmark_returns = np.log(navs['benchmark_nav']).diff().dropna().to_numpy()
151
152 def build_effects(
153 annual_means: dict[str, float],
154 annual_vols: dict[str, float],
155 annual_cost: float,
156 ) -> dict[str, np.ndarray]:
157 """Simulate one feature's layer effects and its incremental implementation cost."""
158 effects = {
159 field: _orthogonal_feature_return(
160 annual_mean=annual_means[field],
161 annual_vol=annual_vols[field],
162 benchmark_returns=benchmark_returns,
163 rng=rng,
164 )
165 for field in ('risk_layer_nav', 'signal_layer_nav', 'full_model_nav')
166 }
167 effects['full_model_net_nav'] = (
168 effects['full_model_nav'] - annual_cost / PERIODS_PER_YEAR
169 )
170 return effects
171
172 beta_effects = build_effects(
173 annual_means={
174 'risk_layer_nav': 0.0015,
175 'signal_layer_nav': -0.0005,
176 'full_model_nav': 0.0025,
177 },
178 annual_vols={
179 'risk_layer_nav': 0.006,
180 'signal_layer_nav': 0.005,
181 'full_model_nav': 0.009,
182 },
183 annual_cost=0.0003,
184 )
185 signal_effects = build_effects(
186 annual_means={
187 'risk_layer_nav': 0.0,
188 'signal_layer_nav': 0.0045,
189 'full_model_nav': 0.0020,
190 },
191 annual_vols={
192 'risk_layer_nav': 0.004,
193 'signal_layer_nav': 0.010,
194 'full_model_nav': 0.009,
195 },
196 annual_cost=0.0005,
197 )
198 interaction_effects = build_effects(
199 annual_means={
200 'risk_layer_nav': 0.0004,
201 'signal_layer_nav': 0.0006,
202 'full_model_nav': 0.0012,
203 },
204 annual_vols={
205 'risk_layer_nav': 0.003,
206 'signal_layer_nav': 0.004,
207 'full_model_nav': 0.005,
208 },
209 annual_cost=0.0001,
210 )
211
212 def to_nav(log_returns: np.ndarray, name: str) -> pd.Series:
213 """Convert one scenario's monthly log returns to a unit-initialised NAV."""
214 return pd.Series(
215 np.exp(np.concatenate([[0.0], np.cumsum(log_returns)])),
216 index=dates,
217 name=name,
218 )
219
220 coalitions = (
221 frozenset(),
222 frozenset({BETA_SPAN_FEATURE}),
223 frozenset({SIGNAL_HORIZON_FEATURE}),
224 frozenset({BETA_SPAN_FEATURE, SIGNAL_HORIZON_FEATURE}),
225 )
226 scenarios: dict[frozenset[str], qis.ModelLayerNavs] = {}
227 for coalition in coalitions:
228 scenario_returns = {
229 field: values.copy() for field, values in base_returns.items()
230 }
231 if BETA_SPAN_FEATURE in coalition:
232 scenario_returns = {
233 field: values + beta_effects[field]
234 for field, values in scenario_returns.items()
235 }
236 if SIGNAL_HORIZON_FEATURE in coalition:
237 scenario_returns = {
238 field: values + signal_effects[field]
239 for field, values in scenario_returns.items()
240 }
241 if len(coalition) == 2:
242 scenario_returns = {
243 field: values + interaction_effects[field]
244 for field, values in scenario_returns.items()
245 }
246 label = '+'.join(sorted(coalition)) or 'production'
247 scenarios[coalition] = qis.ModelLayerNavs(
248 benchmark_nav=navs['benchmark_nav'],
249 risk_layer_nav=to_nav(
250 scenario_returns['risk_layer_nav'], f'{label} Risk Layer'
251 ),
252 signal_layer_nav=to_nav(
253 scenario_returns['signal_layer_nav'], f'{label} Signal Layer'
254 ),
255 full_model_nav=to_nav(
256 scenario_returns['full_model_nav'], f'{label} Full Model'
257 ),
258 full_model_net_nav=to_nav(
259 scenario_returns['full_model_net_nav'], f'{label} Full Model Net'
260 ),
261 )
262 return scenarios
263
264
265def check_identities(attribution: qis.ModelLayerAlphaBetaAttribution,
266 navs: dict[str, pd.Series]
267 ) -> None:
268 """Verify linearity, bar heights, and the excess-basis invariance, and print the residuals."""
269 table = attribution.regression_table
270 alpha, beta = qis.PerfStat.ALPHA.to_str(), qis.PerfStat.BETA.to_str()
271 an_alpha = qis.PerfStat.ALPHA_AN.to_str()
272 linearity_beta = table.loc['Integration', beta] - (
273 table.loc['Full Model', beta]
274 - table.loc['Risk Layer', beta]
275 - table.loc['Signal Layer', beta]
276 )
277 linearity_alpha = table.loc['Integration', alpha] - (
278 table.loc['Full Model', alpha]
279 - table.loc['Risk Layer', alpha]
280 - table.loc['Signal Layer', alpha]
281 )
282 bars = attribution.annualised_components
283 bar_heights = max(abs(bars['Risk Layer Alpha'] - table.loc['Risk Layer', an_alpha]),
284 abs(bars['Signal Layer Alpha'] - table.loc['Signal Layer', an_alpha]),
285 abs(bars['Integration Alpha'] - table.loc['Integration', an_alpha]))
286 # excess basis: the signal-layer NAV divided by the benchmark NAV has log return r_S - r_B
287 excess_navs = dict(navs)
288 excess_navs['signal_layer_nav'] = (
289 navs['signal_layer_nav'] / navs['benchmark_nav']
290 ).rename('Signal Layer')
291 excess = qis.compute_model_layer_alpha_beta_attribution(
292 freq=FREQ, **excess_navs
293 ).regression_table
294 invariant_columns = [
295 alpha,
296 an_alpha,
297 ALPHA_HAC_SE_COLUMN,
298 ALPHA_AN_CI_LOW_COLUMN,
299 ALPHA_AN_CI_HIGH_COLUMN,
300 qis.PerfStat.ALPHA_PVALUE.to_str(),
301 ]
302 invariance = np.abs(excess[invariant_columns] - table[invariant_columns]).max().max()
303 beta_shift_signal_layer = excess.loc['Signal Layer', beta] - table.loc['Signal Layer', beta]
304 beta_shift_integration = excess.loc['Integration', beta] - table.loc['Integration', beta]
305 print(f'linearity: beta residual {linearity_beta:.1e}, alpha residual {linearity_alpha:.1e}')
306 print(f'bar heights minus annualised OLS alphas: {bar_heights:.1e}')
307 print(
308 f'excess basis: max change in alphas, SEs, CIs, p-values {invariance:.1e}; '
309 f'beta shifts signal layer {beta_shift_signal_layer:+.6f}, '
310 f'integration {beta_shift_integration:+.6f}'
311 )
312 assert abs(linearity_beta) < 1e-12 and abs(linearity_alpha) < 1e-12
313 assert bar_heights < 1e-12
314 assert invariance < 1e-10
315 assert abs(beta_shift_signal_layer + 1.0) < 1e-10
316 assert abs(beta_shift_integration - 1.0) < 1e-10
317
318
319def report_lag_rule_half_widths(attribution: qis.ModelLayerAlphaBetaAttribution,
320 navs: dict[str, pd.Series]
321 ) -> None:
322 """Print the alpha interval half-widths at the default lag count and at the Newey-West rule."""
323 n_obs = len(attribution.periodic_returns)
324 rule_lags = newey_west_lag_rule(nobs=n_obs)
325 rule = qis.compute_model_layer_alpha_beta_attribution(freq=FREQ, hac_lags=rule_lags, **navs)
326 layers = ['Risk Layer', 'Signal Layer', 'Integration', 'Full Model']
327 default_table = attribution.regression_table.loc[layers]
328 rule_table = rule.regression_table.loc[layers]
329 half_widths = pd.DataFrame(
330 {
331 f'HAC({attribution.hac_lags}) bp': 0.5
332 * 1e4
333 * (
334 default_table[ALPHA_AN_CI_HIGH_COLUMN]
335 - default_table[ALPHA_AN_CI_LOW_COLUMN]
336 ),
337 f'HAC({rule.hac_lags}) bp': 0.5
338 * 1e4
339 * (
340 rule_table[ALPHA_AN_CI_HIGH_COLUMN]
341 - rule_table[ALPHA_AN_CI_LOW_COLUMN]
342 ),
343 }
344 )
345 print(
346 'annualised alpha interval half-widths, default lags versus '
347 f'Newey-West rule at T = {n_obs}:'
348 )
349 print(half_widths.round(1).to_string())
350
351
352def plot_return_bridge(attribution: qis.ModelLayerAlphaBetaAttribution,
353 ax: Optional[plt.Axes] = None
354 ) -> plt.Figure:
355 """Draw the annualised log-return bridge with HAC whiskers on the three alpha bars."""
356 values = attribution.annualised_components
357 table = attribution.regression_table
358 beta = qis.PerfStat.BETA.to_str()
359 steps = [
360 ('Benchmark', values['Benchmark Return'], None, False),
361 (
362 f'Systematic\nbeta = {table.loc["Full Model", beta]:.2f}',
363 values['Systematic Return'],
364 None,
365 False,
366 ),
367 (
368 f'+ Risk-layer\nalpha\nbeta = {table.loc["Risk Layer", beta]:.2f}',
369 values['Risk Layer Alpha'],
370 'Risk Layer',
371 True,
372 ),
373 (
374 f'+ Signal-layer\nalpha\nbeta = {table.loc["Signal Layer", beta]:.2f}',
375 values['Signal Layer Alpha'],
376 'Signal Layer',
377 True,
378 ),
379 (
380 f'+ Integration\nalpha\nbeta = {table.loc["Integration", beta]:.2f}',
381 values['Integration Alpha'],
382 'Integration',
383 True,
384 ),
385 ('Trading-cost\ndrag', values['Trading Cost Drag'], None, True),
386 ('Full model\nnet', values['Full Model Net Return'], None, False),
387 ]
388 if ax is None:
389 fig, ax = plt.subplots(1, 1, figsize=(11, 6))
390 else:
391 fig = ax.figure
392 level = 0.0
393 for position, (label, value, layer, is_step) in enumerate(steps):
394 bottom = level if is_step else 0.0
395 colour = '#3B5F7A' if not is_step else ('#8A6F3D' if value >= 0.0 else '#B45B5B')
396 ax.bar(position, value, bottom=bottom, width=0.6, color=colour)
397 top = bottom + value
398 if layer is not None:
399 ci_low = table.loc[layer, ALPHA_AN_CI_LOW_COLUMN]
400 ci_high = table.loc[layer, ALPHA_AN_CI_HIGH_COLUMN]
401 ax.errorbar(position, top, yerr=[[value - ci_low], [ci_high - value]], fmt='none',
402 ecolor='black', elinewidth=1.2, capsize=5)
403 annotation_level = bottom + (ci_high if value >= 0.0 else ci_low)
404 else:
405 annotation_level = top
406 ax.annotate(
407 f'{value:+.1%}' if is_step else f'{value:.1%}',
408 xy=(position, annotation_level),
409 xytext=(0, 5 if value >= 0.0 else -14),
410 textcoords='offset points',
411 ha='center',
412 fontsize=10,
413 )
414 level = top if is_step else value
415 if position == 0:
416 level = 0.0
417 ax.set_xticks(range(len(steps)), [step[0] for step in steps], fontsize=9)
418 ax.yaxis.set_major_formatter(PercentFormatter(1.0))
419 ax.set_ylabel('Annualised mean log return')
420 ax.set_title(
421 'Model-layer attribution on simulated layers: '
422 'whiskers are 95% Bartlett HAC(3) intervals'
423 )
424 ax.axhline(0.0, color='black', linewidth=0.8)
425 ax.spines[['top', 'right']].set_visible(False)
426 return fig
427
428
429def _new_exhibit(title: str, subtitle: str) -> tuple[plt.Figure, plt.Axes]:
430 """Create one presentation-style attribution exhibit."""
431 fig, ax = plt.subplots(1, 1, figsize=(11, 7))
432 fig.patch.set_facecolor(REPORT_BACKGROUND)
433 ax.set_facecolor(REPORT_BACKGROUND)
434 fig.subplots_adjust(left=0.10, right=0.98, top=0.80, bottom=0.20)
435 fig.text(
436 0.10,
437 0.935,
438 title,
439 color=REPORT_TEXT,
440 fontsize=20,
441 fontweight='bold',
442 ha='left',
443 )
444 fig.text(0.10, 0.885, subtitle, color='#5F6F78', fontsize=12, ha='left')
445 return fig, ax
446
447
448def _style_exhibit_axes(ax: plt.Axes) -> None:
449 """Apply the common documentation-exhibit axis styling."""
450 ax.grid(axis='y', color=REPORT_GRID, linewidth=0.8, alpha=0.85)
451 ax.set_axisbelow(True)
452 ax.tick_params(colors=REPORT_TEXT)
453 ax.xaxis.label.set_color(REPORT_TEXT)
454 ax.yaxis.label.set_color(REPORT_TEXT)
455 ax.spines[['top', 'right']].set_visible(False)
456 ax.spines[['bottom', 'left']].set_color(REPORT_GRID)
457
458
459def plot_cumulative_alpha(
460 attribution: qis.ModelLayerAlphaBetaAttribution,
461) -> plt.Figure:
462 """Draw additive cumulative alpha paths from the exact periodic bridge components."""
463 alpha_returns = attribution.component_returns.loc[:, [
464 'Risk Layer Alpha',
465 'Signal Layer Alpha',
466 'Integration Alpha',
467 ]].rename(columns={
468 'Risk Layer Alpha': 'Risk-layer alpha',
469 'Signal Layer Alpha': 'Signal-layer alpha',
470 'Integration Alpha': 'Integration alpha',
471 })
472 alpha_returns.insert(0, 'Total model alpha', alpha_returns.sum(axis=1))
473 initial_date = alpha_returns.index[0] - pd.tseries.frequencies.to_offset(
474 attribution.freq
475 )
476 alpha_paths = pd.concat([
477 pd.DataFrame(0.0, index=[initial_date], columns=alpha_returns.columns),
478 alpha_returns.cumsum(),
479 ])
480 np.testing.assert_allclose(
481 alpha_paths['Total model alpha'],
482 alpha_paths[
483 ['Risk-layer alpha', 'Signal-layer alpha', 'Integration alpha']
484 ].sum(axis=1),
485 atol=1.0e-12,
486 rtol=0.0,
487 )
488
489 fig, ax = _new_exhibit(
490 title='Cumulative model-layer alpha contributions',
491 subtitle='Additive full-sample attribution | cumulative monthly log returns, start = 0%',
492 )
493 qis.plot_time_series(
494 df=alpha_paths,
495 ax=ax,
496 colors=[
497 TOTAL_ALPHA_COLOR,
498 RISK_ALPHA_COLOR,
499 SIGNAL_ALPHA_COLOR,
500 INTEGRATION_ALPHA_COLOR,
501 ],
502 linewidth=1.8,
503 x_date_freq='4YE',
504 date_format='%Y',
505 legend_stats=qis.LegendStats.NONE,
506 legend_loc='upper left',
507 ylabel='Cumulative alpha contribution',
508 var_format='{:.1%}',
509 text_weight='normal',
510 )
511 ax.lines[0].set_linewidth(2.6)
512 ax.axhline(0.0, color=REPORT_TEXT, linewidth=0.8)
513 ax.yaxis.set_major_formatter(PercentFormatter(1.0))
514 _style_exhibit_axes(ax=ax)
515 fig.text(
516 0.10,
517 0.055,
518 'Paths cumulatively sum the beta-adjusted monthly log-return components estimated '
519 'with full-sample OLS betas.\nTotal model alpha equals risk-layer + signal-layer + '
520 'integration alpha at every date; the paths are explanatory contributions, not NAVs.',
521 color='#65747C',
522 fontsize=9,
523 ha='left',
524 )
525 return fig
526
527
528def check_feature_design(
529 decomposition: qis.ModelFeatureAlphaBetaAttribution,
530) -> None:
531 """Check the Shapley estimates against the simulation's independently derived means."""
532 expected = pd.DataFrame(
533 {
534 'Annualised Full Model Net Return': [0.00275, 0.00205],
535 'Full Model Alpha': [0.00310, 0.00260],
536 'Risk Layer Alpha': [0.00170, 0.00020],
537 'Signal Layer Alpha': [-0.00020, 0.00480],
538 'Integration Alpha': [0.00160, -0.00240],
539 },
540 index=[BETA_SPAN_FEATURE, SIGNAL_HORIZON_FEATURE],
541 )
542 actual = decomposition.summary.loc['Shapley', expected.columns]
543 np.testing.assert_allclose(actual, expected, atol=1.0e-10, rtol=0.0)
544 np.testing.assert_allclose(
545 actual['Full Model Alpha'],
546 actual[['Risk Layer Alpha', 'Signal Layer Alpha', 'Integration Alpha']].sum(axis=1),
547 atol=1.0e-12,
548 rtol=0.0,
549 )
550 assert float(decomposition.identity_errors.max()) < 1.0e-12
551 print('two-feature Shapley effects (annualised percentage points):')
552 print((100.0 * actual).round(3).to_string())
553
554
555def plot_feature_decomposition(
556 decomposition: qis.ModelFeatureAlphaBetaAttribution,
557) -> plt.Figure:
558 """Draw grouped Shapley net-return and layer-alpha effects with HAC intervals."""
559 summary = decomposition.summary.loc['Shapley']
560 metric_specs = (
561 ('Annualised Full Model Net Return', 'Total net\nreturn change'),
562 ('Full Model Alpha', 'Total alpha\nchange'),
563 ('Risk Layer Alpha', 'Risk-layer\nalpha'),
564 ('Signal Layer Alpha', 'Signal-layer\nalpha'),
565 ('Integration Alpha', 'Integration\nalpha'),
566 )
567 x_positions = np.arange(len(metric_specs), dtype=float)
568 width = 0.34
569 fig, ax = _new_exhibit(
570 title='Two-feature model sensitivity',
571 subtitle=(
572 'Annualised net-return and OLS alpha effects | monthly log returns | '
573 'order-independent Shapley allocation'
574 ),
575 )
576 for feature_index, feature in enumerate(
577 (BETA_SPAN_FEATURE, SIGNAL_HORIZON_FEATURE)
578 ):
579 offset = (-0.5 if feature_index == 0 else 0.5) * width
580 positions = x_positions + offset
581 values = np.array([
582 float(summary.loc[feature, metric]) for metric, _ in metric_specs
583 ])
584 ci_low = np.array([
585 float(summary.loc[feature, f'{metric} CI Low'])
586 for metric, _ in metric_specs
587 ])
588 ci_high = np.array([
589 float(summary.loc[feature, f'{metric} CI High'])
590 for metric, _ in metric_specs
591 ])
592 interval_midpoints = 0.5 * (ci_low + ci_high)
593 np.testing.assert_allclose(values, interval_midpoints, atol=1.0e-12, rtol=0.0)
594 ax.bar(
595 positions,
596 values,
597 width=width * 0.88,
598 color=FEATURE_COLORS[feature],
599 label=FEATURE_LABELS[feature],
600 zorder=3,
601 )
602 ax.errorbar(
603 positions,
604 values,
605 yerr=np.vstack([values - ci_low, ci_high - values]),
606 fmt='none',
607 color='black',
608 ecolor='black',
609 elinewidth=1.3,
610 capsize=4.0,
611 zorder=5,
612 )
613 ax.scatter(
614 positions,
615 interval_midpoints,
616 s=24.0,
617 color='black',
618 edgecolors=REPORT_BACKGROUND,
619 linewidths=0.8,
620 zorder=6,
621 )
622 for position, value, low, high in zip(positions, values, ci_low, ci_high):
623 label_anchor = high if value >= 0.0 else low
624 ax.annotate(
625 f'{value:+.2%}',
626 xy=(position, label_anchor),
627 xytext=(0, 6 if value >= 0.0 else -8),
628 textcoords='offset points',
629 ha='center',
630 va='bottom' if value >= 0.0 else 'top',
631 color=REPORT_TEXT,
632 fontsize=8.5,
633 fontweight='bold',
634 )
635 ax.set_xticks(x_positions, [label for _, label in metric_specs])
636 ax.axhline(0.0, color=REPORT_TEXT, linewidth=0.8)
637 ax.set_ylabel('Annualised effect')
638 ax.yaxis.set_major_formatter(PercentFormatter(1.0))
639 ax.legend(frameon=False, ncols=2, loc='upper center')
640 ax.margins(x=0.08, y=0.28)
641 _style_exhibit_axes(ax=ax)
642 fig.text(
643 0.10,
644 0.045,
645 f'Whiskers are {decomposition.confidence_level:.0%} Bartlett HAC('
646 f'{decomposition.hac_lags}) intervals: intercept-only for net-return changes and '
647 'benchmark OLS for alpha.\nEach feature receives half of the two-feature interaction; '
648 'total alpha is the exact sum of risk, signal, and integration alpha.',
649 color='#65747C',
650 fontsize=9,
651 ha='left',
652 )
653 return fig
654
655
656def run_example(
657 save_figure_path: Optional[str] = None,
658 output_dir: Optional[Path] = None,
659) -> qis.ModelLayerAlphaBetaAttribution:
660 """Run the seeded layer and feature attributions and draw all three exhibits.
661
662 Args:
663 save_figure_path: Optional legacy destination for the return-bridge figure.
664 output_dir: Optional directory for all three documentation figures.
665
666 Returns:
667 The base model-layer attribution used by the bridge and cumulative-alpha exhibits.
668 """
669 navs = simulate_layer_navs()
670 attribution = qis.compute_model_layer_alpha_beta_attribution(freq=FREQ, **navs)
671 feature_decomposition = qis.compute_model_feature_alpha_beta_attribution(
672 scenario_layer_navs=simulate_feature_scenarios(navs=navs),
673 freq=FREQ,
674 )
675 pd.set_option('display.width', 200)
676 first_date = attribution.periodic_returns.index[0]
677 last_date = attribution.periodic_returns.index[-1]
678 print(
679 f'common sample: {len(attribution.periodic_returns)} '
680 f'{attribution.freq} log returns, {first_date:%b %Y} to {last_date:%b %Y}; '
681 f'HAC lags {attribution.hac_lags}, '
682 f'confidence level {attribution.confidence_level:.0%}'
683 )
684 print('regression table (alpha and its bounds annualised, beta and SE periodic):')
685 print(attribution.regression_table.round(5).to_string())
686 print('annualised components (bar heights):')
687 print((100.0 * attribution.annualised_components).round(2).to_string())
688 check_identities(attribution=attribution, navs=navs)
689 report_lag_rule_half_widths(attribution=attribution, navs=navs)
690 check_feature_design(decomposition=feature_decomposition)
691 bridge_figure = plot_return_bridge(attribution=attribution)
692 cumulative_figure = plot_cumulative_alpha(attribution=attribution)
693 feature_figure = plot_feature_decomposition(
694 decomposition=feature_decomposition
695 )
696 if save_figure_path is not None:
697 bridge_figure.savefig(save_figure_path, dpi=150, bbox_inches='tight')
698 if output_dir is not None:
699 output_dir = Path(qis.get_output_path(output_dir))
700 documentation_figures = {
701 'model_layer_attribution_simulated.png': bridge_figure,
702 'model_layer_attribution_cumulative_alpha_simulated.png': cumulative_figure,
703 'model_feature_attribution_simulated.png': feature_figure,
704 }
705 for file_name, figure in documentation_figures.items():
706 figure.savefig(output_dir.joinpath(file_name), dpi=150, bbox_inches='tight')
707 if save_figure_path is None and output_dir is None:
708 plt.show()
709 else:
710 for figure in (bridge_figure, cumulative_figure, feature_figure):
711 plt.close(figure)
712 return attribution
713
714
715class Locals(Enum):
716 PLOT = 1
717 EXPORT = 2
718
719
720def run_local(local: Locals, output_path: str = None):
721 """Display the simulation or export figures through the shared YAML path resolver."""
722 if local not in (Locals.PLOT, Locals.EXPORT):
723 raise ValueError(local)
724 output = None
725 if local == Locals.EXPORT or output_path is not None:
726 output = Path(qis.get_output_path(output_path))
727 return run_example(output_dir=output)
728
729
730if __name__ == '__main__':
731 run_local(local=Locals.PLOT)
The printed regression table (alphas and bounds in decimal log-return units, beta dimensionless, and the HAC standard error measured per observation) is:
Alpha An Alpha Beta R2 p-Alpha Alpha HAC SE An Alpha CI Low An Alpha CI High
Benchmark 0.00000 0.00000 1.00000 1.00000 1.00000 0.00000 0.00000 0.00000
Risk Layer 0.00103 0.01232 1.04715 0.96061 0.04831 0.00052 0.00009 0.02455
Signal Layer 0.00229 0.02743 0.98753 0.85319 0.01073 0.00090 0.00636 0.04851
Integration -0.00071 -0.00849 -1.17503 0.94954 0.21851 0.00058 -0.02203 0.00504
Full Model 0.00260 0.03126 0.85966 0.83225 0.00354 0.00089 0.01025 0.05227
Full Model Net 0.00248 0.02976 0.85966 0.83225 0.00550 0.00089 0.00875 0.05077
The annualised mean log-return components in percent are benchmark return 5.05, systematic return 4.34, risk-layer alpha 1.23, signal-layer alpha 2.74, integration alpha −0.85, full-model return 7.47, trading-cost drag −0.15 and net return 7.32. The identity checks print residuals of order \(10^{-15}\) or smaller for linearity and bar heights, and the excess-basis run changes no alpha, standard error, bound or p-value while shifting the signal-layer beta by exactly −1 and the integration beta by exactly +1. The lag-rule check moves from three to four Bartlett lags and changes the interval half-widths by at most 5 basis points per year, from 122 to 126 for the risk layer and from 210 to 215 for the full model. The headline directions in this illustration remain the same, but marginal significance and reported bounds still depend on the lag choice.

Read the exhibit left to right. The benchmark’s annualised mean log return was 5.05%. The full
model runs at \(\hat\beta_F = 0.86\), so its systematic return is 4.34%, and the 0.71% gap between the two
blue bars is the systematic return given up by running below beta one. The risk layer added
1.23% of alpha with an interval that just excludes zero (p = 0.048). The signal layer added
2.74% with an interval of 0.64% to 4.85%. The integration alpha is −0.85% with an interval of
−2.20% to +0.50%: the constrained model kept less than the full signal-layer alpha, and the
loss is not distinguishable from zero at this sample length. The design value of −1.2% lies
inside the interval. Total alpha is 3.13% with an interval of 1.03% to 5.23%, which is the sum of
the three alpha bars and the Full Model row of the table. Trading costs at 15 basis points per
year take the net return to 7.32%.
The integration beta is −1.18 on the total-return basis because both the risk and signal layers carry betas near one. On the excess basis for the signal layer it is −0.18, with the same alpha and the same whisker. The example checks this invariance at machine precision.
Additive cumulative exhibit¶

The seeded example accumulates 62.5 log-return percentage points of total model alpha over the 20-year sample: approximately 24.6 points from the risk layer and 54.9 from the signal layer, offset by 17.0 points of negative integration. The terminal identity is only one reading of the chart. The paths also show when each source added or detracted and whether the total was diversified across sources. At every intermediate date, not just at the end, the dark-green total is the exact sum of the teal, amber and brown paths.
Two-feature sensitivity exhibit¶
The simulated example represents a controlled \(2 \times 2\) experiment: production, a doubled beta-estimation span, a doubled signal horizon, and both changes together. In a production study, the caller reruns the complete model under the same data, constraints and cost assumptions for all four coalitions. The example supplies seeded illustrative NAVs for those four completed runs; QIS performs the factorial, Shapley and layer attribution, not the model reruns themselves.

Read each colour across the five groups. The first group is the feature’s annualised net-return change, estimated as a HAC mean. The remaining groups are benchmark-OLS alphas. The doubled beta-estimation span has a +0.31% total-alpha effect: +0.17% through the risk layer, -0.02% through the signal layer and +0.16% through integration. The doubled signal horizon has a +0.26% total-alpha effect: +0.02% risk, +0.48% signal and -0.24% integration. The component bars sum to the total-alpha bar for each feature; the net-return bar additionally reflects the simulated implementation-cost change.
The black whiskers are 95% Bartlett HAC(3) intervals from one regression on each Shapley effect path, and the black point marks the estimate at the interval midpoint. All intervals cross zero in this illustration: the chart communicates both the estimated direction and the uncertainty, not a tuning recommendation. One colour is retained for every bar belonging to the same feature, so the viewer follows a feature across layers rather than mistaking the layers for independent experiments.
Implementation in qis¶
Quantity |
Formula |
qis entry point |
|---|---|---|
Common-sample layer log returns |
\(\ell_{L,t}=\log V_{L,t}-\log V_{L,t-1}\) on the intersection of valid ranges |
|
Full-sample layer regressions and intervals |
OLS of \(\ell_L\) on \(\ell_B\); \(\mathrm{af}(\hat\alpha_L\pm z_{\gamma}\,\mathrm{se})\) |
|
Exact return bridge |
\(\ell_{F,t}=\hat\beta_F\ell_{B,t}+a_{R,t}+a_{S,t}+a_{I,t}\) |
|
Lagged realised alpha |
\(a_{L,t}=\ell_{L,t}-b_{L,t}\ell_{B,t}\) with \(b_{L,t}=\hat\beta_{L,t-h}\) |
|
Current EWMA of realised alpha |
\(\mathrm{af}\,\mathcal{E}_t[a_L]\) |
|
Post-warm-up cumulative alpha |
Sum of \(a_{L,t'}\) after a base date, zero on it |
|
Endpoint EWMA-WLS attribution |
WLS with \(\omega_t=\lambda^{T-1-t}\); stacked Bartlett HAC |
|
Expanding-prefix EWMA-WLS alpha |
\(\mathrm{af}\,\hat\alpha_{L,t}\) with \(\omega_{t',t}=\lambda^{t-t'}\) |
|
Common-denominator Sharpe contributions |
\(\pi_K=\hat\mu_K/\sigma_{F^{*}}\), \(\mathrm{SR}_B=\hat\mu_B/\sigma_B\) |
|
Sequential stage Sharpes |
EWM Sharpe of cumulative bridge stages |
|
Factorial and Shapley feature effects |
\(d^{\mathcal{C}}_{L,t}\), \(\phi_{f,L,t}\), then the layer attribution of each |
|
The runnable workflow covers the public attribution entry points. Plot a result with
qis.plot_model_layer_ewma_return_bridge, qis.plot_model_layer_rolling_ewma_regression_alpha,
qis.plot_model_layer_ewma_sharpe_bridge, or qis.plot_model_layer_in_sample_sharpe_bridge;
each accepts the matching attribution object. Canonical sources are
model_layer.py,
model_feature.py,
and the plotting module.
The regression module
owns the OLS and weighted HAC estimators. Its qualified helper names are contributor references,
not a promise that every helper is exported as qis.<name>.
The three previews use the dedicated simulation and are registered to the model-layer producer. The batch runner instructions describe how to regenerate the documentation analytics image bundle with its tables and source fingerprints in one run. The published provenance record identifies the actual source version, parameters, checks and image hashes. These previews share the gallery’s typography while preserving the simulation and computed values. Their fixed sample endpoint is not a market-data freshness claim.
Reading the result¶
ModelLayerAlphaBetaAttribution has seven fields.
periodic_returnsThe common-sample log returns of the supplied NAVs, one column per layer.
regression_tableOne row per layer (
Benchmark,Risk Layer,Signal Layer,Integration,Full Model, andFull Model Netwhen a net NAV is supplied). Columns are thePerfStatlabels for alpha, annualised alpha, beta, \(R^2\) and the alpha p-value, thenAlpha HAC SE(periodic),An Alpha CI LowandAn Alpha CI High(annualised). The column-label constants are exported fromqis.portfolio.attribution.model_layer.component_returnsThe exact periodic components:
Benchmark Return,Risk Layer Return,Signal Layer Return,Systematic Return,Risk Layer Alpha,Signal Layer Alpha,Integration Alpha,Full Model Return, thenTrading Cost DragandFull Model Net Returnwhen a net NAV is supplied.annualised_components\(\mathrm{af}\) times the column means of
component_returns. These are the bar heights of a return bridge, and by the bar-height identity the three alpha entries equal the annualised alphas inregression_table.freq,hac_lags,confidence_levelThe return frequency, Bartlett lag count and interval level used in the estimation.
ModelLayerEwmaAlphaAttribution contains periodic_returns, estimated_betas, applied_betas,
component_returns, cumulative_alpha, expanding_annualised_alpha, and the settings freq,
beta_span, beta_lag, beta_init_value, and mean_adj_type. Its computed properties
ewma_annualised_components and ewma_annualised_alpha apply beta_span to the exact realised
component returns. current_ewma_annualised_components and current_ewma_annualised_alpha return
their final rows. The final row of estimated_betas is the beta estimate after the latest return,
available for the next period; the final row of applied_betas is the lagged beta that explained
the latest return.
ModelLayerEwmaRegressionAttribution contains periodic_returns (monthly at the default
freq='ME'), geometric weights, regression_table, exact component_returns, weighted
annualised_components, joint annualised_alpha_covariance, direct-equation
parameter_covariance, and the settings freq, span, ewm_lambda, nobs, effective_nobs,
hac_lags, and confidence_level. This result is the input to both EWMA bridge plots, the rolling
EWMA-WLS alpha path, the additive Sharpe contributions, and the legacy sequential stage Sharpes.
ModelLayerCumulativeAlphaAttribution contains the post-warm-up alpha_returns and
cumulative_alpha, the base_date, first_alpha_date, warmup_periods, and the inherited beta
estimator settings.
Reading the feature-attribution result¶
ModelFeatureAlphaBetaAttribution keeps the scenario paths, effect paths and statistical
attributions separate:
scenario_layer_navscontains the aligned, rebasedModelLayerNavsinput for every coalition.factorial_effect_navsandfactorial_effect_attributionscontain the Harsanyi direct effects and interactions. Singleton coalitions are direct effects; larger coalitions are interactions.shapley_feature_navsandfeature_attributionscontain the order-independent allocation of all interactions to individual features.joint_effect_navsandjoint_attributionmeasure all features enabled versus production.summaryprovides factorial, Shapley and joint return estimates, alpha estimates, betas, p-values and confidence intervals in one table.identity_errorsaudits that both the factorial effects and Shapley effects reconstruct the joint path, and that every model-layer alpha bridge reconciles.
Every value in feature_attributions is a normal ModelLayerAlphaBetaAttribution. Consequently,
the additive cumulative-alpha construction above applies without modification to one feature’s
Shapley effect. The runnable workflow constructs the corresponding risk_span_alpha_paths.
The resulting total path answers when the Shapley-allocated alpha effect of beta_span
accumulated. Its three component paths show whether that effect came through the risk layer, the
signal layer, or integration in the constrained full model. As for the base model, the
paths are additive log-return percentage points, not compounded feature NAVs.
Interpretation and limitations¶
Returns are log returns at
freq, and alphas are annualised linearly by the periods per year offreq. State the frequency when quoting the numbers.The OLS/HAC regressions are full-sample and descriptive. Their betas are not point-in-time estimates and their components must not be used as backtest inputs or read as forecasts.
The rolling estimator is point-in-time only when
mean_adj_typeisEWMA,EXPANDING, orNONEand the estimated beta is applied after a positive lag. The API rejectsINSAMPLE.The endpoint EWMA-WLS estimator is also descriptive. Its geometric weights emphasise recent monthly returns, but its final beta is estimated with the same final return it describes.
The default lag count of three applies at any frequency. At the default quarterly frequency three lags span nine months, and
newey_west_lag_rulegives the sample-size rule instead. Normal-reference HAC inference is asymptotic. Small samples, structural breaks and strong dependence can make nominal 95% intervals unreliable; see serial dependence for diagnosing persistent residuals.The common sample is the intersection of the layers’ valid ranges. A short layer shortens the sample for every layer, so check
periodic_returns.indexwhen a layer has a late start or an early end.The integration term is a log-return residual, not a portfolio. Its beta depends on the stated total-return or benchmark-excess basis for the signal layer.
Cumulative alpha paths are arithmetic sums of the periodic log-return components. Compounding them into NAV indices changes the question from additive alpha attribution to wealth impact.
The EWMA Sharpe bridge divides all model components by the same full-model EWMA volatility, so it is additive and order-free. The benchmark reference uses benchmark volatility. The legacy
compute_model_layer_ewma_stage_sharpesdiagnostic remains order-dependent.Layer and feature effects depend on the supplied counterfactual runs and the chosen benchmark. They do not establish causal effects of changing an optimiser or prove investable future alpha.
Forward filling within a common sample can hide stale marks. Validate positive NAVs, duplicate dates, calendar alignment and valuation timing before fitting; dropping nonfinite returns is not a data-quality repair.
The Sharpe bridges use log-return numerators on the supplied NAV basis and do not automatically subtract risk-free returns. They are not the separately specified Sharpe conventions in performance analytics.
HAC intervals quantify sampling uncertainty conditional on the experiment. They do not correct for choosing a benchmark, seed, features or settings after seeing the results, and separate feature intervals are not a simultaneous multiple-testing guarantee.
See also¶
Regression and HAC inference: OLS, linearity, Bartlett HAC, lag rule and EWMA-WLS
Exponentially weighted estimators: spans, seeds, mean adjustment and EWM volatility
References¶
Kish, L. (1965). Survey Sampling. Wiley. Defines the effective sample size reported for the geometric weights.
Newey, W. K., and West, K. D. (1987). A Simple, Positive Semi-Definite, Heteroskedasticity and Autocorrelation Consistent Covariance Matrix. Econometrica, 55(3), 703–708. Working paper and published-version record.
Newey, W. K., and West, K. D. (1994). Automatic Lag Selection in Covariance Matrix Estimation. The Review of Economic Studies, 61(4), 631–653. DOI: 10.2307/2297912. The lag rule of thumb returned by
newey_west_lag_ruleis associated with this paper.Shapley, L. S. (1952). A Value for N-Person Games. RAND, P-295. Original report. Published in Contributions to the Theory of Games II (1953); publisher’s reprint record.
statsmodels developers. statsmodels. Software. HAC covariance documentation.
Sepp, A. qis: Performance analytics, portfolio backtesting, risk analysis, and factsheet reporting in Python. Software citation metadata.