Factor attribution realised: private API

PortfolioOptimisers.attribution_slice — Function
attribution_slice(B::MatNum, t::Integer)
attribution_slice(B::Arr3Num, t::Integer)

Return the exposure slice of one observation.

A block whose exposures do not move holds one matrix, and that matrix is the slice of every observation. A block that keeps a history returns the slice of t. The shape of B selects the method, so a caller uses one function for both.

Arguments

  • B: The static loadings, or the exposure history.
  • t: The observation.

Returns

  • Bt::MatNum: The exposures of observation t, assets × factors.

Related

source
PortfolioOptimisers.attribution_weights — Function
attribution_weights(w::VecNum, t::Integer)
attribution_weights(W::MatNum, t::Integer)

Return the portfolio weights of one observation.

A constant weight vector is the weights of every observation. A weight history returns the row of t. The shape of the weights selects the method, so a caller uses one function for both.

Arguments

  • w: The constant weights, or the weight history.
  • t: The observation.

Returns

  • wt::VecNum: The weights of observation t.

Related

source
PortfolioOptimisers.attribution_cov — Function
attribution_cov(x::VecNum, yc::VecNum)

Return the covariance of a series with a pre-centred series.

A realised attribution centres the portfolio series once and takes every covariance against it. The covariances of the parts with the whole then sum to the variance of the whole, so the components add up.

Mathematical definition

\[\begin{align} \operatorname{cov}(x, y) &= \frac{1}{T - 1} \sum_{t=1}^{T} (x_{t} - \bar{x})\, y_{t}\,, \\ 0 &= \sum_{t=1}^{T} y_{t}\,. \end{align}\]

A centred $y$ makes the sum equal to the sample covariance, because $\bar{x} \sum_{t} y_{t}$ vanishes.

Where:

  • $x_{t}$, $y_{t}$: Entry $t$ of the series and of the centred series.
  • $\bar{x}$: Mean of the series.
  • $T$: Number of observations.

Arguments

  • x: The series.
  • yc: The pre-centred series.

Returns

  • cv::Real: The covariance, with the corrected denominator.

Related

source
PortfolioOptimisers.AlignedAttributionBlock — Type
struct AlignedAttributionBlock{__T_B, __T_f, __T_eps, __T_act, __T_rw, __T_vs, __T_fcb, __T_unseen, __T_rows, __T_no, __T_h1, __T_dc}

The lag-aligned history of a factor model block, which a realised attribution decomposes row by row.

This type is an implementation detail and is not intended for direct use. attribution_align makes it from an AttributionBlock, and attribution_window cuts it to a window. Aligned observation j reads the exposures of block row j and the returns of block row j + lag.

Fields

  • B: B: The exposures, static or lag-aligned, zero at every inactive pair.
  • f: f: The lag-aligned factor returns, with every non-finite entry replaced by zero.
  • eps: eps: The lag-aligned idiosyncratic returns, zero at every inactive pair.
  • act: act: Whether each aligned (observation, asset) pair is active.
  • rw: rw: The lag-aligned regression weights, with every non-finite entry replaced by zero, or nothing.
  • vs: vs: The lag-aligned idiosyncratic variances, NaN where the block states none, or nothing.
  • fcb: fcb: The family re-basis over the aligned axis, or nothing.
  • unseen: unseen: The Unseen Member rule the fit regressed under.
  • rows: rows: The rows of the caller's series the aligned history describes.
  • no: no: The number of observed factors, the last factors of the axis.
  • h1: h1: The lag-aligned leverage-one mask, or nothing.
  • dc: dc: The lag-aligned dropped-column mask, or nothing.

Constructors

AlignedAttributionBlock(B, f, eps, act, rw, vs, fcb, unseen, rows, no, h1, dc)AlignedAttributionBlock(; B, f, eps, act, rw, vs, fcb, unseen, rows, no, h1, dc)

Arguments correspond to the struct's fields, in the order they are declared, and the keyword constructor takes each field by its name, with no default. attribution_key_align replaces rows through rebuild_struct, which calls the keyword form.

Related

source
PortfolioOptimisers.attribution_align — Function
attribution_align(blk::AttributionBlock, T::Integer)

Return the lag-aligned history a realised factor attribution reads off a factor model block.

The function aligns bare arrays. A prior method of factor_attribution reads the block into them with attribution_block_arrays, and the bare-array method passes them directly, so the two paths share one alignment.

The fit of observation t regresses the returns of t on the exposures of t - lag, so the exposures are trimmed at the tail and every return-like history at the head. A block whose exposures do not move keeps its one matrix, because a static slice needs no alignment.

A fit that warmed up on the first observations keeps fewer than the caller's series carries, so the two axes are lined up at their tail. The aligned history describes the last observations of the caller's series, and rows names them.

Algorithm

  1. Read the exposure lag lag, the factor returns f and the idiosyncratic returns eps off the block, and the number of block observations Tb.
  2. Check that eps carries the observations of f, that the caller's series is at least as long as the block, and that the lag is non-negative and below the length of the block.
  3. Take the block rows brows = lag + 1:Tb, whose returns an exposure explains, and the caller's rows rows, the last Tb - lag of its T. Aligned observation j therefore reads the exposures of block row j, the returns of block row j + lag, and the caller's row T - Tb + lag + j.
  4. Trim the exposure history by lag at its tail. A static loadings matrix is kept as it is.
  5. Take the rows brows of f, of eps, of the regression weights rw and of the idiosyncratic variances vs.
  6. Zero every inactive (observation, asset) pair of the exposures and of eps with attribution_zero_inactive, giving B, eps and the mask act of the active pairs.
  7. Replace every non-finite entry of f and rw with zero through attribution_finite. vs keeps its non-finite entries, because a standard error that reads an unknown variance is unknown.
  8. Slice the family re-basis to its first Tb - lag observations with factor_basis_slice, giving fcb. The coefficients of observation t are coordinates in the basis of t - lag, so the basis follows the exposures and is sliced at the head of its own axis.

Arguments

Validation

  • The idiosyncratic returns carry the observations of the factor returns, else a DimensionMismatch is raised.
  • The caller's series carries at least as many observations as the block, else a DimensionMismatch is raised.
  • The exposure lag is non-negative, else a DomainError is raised.
  • The block carries more observations than the exposure lag, else a DimensionMismatch is raised.

Returns

  • al::AlignedAttributionBlock: The aligned history. Its rows are the rows of the caller's series the aligned history describes.

Related

source
PortfolioOptimisers.attribution_trim_exposures — Function
attribution_trim_exposures(B::MatNum, lag::Integer)
attribution_trim_exposures(B::Arr3Num, lag::Integer)

Return the exposure history trimmed at the tail by the lag.

A static loadings matrix describes every observation, so it is returned unchanged. A history is trimmed at the tail, which is the half of the alignment the exposures carry.

Arguments

  • B: The static loadings, or the exposure history.
  • lag: The exposure lag.

Returns

  • B: The static loadings, or the trimmed exposure history.

Related

source
PortfolioOptimisers.ZeroedInactivePairs — Type
struct ZeroedInactivePairs{__T_B, __T_eps, __T_act}

The exposures and the idiosyncratic returns of a block with every inactive pair zeroed, and the mask of the active pairs.

This type is an implementation detail and is not intended for direct use. attribution_zero_inactive makes it, and attribution_align reads it. A static loadings matrix and the idiosyncratic returns are matrices of one type, so a record names them.

Fields

  • B: B: The exposures, zero at every inactive pair.
  • eps: eps: The idiosyncratic returns, zero at every inactive pair.
  • act: act: Whether each pair is active, observations × assets.

Related

source
PortfolioOptimisers.attribution_zero_inactive — Function
attribution_zero_inactive(B::MatNum, eps::MatNum)
attribution_zero_inactive(B::Arr3Num, eps::MatNum)

Return the exposures and the idiosyncratic returns with every inactive pair zeroed, and the mask of the active pairs.

A pair is inactive when the block states no idiosyncratic return for it, or no exposure to one of the factors: the asset was not listed, was on a holiday, or was outside the fit. The net series takes no return from a pair the block cannot decompose, so the pair contributes nothing to the total, and it must contribute nothing to any component. Zeroing only its idiosyncratic return would leave its systematic return w B f in the systematic component, and put the opposite amount in the remainder, which then reports a data gap as a return the model does not explain.

A static loadings matrix keeps its shape when every inactive pair belongs to an asset without loadings, because that asset is inactive at every observation. Otherwise the matrix is broadcast to a history first, so a single observation of an asset can be zeroed.

Mathematical definition

\[\begin{align} a_{ti} &= \mathbb{1}\left[\varepsilon_{ti} \text{ is finite}\right] \prod_{k} \mathbb{1}\left[B_{tik} \text{ is finite}\right]\,, \\ \tilde{B}_{tik} &= \begin{cases} B_{tik} & \text{if } a_{ti} = 1\,, \\ 0 & \text{otherwise}\,, \end{cases} \\ \tilde{\varepsilon}_{ti} &= \begin{cases} \varepsilon_{ti} & \text{if } a_{ti} = 1\,, \\ 0 & \text{otherwise}\,. \end{cases} \end{align}\]

Where:

  • $a_{ti}$: Whether the pair of observation $t$ and asset $i$ is active.
  • $B_{tik}$, $\varepsilon_{ti}$: Entries of $\mathbf{B}_{t}$ and $\boldsymbol{\varepsilon}_{t}$. A static matrix is the same $\mathbf{B}_{t}$ at every observation.
  • $\tilde{B}_{tik}$, $\tilde{\varepsilon}_{ti}$: The returned exposure and idiosyncratic return.
  • $\mathbf{B}_{t}$: Exposure slice of observation $t$, $N \times K$, the exposures the factor returns of $t$ are read against.
  • $\boldsymbol{\varepsilon}_{t}$: Idiosyncratic returns of observation $t$, $N \times 1$.

Arguments

  • B: The static loadings, assets × factors, or the exposure history, assets × factors × observations.
  • eps: The idiosyncratic returns, observations × assets.

Validation

  • An exposure history carries the observations of eps, else a DimensionMismatch is raised.

Returns

  • za::ZeroedInactivePairs: The exposures B, zero at every inactive pair, the idiosyncratic returns eps, zero at every inactive pair, and the mask act of the active pairs, observations × assets. A static matrix stays static when its inactive pairs are whole assets.

Related

source
PortfolioOptimisers.attribution_trim_rows — Function
attribution_trim_rows(A::Nothing, rows)
attribution_trim_rows(A::MatNum, rows)

Return the rows of an optional per-observation history, or nothing.

The regression weights and the idiosyncratic variances are optional, so the absent case is a method rather than a test at the call site.

Arguments

  • A: The history, or nothing.
  • rows: The rows to keep.

Returns

  • A::Option{<:MatNum}: The kept rows, or nothing.

Related

source
PortfolioOptimisers.attribution_window — Function
attribution_window(al::AlignedAttributionBlock, rows)

Return the aligned history restricted to one rolling window.

The alignment runs once over the whole history, and a window is a slice of the aligned axis. Windowing before the alignment would spend the lag again inside every window.

Arguments

  • al: The aligned history.
  • rows: The rows of the aligned axis the window covers.

Returns

  • al::AlignedAttributionBlock: The aligned history over the window.

Related

source
PortfolioOptimisers.attribution_window_exposures — Function
attribution_window_exposures(B::MatNum, rows)
attribution_window_exposures(B::Arr3Num, rows)

Return the exposures of one rolling window.

A static loadings matrix describes every window, so it is returned unchanged.

Arguments

  • B: The static loadings, or the aligned exposure history.
  • rows: The rows the window covers.

Returns

  • B: The static loadings, or the exposures of the window.

Related

source
PortfolioOptimisers.attribution_window_weights — Function
attribution_window_weights(w::VecNum, rows)
attribution_window_weights(W::MatNum, rows)

Return the portfolio weights of one rolling window.

A constant weight describes every window, so it is returned unchanged.

Arguments

  • w: The constant weights, or the weight history.
  • rows: The rows the window covers.

Returns

  • w: The constant weights, or the weights of the window.

Related

source
PortfolioOptimisers.WeightMoments — Type
struct WeightMoments{__T_weight, __T_weight_std}

The mean weight of each asset over a realised attribution, and the spread of its history.

This type is an implementation detail and is not intended for direct use. attribution_weight_moments makes it, and realised_attribution passes it to the asset axis, where it fills the fields weight and weight_std of AssetAttributionBreakdown.

Fields

  • weight: weight: The mean weight of each asset.
  • weight_std: weight_std: The spread of the weight of each asset, zero for a constant weight.

Related

source
PortfolioOptimisers.attribution_weight_moments — Function
attribution_weight_moments(w::VecNum, ddof::Integer, T::Integer)
attribution_weight_moments(W::MatNum, ddof::Integer, T::Integer)

Return the mean weight of each asset and the spread of its history.

The portfolio exposure g_t = B_t' w_t is linear in the weights, so the weight spread takes the divisor of the exposure spread beside it, T - 1, by default. ddof = 0 gives the population spread. The library subtracts ddof itself. A constant weight does not move, so its spread is exactly zero.

Mathematical definition

\[\begin{align} \bar{w}_{i} &= \frac{1}{T} \sum_{t=1}^{T} w_{ti}\,, \\ s_{i} &= \sqrt{\frac{1}{T - d} \sum_{t=1}^{T} \left(w_{ti} - \bar{w}_{i}\right)^{2}}\,. \end{align}\]

Where:

  • $\bar{w}_{i}$, $s_{i}$: Mean weight and weight spread of asset $i$.
  • $d$: The degrees-of-freedom correction ddof.
  • $\boldsymbol{w}_{t}$: Portfolio weights held over observation $t$, $N \times 1$, with entry $w_{ti}$ for asset $i$. A constant weight vector is the same at every $t$.
  • $T$: Number of observations.

Arguments

  • w: The constant weights, or the weight history.
  • ddof: Degrees-of-freedom correction, an integer that the library subtracts from the number of observations itself.
  • T: The number of observations the weights describe.

Validation

  • 0 <= ddof < T, else a DomainError is raised.

Returns

  • wm::WeightMoments: The mean weight of each asset, weight, and the spread of each asset's weight, weight_std.

Related

source
PortfolioOptimisers.assert_attribution_ddof — Function
assert_attribution_ddof(ddof::Integer, T::Integer)

Refuse a degrees-of-freedom correction that leaves no observation to divide by.

The weight spread divides by T - ddof. A negative correction divides by more observations than the history holds, and a correction of T or more divides by zero or by a negative count.

Arguments

  • ddof: Degrees-of-freedom correction, an integer that the library subtracts from the number of observations itself.
  • T: The number of observations the weights describe.

Validation

  • 0 <= ddof < T, else a DomainError is raised.

Returns

  • Nothing is returned.

Related

source
PortfolioOptimisers.realised_attribution — Function
realised_attribution(W::VecNum_MatNum, ret::VecNum, al::AlignedAttributionBlock,
                     fam::Option{<:VecStr}, assets::Bool, se::Bool, ppy::Number,
                     wm::WeightMoments, unknown::AbstractUnknownEntryRule)
    -> FactorAttributionResult

Decompose one realised return series over the factors of an aligned factor model history.

Every realised method of factor_attribution, and every window of every rolling method, calls this function. It assumes the alignment is done, so it reads the exposures, the factor returns and the idiosyncratic returns as they stand.

Mathematical definition

The portfolio return splits into three series:

\[\begin{align} s_{t} &= \boldsymbol{g}_{t}^{\intercal} \boldsymbol{f}_{t} = \sum_{k=1}^{K} g_{tk} f_{tk}\,, \\ e_{t} &= \boldsymbol{w}_{t}^{\intercal} \boldsymbol{\varepsilon}_{t}\,, \\ u_{t} &= r_{t} - s_{t} - e_{t}\,. \end{align}\]

The systematic, the idiosyncratic and the unattributed components are $s$, $e$ and $u$, and each component is the five numbers of its series. The total is $r$ itself, so its volatility contribution is $\sqrt{p}\, \sigma_{P}$, its variance share is $1$ and its correlation is $1$. The three series sum to $r$, and the covariance is linear, so the three volatility contributions sum to the total and the three variance shares sum to $1$.

Row $k$ of the factor axis takes its numbers from the series $g_{\cdot k} f_{\cdot k}$. These series sum to $s$ over $k$, so the rows sum to the systematic component.

\[\begin{align} \bar{g}_{k} &= \frac{1}{T} \sum_{t=1}^{T} g_{tk}\,, \\ \mathrm{VC}_{k} &= \mathrm{VC}(g_{\cdot k} f_{\cdot k})\,, \\ \mathrm{PV}_{k} &= \mathrm{PV}(g_{\cdot k} f_{\cdot k})\,, \\ \mathrm{MC}_{k} &= \mathrm{MC}(g_{\cdot k} f_{\cdot k})\,, \\ \rho_{k} &= \frac{\operatorname{cov}(f_{\cdot k}, r)}{\operatorname{sd}(f_{\cdot k})\, \sigma_{P}}\,. \end{align}\]

The row also carries the exposure spread $\operatorname{sd}(g_{\cdot k})$, the factor volatility $\sqrt{p}\, \operatorname{sd}(f_{\cdot k})$ and the factor mean return $p\, \bar{f}_{k}$. The correlation $\rho_{k}$ is of the factor return and not of its contribution, and it is NaN when $\operatorname{sd}(f_{\cdot k})$ is zero.

Where:

  • $u_{t}$: Unattributed return of the portfolio at observation $t$.
  • $s_{t} = \boldsymbol{g}_{t}^{\intercal} \boldsymbol{f}_{t}$, $e_{t} = \boldsymbol{w}_{t}^{\intercal} \boldsymbol{\varepsilon}_{t}$: Systematic and idiosyncratic return of the portfolio at observation $t$.
  • $\bar{g}_{k}$, $\bar{f}_{k}$: Mean portfolio exposure to factor $k$, and mean return of factor $k$.
  • $\mathrm{VC}_{k}$, $\mathrm{PV}_{k}$, $\mathrm{MC}_{k}$, $\rho_{k}$: Volatility contribution, variance share, mean return contribution and correlation with the portfolio of factor $k$.
  • $\boldsymbol{g}_{t} = \mathbf{B}_{t}^{\intercal} \boldsymbol{w}_{t}$: Portfolio factor exposure of observation $t$, $K \times 1$, with entry $g_{tk}$ for factor $k$.
  • $\boldsymbol{f}_{t}$: Factor returns of observation $t$, $K \times 1$, with entry $f_{tk}$ for factor $k$.
  • $\boldsymbol{w}_{t}$: Portfolio weights held over observation $t$, $N \times 1$, with entry $w_{ti}$ for asset $i$. A constant weight vector is the same at every $t$.
  • $\boldsymbol{\varepsilon}_{t}$: Idiosyncratic returns of observation $t$, $N \times 1$.
  • $r_{t}$: Realised portfolio return of observation $t$, net of fees.
  • $\sigma_{P} = \operatorname{sd}(r)$: Realised portfolio volatility, the sample standard deviation of the portfolio returns.
  • $\mathrm{VC}(c)$, $\mathrm{PV}(c)$, $\mathrm{MC}(c)$, $\rho(c)$: Volatility contribution, variance share, mean return contribution and correlation with the portfolio of a return series $c$, as attribution_series_component states them.
  • $\operatorname{cov}(x, y)$, $\operatorname{sd}(x)$: Sample covariance of two series and sample standard deviation of one, over the $T$ observations and with the denominator $T - 1$.
  • $p$: Periods per year.
  • $K$: Number of factors.
  • $T$: Number of observations.

Algorithm

  1. Centre the portfolio series once, and take every covariance against it.
  2. Form the per-observation portfolio exposure g and the per-observation systematic and idiosyncratic series.
  3. Take each component's mean, volatility and covariance with the portfolio.
  4. Put the difference between the portfolio series and the model's reconstruction into the remainder. A difference that is constant within the round-off of its terms at every observation is that constant, by attribution_remainder, so a model that reconstructs the series exactly, or misses it by a constant, reports a remainder with no volatility and a NaN correlation, not a correlation of round-off.
  5. Sum the factor rows by family, and over the assets when assets = true.
  6. Scale by ppy.

Arguments

  • W: The constant weights, or the weight history.
  • ret: The net portfolio return series.
  • al: The aligned factor model history.
  • fam: The family label of each raw factor, or nothing.
  • assets: Whether to fill the asset axis and the asset-by-factor matrices.
  • se: Whether to fill the standard errors of the mean return contributions.
  • ppy: Periods per year the numbers are scaled to.
  • wm: The mean weight and the weight spread of each asset, from attribution_weight_moments.
  • unknown: Rule for an entry the factor model does not state, and for the variance split of a Leverage-One Pair, a subtype of AbstractUnknownEntryRule. EntrywiseUnknown gives NaN for every number that reads one, ZeroUnknown reads it as zero, and KindwiseUnknown applies one rule to each kind.

Validation

  • The portfolio volatility is positive, else a DomainError is raised.
  • ppy > 0, else a DomainError is raised.

Returns

  • fa::FactorAttributionResult: The attribution of the series.

Related

source
PortfolioOptimisers.attribution_remainder — Function
attribution_remainder(u::VecNum, mag::VecNum, n::Integer)

Return the unattributed series, or its mean at every observation when it is constant to working precision.

The remainder is a difference, r - s - e. When the model reconstructs the portfolio return exactly, the difference is zero in exact arithmetic and round-off in floating point. When it misses the return by a constant, a per-observation intercept or a fixed fee for example, the difference is that constant and round-off. The volatility of round-off is harmless next to the portfolio's, but its correlation with the portfolio is a ratio of two round-off numbers, which can take any value in [-1, 1] and states a relation the data does not hold. A difference whose deviation from its mean is inside the forward-error bound of its own sums, at every observation, is therefore the constant, with no volatility and a NaN correlation, as a series without variance has no correlation. A single observation outside the bound keeps the whole series, because a remainder with one real deviation has a real volatility.

The bound is relative to the size of the terms, so the test does not depend on the units of the returns.

Mathematical definition

\[\begin{align} m_{t} &= |r_{t}| + \sum_{i=1}^{N} \sum_{k=1}^{K} |w_{ti} B_{tik} f_{tk}| + \sum_{i=1}^{N} |w_{ti} \varepsilon_{ti}|\,, \\ \bar{u} &= \frac{1}{T} \sum_{t=1}^{T} u_{t}\,, \\ \tilde{u}_{t} &= \begin{cases} \bar{u} & \text{if } |u_{s} - \bar{u}| \le n\, \epsilon\, m_{s} \text{ for every } s\,, \\ u_{t} & \text{otherwise}\,. \end{cases} \end{align}\]

Where:

  • $u_{t}$: Unattributed return of the portfolio at observation $t$.
  • $\bar{u}$: Mean unattributed return.
  • $m_{t}$: Size of the terms whose sums form $u_{t}$.
  • $n$: Number of terms of the longest sum, N + K + 2: the exposure sums over the assets, the systematic sum over the factors, and the two subtractions.
  • $\epsilon$: Machine epsilon of the element type of $u$.
  • $\tilde{u}_{t}$: Returned unattributed return.
  • $r_{t}$: Realised portfolio return of observation $t$, net of fees.
  • $\boldsymbol{w}_{t}$: Portfolio weights held over observation $t$, $N \times 1$, with entry $w_{ti}$ for asset $i$. A constant weight vector is the same at every $t$.
  • $\boldsymbol{f}_{t}$: Factor returns of observation $t$, $K \times 1$, with entry $f_{tk}$ for factor $k$.
  • $\boldsymbol{\varepsilon}_{t}$: Idiosyncratic returns of observation $t$, $N \times 1$.
  • $\mathbf{B}_{t}$: Exposure slice of observation $t$, $N \times K$, the exposures the factor returns of $t$ are read against.
  • $N$: Number of assets.
  • $K$: Number of factors.

Arguments

  • u: The unattributed series.
  • mag: The size of the terms at each observation.
  • n: The number of terms of the longest sum.

Returns

  • u::VecNum: The unattributed series, or its mean at every observation.

Related

source
PortfolioOptimisers.attribution_series_component — Function
attribution_series_component(pnl::VecNum, retc::VecNum, total_vol::Number,
                             sc::AnnualisationScale, mu_se) -> AttributionComponent

Return one component of a realised attribution from its own return series.

The systematic, the idiosyncratic and the unattributed series are decomposed alike, so one verb builds all three. The volatility contribution is the covariance with the portfolio over the portfolio volatility, which is what makes the three sum to the portfolio volatility exactly.

Mathematical definition

\[\begin{align} \mathrm{vol}(c) &= \sqrt{p}\, \operatorname{sd}(c)\,, \\ \mathrm{VC}(c) &= \sqrt{p}\, \frac{\operatorname{cov}(c, r)}{\sigma_{P}}\,, \\ \mathrm{PV}(c) &= \frac{\operatorname{cov}(c, r)}{\sigma_{P}^{2}}\,, \\ \mathrm{MC}(c) &= \frac{p}{T} \sum_{t=1}^{T} c_{t}\,, \\ \rho(c) &= \frac{\operatorname{cov}(c, r)}{\operatorname{sd}(c)\, \sigma_{P}}\,. \end{align}\]

$\rho(c)$ is NaN when $\operatorname{sd}(c)$ is zero. A series whose entries are all equal has a volatility and a covariance of exactly zero: the sample formulas would give round-off, because the mean of equal floating-point numbers need not equal them. For series that sum to $r$, the covariances sum to $\sigma_{P}^{2}$, so the volatility contributions sum to $\sqrt{p}\, \sigma_{P}$ and the variance shares sum to $1$.

Where:

  • $c_{t}$: Return of the series at observation $t$.
  • $\mathrm{vol}(c)$: Standalone volatility of the series.
  • $\mathrm{VC}(c)$, $\mathrm{PV}(c)$, $\mathrm{MC}(c)$, $\rho(c)$: Volatility contribution, variance share, mean return contribution and correlation with the portfolio of a return series $c$, as attribution_series_component states them.
  • $r_{t}$: Realised portfolio return of observation $t$, net of fees.
  • $\sigma_{P} = \operatorname{sd}(r)$: Realised portfolio volatility, the sample standard deviation of the portfolio returns.
  • $\operatorname{cov}(x, y)$, $\operatorname{sd}(x)$: Sample covariance of two series and sample standard deviation of one, over the $T$ observations and with the denominator $T - 1$.
  • $p$: Periods per year.
  • $T$: Number of observations.

Arguments

  • pnl: The component's own return series.
  • retc: The centred portfolio return series.
  • total_vol: The portfolio volatility.
  • sc: The two annualisation factors.
  • mu_se: The standard error of the mean return contribution, or nothing.

Returns

  • c::AttributionComponent: The component.

Related

source
PortfolioOptimisers.attribution_family_spread — Function
attribution_family_spread(fam::Nothing, g::MatNum)
attribution_family_spread(fam::VecStr, g::MatNum)

Return the spread of each family's portfolio exposure over the observations.

A family's exposure is the sum of the exposures of its factors, so its spread is the spread of that sum and not the sum of the spreads.

Mathematical definition

\[\begin{align} s_{\mathcal{F}} &= \operatorname{sd}\left(\sum_{k \in \mathcal{F}} g_{\cdot k}\right)\,. \end{align}\]

Where:

  • $s_{\mathcal{F}}$: Exposure spread of the family.
  • $\mathcal{F}$: Raw factors of one family.
  • $\boldsymbol{g}_{t} = \mathbf{B}_{t}^{\intercal} \boldsymbol{w}_{t}$: Portfolio factor exposure of observation $t$, $K \times 1$, with entry $g_{tk}$ for factor $k$.
  • $\operatorname{cov}(x, y)$, $\operatorname{sd}(x)$: Sample covariance of two series and sample standard deviation of one, over the $T$ observations and with the denominator $T - 1$.

Arguments

  • fam: The family label of each raw factor, or nothing.
  • g: The per-observation portfolio exposure, observations × factors.

Returns

  • exposure_std::Option{<:VecNum}: The spread of each family's exposure, or nothing.

Related

source
PortfolioOptimisers.attribution_standard_errors — Function
attribution_standard_errors(g::MatNum, al::AlignedAttributionBlock, fam::Option{<:VecStr},
                            s1::Number, T::Integer, rule::AbstractUnknownEntryRule)
    -> AttributionErrorsResult

Return the standard errors of the mean return contributions of a realised attribution.

The cross-sectional fit estimates the factor returns of every observation, and that estimation error propagates into every mean return contribution. The error is the sandwich covariance of the fit, summed over the observations through the portfolio's own exposure.

Under a family re-basis the raw Gram matrix is singular by construction, so the sandwich is taken in the reduced full-rank basis and mapped back onto the raw axis for the per-factor and per-family answers. The systematic answer is invariant under the change of basis, so it is read in the reduced basis directly.

The systematic and the idiosyncratic errors are equal. The portfolio return is observed, so the two estimation errors sum to zero.

An Unseen Member changes the design. At an observation with an Unseen Member, the fit regressed on the reduced exposures times a change $\mathbf{P}_{t}$, and the factor returns are $\mathbf{P}_{t}$ times its coefficients. So the sandwich is taken on the changed design, and attribution_changed_covariance maps it to $\mathbf{P}_{t} \mathbf{V}_{t} \mathbf{P}_{t}^{\intercal}$. The standard errors then do not depend on the member that the family drops, and an Unseen Member has an error of zero, because the rule states its return.

An unknown variance makes the error unknown. The sandwich of an observation reads the idiosyncratic variance of every active pair with a non-zero regression weight. Where the block states no such variance, in the warm-up of the variance estimate for example, $\mathbf{V}_{t}$ is unknown, and every answer that sums over the observation is NaN. A zero variance would understate the error, and dropping the pair would give the covariance of a regression the fit did not run. A window after the warm-up, or a variance estimate with a shorter warm-up, states every entry. A pair outside the regression, or inactive, reads no variance.

A Leverage-One Pair makes the error unknown where the sandwich reads it. The fit reproduces the return of a marked pair, so the variance of the pair is not identified, and the plug-in variance of the block is one of many values that fit the data. Under EntrywiseUnknown every answer whose sandwich gives a marked pair of the regression a coefficient that is not zero is NaN, through attribution_leverage_errors. The pair stays in the sandwich. ZeroUnknown reads the plug-in variance, which is the answer of the oracle. One reduction, attribution_error_pass, gives the answer and the two indicator sums of the test.

Mathematical definition

\[\begin{align} \mathrm{SE} &= \frac{p}{T} \sqrt{\sum_{t=1}^{T} \boldsymbol{g}_{t}^{\intercal} \mathbf{V}_{t} \boldsymbol{g}_{t}}\,, \\ \mathrm{SE}_{k} &= \frac{p}{T} \sqrt{\sum_{t=1}^{T} g_{tk}^{2}\, V_{t,kk}}\,. \end{align}\]

attribution_sandwich states $\mathbf{V}_{t}$. The systematic error $\mathrm{SE}$ is the error of the mean of $s_{t} = \boldsymbol{g}_{t}^{\intercal} \hat{\boldsymbol{f}}_{t}$, with the estimation errors of two observations taken as independent. An observed factor, a Currency Factor for example, is not estimated, so its row and its column of $\mathbf{V}_{t}$ are zero, and $\mathrm{SE}_{k}$ of such a factor is NaN. The observed factors are the last al.no factors of both axes.

Where:

  • $\mathrm{SE}$, $\mathrm{SE}_{k}$: Standard error of the systematic mean return contribution, and of the mean return contribution of factor $k$.
  • $\hat{\boldsymbol{f}}_{t}$: Factor returns the cross-sectional fit estimates at observation $t$.
  • $V_{t,kk}$: Diagonal entry $k$ of $\mathbf{V}_{t}$.
  • $\boldsymbol{g}_{t} = \mathbf{B}_{t}^{\intercal} \boldsymbol{w}_{t}$: Portfolio factor exposure of observation $t$, $K \times 1$, with entry $g_{tk}$ for factor $k$.
  • $\mathbf{V}_{t}$: Sandwich covariance of the factor returns the cross-sectional fit estimates at observation $t$, $K \times K$.
  • $p$: Periods per year.
  • $T$: Number of observations.

Arguments

  • g: The per-observation portfolio exposure on the raw axis, observations × factors.
  • al: The aligned factor model history.
  • fam: The family label of each raw factor, or nothing.
  • s1: The factor a mean takes under the annualisation.
  • T: The number of aligned observations.
  • rule: The rule for the variance of a Leverage-One Pair, the leverage kind of the rule of the attribution.

Validation

  • al.rw and al.vs are not nothing, else an IsNothingError names the field.

Returns

  • ses::AttributionErrorsResult: The standard error sys of the systematic mean return contribution, the standard error factor of each factor's mean return contribution, and the standard error family of each family's, or nothing.

Related

source
PortfolioOptimisers.attribution_observed_indices — Function
attribution_observed_indices(
    no::Integer,
    K::Integer
) -> UnitRange{Int64}

Return the factors of an axis whose returns are observed, which are its last no factors.

An observed factor, a Currency Factor for example, is a direct return rather than a coefficient the cross-sectional fit estimates, so the sandwich covariance says nothing about it. A CrossSectionalFactorModel puts its observed factors after the estimated ones on the raw axis and on the reduced axis, and states their count through fx, so their position is the whole answer.

Arguments

Returns

  • obs::UnitRange{Int}: The positions of the observed factors on the axis.

Related

source
PortfolioOptimisers.ErrorRegressionBasis — Type
struct ErrorRegressionBasis{__T_B, __T_g, __T_observed, __T_nr, __T_P}

The regression basis that the sandwich covariance of a realised attribution is taken in.

This type is an implementation detail and is not intended for direct use. attribution_reduce_for_errors makes it, and attribution_standard_errors and attribution_error_pass read it.

Fields

  • B: B: The exposures of the regression basis, one slice per observation.
  • g: g: The portfolio exposure in the regression basis.
  • observed: observed: Whether each column of the regression basis is an observed factor.
  • nr: nr: The number of columns of the regression basis.

Related

source
PortfolioOptimisers.attribution_reduce_for_errors — Function
attribution_reduce_for_errors(fcb::Nothing, rule::AbstractUnseenMemberRule, B,
                              rw::MatNum, g::MatNum, no::Integer, T::Integer)
attribution_reduce_for_errors(fcb::FactorFamilyBasis, rule::AbstractUnseenMemberRule, B,
                              rw::MatNum, g::MatNum, no::Integer, T::Integer)

Return the exposures and the portfolio exposure the sandwich covariance is taken in.

A block that constrains no family is regressed on its raw axis, and the function returns the two inputs unchanged. A block that constrains a family has a singular raw Gram matrix, so the sandwich is taken in the reduced full-rank basis. At an observation with an Unseen Member, the fit regressed on a changed design, so the function changes the reduced exposures with unseen_member_design under the rule of the block, on the pairs of positive regression weight.

Arguments

  • fcb: The family re-basis, or nothing.
  • rule: The Unseen Member rule of the block.
  • B: The static loadings, or the aligned exposure history.
  • rw: The aligned regression weights.
  • g: The per-observation portfolio exposure on the raw axis.
  • no: The number of observed factors, the last columns of both axes.
  • T: The number of aligned observations.

Returns

  • red::ErrorRegressionBasis: The exposures B of the regression basis, one slice per observation, the portfolio exposure g in the regression basis, whether each column is an observed factor in observed, the number nr of columns, and the t => P_t pairs P of unseen_member_design.

Related

source
PortfolioOptimisers.attribution_broadcast_exposures — Function
attribution_broadcast_exposures(B::MatNum, T::Integer)
attribution_broadcast_exposures(B::Arr3Num, T::Integer)

Return an exposure history of T slices, repeating a static loadings matrix.

The sandwich covariance runs per observation, and the basis transforms it reads take a history, so a static block is repeated once here rather than branched at every use.

Arguments

  • B: The static loadings, or the aligned exposure history.
  • T: The number of aligned observations.

Returns

  • Ms::Arr3Num: The exposure history, assets × factors × observations.

Related

source
PortfolioOptimisers.attribution_sandwich — Function
attribution_sandwich(Bt::MatNum, q::VecNum, s2::VecNum, keep::AbstractVector{<:Integer})

Return the sandwich covariance of the factor returns of one observation.

The fit of one observation is a weighted least squares across the assets, so the covariance of its coefficients is the sandwich of the Gram matrix around the weighted idiosyncratic variances. A rank-deficient design falls back to the pseudo-inverse, which is the policy PseudoInverseFallback states, so the standard errors of a collinear cross-section are the minimum-norm answer rather than an arbitrarily large one.

The verb reads the weighted design $\mathbf{D}_{t}$ of the pairs of positive weight rather than its Gram matrix, and takes its rank with cross_sectional_rank, the rank test of the fit. A Gram matrix formed in floating point squares the condition number, so on a design whose condition number exceeds about $10^{8}$ its rank test would drop a direction that the fit kept, and truncate the sandwich of a factor that the fit estimated.

Mathematical definition

\[\begin{align} \mathbf{G}_{t} &= \mathbf{B}_{t}^{\intercal} \mathbf{Q}_{t} \mathbf{B}_{t} = \mathbf{D}_{t}^{\intercal} \mathbf{D}_{t}\,, \quad \mathbf{D}_{t} = \mathbf{Q}_{t}^{1/2} \mathbf{B}_{t}\,, \\ \mathbf{V}_{t} &= \mathbf{G}_{t}^{+} \mathbf{B}_{t}^{\intercal} \mathbf{Q}_{t} \boldsymbol{\Omega}_{t} \mathbf{Q}_{t} \mathbf{B}_{t} \mathbf{G}_{t}^{+} = \mathbf{D}_{t}^{+} \mathbf{Q}_{t} \boldsymbol{\Omega}_{t} \left(\mathbf{D}_{t}^{+}\right)^{\intercal}\,. \end{align}\]

$\mathbf{B}_{t}$ here holds the columns of the estimated factors alone. $\mathbf{D}_{t}^{+}$ is the pseudo-inverse of $\mathbf{D}_{t}$ over its first $r_{t}$ singular directions, where $r_{t}$ is the rank that cross_sectional_rank reads. It equals $\mathbf{G}_{t}^{+} \mathbf{D}_{t}^{\intercal}$, so the two forms agree, and it is $\mathbf{G}_{t}^{-1} \mathbf{D}_{t}^{\intercal}$ on a design of full rank.

Where:

  • $\mathbf{G}_{t}$: Gram matrix of the weighted cross-sectional fit of observation $t$.
  • $\mathbf{G}_{t}^{+}$: Pseudo-inverse of $\mathbf{G}_{t}$.
  • $\mathbf{D}_{t}$: Weighted design of observation $t$, over the pairs of positive weight.
  • $\mathbf{B}_{t}$: Exposure slice of observation $t$, $N \times K$, the exposures the factor returns of $t$ are read against.
  • $\mathbf{Q}_{t}$: Regression weight matrix of observation $t$, diagonal, holding the cross-sectional weight of each asset.
  • $\boldsymbol{\Omega}_{t}$: Idiosyncratic variance matrix of observation $t$, diagonal, holding the idiosyncratic variance of each asset.
  • $\mathbf{V}_{t}$: Sandwich covariance of the factor returns the cross-sectional fit estimates at observation $t$, $K \times K$.

Arguments

  • Bt: The exposures of the observation, assets × factors.
  • q: The regression weight of each asset at the observation.
  • s2: The idiosyncratic variance of each asset at the observation.
  • keep: The factors the regression estimates.

Returns

  • V::MatNum: The covariance of the estimated factor returns.

Related

source
PortfolioOptimisers.attribution_changed_covariance — Function
attribution_changed_covariance(Pt::Nothing, V::MatNum, keep::AbstractVector{<:Integer})
attribution_changed_covariance(Pt::AbstractMatrix, V::MatNum,
                               keep::AbstractVector{<:Integer})

Return the sandwich covariance of one observation on the factor returns, mapped by the change of an observation with an Unseen Member.

The fit of such an observation regressed on the reduced exposures times $\mathbf{P}_{t}$, and its factor returns are $\mathbf{P}_{t}$ times the coefficients. attribution_sandwich states the covariance of the coefficients, so the covariance of the factor returns is $\mathbf{P}_{t} \mathbf{V}_{t} \mathbf{P}_{t}^{\intercal}$. The observed factors are not in a family, so the block of $\mathbf{P}_{t}$ on the estimated factors is the whole change. A zero row of $\mathbf{P}_{t}$, an Unseen Member, gives a zero row and a zero column. An observation without a change keeps V.

Arguments

  • Pt: The change of the observation from unseen_member_design, or nothing.
  • V: The covariance of the coefficients over the estimated factors, from attribution_sandwich.
  • keep: The factors the regression estimates.

Returns

  • V::MatNum: The covariance of the estimated factor returns.

Related

source
PortfolioOptimisers.attribution_dropped_observation — Function
attribution_dropped_observation(dc::Nothing, Bt::MatNum, Pt::Option{<:AbstractMatrix},
                                keep::AbstractVector{<:Integer}, nr::Integer,
                                t::Integer) -> ChangedDesign
attribution_dropped_observation(dc::AbstractMatrix{Bool}, Bt::MatNum,
                                Pt::Option{<:AbstractMatrix},
                                keep::AbstractVector{<:Integer}, nr::Integer,
                                t::Integer) -> ChangedDesign

Return the exposures and the change of one observation after the columns that its fit dropped.

Under DependentColumnDrop the fit solved the kept columns and gave each dropped factor a return of zero by the rule. So the function zeroes the dropped columns of the exposures, and composes the change of the observation with the selection of the kept columns through cs_dropped_change. attribution_sandwich then reads the kept columns, and attribution_changed_covariance gives a dropped factor a zero row and a zero column, as it gives an Unseen Member.

Arguments

  • dc: The dropped-column mask, observations × estimated factors, or nothing.
  • Bt: The exposures of the observation in the regression basis, assets × factors.
  • Pt: The change of the observation, or nothing.
  • keep: The factors the regression estimates, one per column of dc.
  • nr: The number of columns of the regression basis.
  • t: The observation.

Returns

  • ob::ChangedDesign: The exposures and the change, Bt and Pt themselves when the observation drops nothing.

Related

source
PortfolioOptimisers.attribution_scatter — Function
attribution_scatter(V::AbstractVector{<:MatNum}, keep, nr::Integer)

Return the covariance of each observation over a subset of factors, placed into a zero stack of the full axis.

A factor the regression does not estimate carries no estimation uncertainty, so its row and its column are zero rather than absent.

Arguments

  • V: The covariance over the estimated factors, one matrix per observation.
  • keep: The factors the regression estimates.
  • nr: The number of factors of the full axis.

Returns

  • S::Arr3Num: The covariance of each observation on the full axis, factors × factors × observations.

Related

source
PortfolioOptimisers.attribution_family_errors — Function
attribution_family_errors(fam::Nothing, g::MatNum, Vf::Arr3Num, s1::Number, T::Integer,
                          obs::AbstractVector{<:Integer})
attribution_family_errors(fam::VecStr, g::MatNum, Vf::Arr3Num, s1::Number, T::Integer,
                          obs::AbstractVector{<:Integer})

Return the standard error of each family's mean return contribution.

A family's contribution sums the contributions of its factors, so its error reads the full covariance block of the family rather than the diagonal alone. A family of observed factors reports NaN, because its rows carry no regression-estimation uncertainty.

Mathematical definition

\[\begin{align} \mathrm{SE}_{\mathcal{F}} &= \frac{p}{T} \sqrt{\sum_{t=1}^{T} \boldsymbol{g}_{t,\mathcal{F}}^{\intercal} \mathbf{V}_{t,\mathcal{F}\mathcal{F}}\, \boldsymbol{g}_{t,\mathcal{F}}}\,. \end{align}\]

Where:

  • $\mathrm{SE}_{\mathcal{F}}$: Standard error of the mean return contribution of the family.
  • $\boldsymbol{g}_{t,\mathcal{F}}$, $\mathbf{V}_{t,\mathcal{F}\mathcal{F}}$: The entries of $\boldsymbol{g}_{t}$, and the block of $\mathbf{V}_{t}$, that the factors of the family index.
  • $\mathcal{F}$: Raw factors of one family.
  • $\boldsymbol{g}_{t} = \mathbf{B}_{t}^{\intercal} \boldsymbol{w}_{t}$: Portfolio factor exposure of observation $t$, $K \times 1$, with entry $g_{tk}$ for factor $k$.
  • $\mathbf{V}_{t}$: Sandwich covariance of the factor returns the cross-sectional fit estimates at observation $t$, $K \times K$.
  • $p$: Periods per year.
  • $T$: Number of observations.

Arguments

  • fam: The family label of each raw factor, or nothing.
  • g: The per-observation portfolio exposure on the raw axis.
  • Vf: The sandwich covariance of each observation, on the raw axis, factors × factors × observations.
  • s1: The factor a mean takes under the annualisation.
  • T: The number of aligned observations.
  • obs: The raw factors that are observed, from attribution_observed_indices.

Returns

  • family::Option{<:VecNum}: The standard error of each family, or nothing.

Related

source
PortfolioOptimisers.realised_attribution_assets — Function
realised_attribution_assets(assets::Bool, W::VecNum_MatNum, al::AlignedAttributionBlock,
                            sysr::MatNum, ret::VecNum, total_vol::Number,
                            sc::AnnualisationScale, wm::WeightMoments,
                            unknown::AbstractUnknownEntryRule)

Return the asset axis and the asset-by-factor matrices of a realised attribution.

Each asset's systematic and idiosyncratic contributions are the covariances of its own weighted series with the portfolio, so the rows sum to their components exactly. The axis decomposes the model, so vol_contrib is the two parts together, and the rows sum to the systematic and idiosyncratic components together and not to the total. The remainder belongs to the portfolio and has no split over the assets. The asset-by-factor matrices split the systematic row of each asset over the factors.

Mathematical definition

The model return of asset $i$ is the sum of its systematic and idiosyncratic returns.

\[\begin{align} a_{ti} &= s_{ti} + \varepsilon_{ti}\,. \end{align}\]

The systematic row of asset $i$ is $\mathrm{VC}$ and $\mathrm{MC}$ of $w_{\cdot i} s_{\cdot i}$, and the idiosyncratic row is the same two numbers of $w_{\cdot i} \varepsilon_{\cdot i}$. The total row is $\mathrm{VC}$, $\mathrm{PV}$ and $\mathrm{MC}$ of $w_{\cdot i} a_{\cdot i}$. The weighted series of all the assets sum to $s_{t}$ and $e_{t}$, so the rows sum to the two components. An inactive pair is zero in both series, so it adds nothing to a row.

The standalone numbers are those of the model return, which holds no per-observation intercept. Under EntrywiseUnknown they read the active pairs of the asset alone. An asset has no return at an inactive pair: it was not listed, or it was on a holiday, which carries no information. A zero there would state a return the asset never had, and dilute its mean by the observations it was absent. An asset with fewer than two active pairs has no standalone volatility and no correlation, and one with none has no mean. Under ZeroUnknown they read every observation, with the zero return of each inactive pair, through attribution_standalone_pairs.

\[\begin{align} \mathrm{vol}_{i} &= \sqrt{p}\, \operatorname{sd}_{t \in \mathcal{A}_{i}}(a_{ti})\,, \\ \mu_{i} &= \frac{p}{|\mathcal{A}_{i}|} \sum_{t \in \mathcal{A}_{i}} a_{ti}\,, \\ \rho_{i} &= \frac{\operatorname{cov}_{t \in \mathcal{A}_{i}}(a_{ti}, r_{t})}{\operatorname{sd}_{t \in \mathcal{A}_{i}}(a_{ti})\, \operatorname{sd}_{t \in \mathcal{A}_{i}}(r_{t})}\,. \end{align}\]

Where:

  • $\varepsilon_{ti}$, $a_{ti}$: Idiosyncratic and model return of asset $i$ at observation $t$.
  • $\mathcal{A}_{i}$: Observations at which asset $i$ is active, from attribution_zero_inactive, or every observation under ZeroUnknown. When it holds every observation, the correlation divides by $\sigma_{P}$.
  • $s_{ti} = (\mathbf{B}_{t} \boldsymbol{f}_{t})_{i}$: Systematic return of asset $i$ at observation $t$.
  • $s_{t} = \boldsymbol{g}_{t}^{\intercal} \boldsymbol{f}_{t}$, $e_{t} = \boldsymbol{w}_{t}^{\intercal} \boldsymbol{\varepsilon}_{t}$: Systematic and idiosyncratic return of the portfolio at observation $t$.
  • $\mathrm{vol}_{i}$, $\mu_{i}$, $\rho_{i}$: Standalone volatility, mean return and correlation with the portfolio of asset $i$.
  • $\mathbf{B}_{t}$: Exposure slice of observation $t$, $N \times K$, the exposures the factor returns of $t$ are read against.
  • $\boldsymbol{f}_{t}$: Factor returns of observation $t$, $K \times 1$, with entry $f_{tk}$ for factor $k$.
  • $\boldsymbol{\varepsilon}_{t}$: Idiosyncratic returns of observation $t$, $N \times 1$.
  • $\boldsymbol{w}_{t}$: Portfolio weights held over observation $t$, $N \times 1$, with entry $w_{ti}$ for asset $i$. A constant weight vector is the same at every $t$.
  • $r_{t}$: Realised portfolio return of observation $t$, net of fees.
  • $\sigma_{P} = \operatorname{sd}(r)$: Realised portfolio volatility, the sample standard deviation of the portfolio returns.
  • $\mathrm{VC}(c)$, $\mathrm{PV}(c)$, $\mathrm{MC}(c)$, $\rho(c)$: Volatility contribution, variance share, mean return contribution and correlation with the portfolio of a return series $c$, as attribution_series_component states them.
  • $\operatorname{cov}(x, y)$, $\operatorname{sd}(x)$: Sample covariance of two series and sample standard deviation of one, over the $T$ observations and with the denominator $T - 1$.
  • $p$: Periods per year.
  • $T$: Number of observations.

Arguments

  • assets: Whether to compute the two answers at all.
  • W: The constant weights, or the weight history.
  • al: The aligned factor model history.
  • sysr: The per-observation systematic return of each asset.
  • ret: The portfolio return series.
  • total_vol: The portfolio volatility.
  • sc: The two annualisation factors.
  • wm: The mean weight and the weight spread of each asset, from attribution_weight_moments.
  • unknown: Rule for an entry the factor model does not state, and for the variance split of a Leverage-One Pair, a subtype of AbstractUnknownEntryRule. EntrywiseUnknown gives NaN for every number that reads one, ZeroUnknown reads it as zero, and KindwiseUnknown applies one rule to each kind.

Returns

  • abd::Option{<:AssetAttributionBreakdown}: The asset axis, or nothing.
  • afc::Option{<:AssetFactorContribution}: The asset-by-factor matrices, or nothing.

Related

source
PortfolioOptimisers.realised_attribution_asset_factor — Function
realised_attribution_asset_factor(W::VecNum_MatNum, al::AlignedAttributionBlock, retc::VecNum,
                                  total_vol::Number, sc::AnnualisationScale, T::Integer,
                                  N::Integer, K::Integer) -> AssetFactorContribution

Return the asset-by-factor contributions of a realised attribution.

Each pair of an asset and a factor is one term of the systematic return, so a row of the matrices sums to the asset's systematic row and a column sums to the factor's row.

Mathematical definition

\[\begin{align} c^{(ik)}_{t} &= w_{ti}\, B_{t,ik}\, f_{tk}\,, \\ \mathrm{VC}_{ik} &= \mathrm{VC}(c^{(ik)})\,, \\ \mathrm{MC}_{ik} &= \mathrm{MC}(c^{(ik)})\,. \end{align}\]

$\sum_{k} c^{(ik)}_{t} = w_{ti} s_{ti}$ and $\sum_{i} c^{(ik)}_{t} = g_{tk} f_{tk}$, and both numbers are linear in the series.

Where:

  • $c^{(ik)}_{t}$: Return of the pair of asset $i$ and factor $k$ at observation $t$.
  • $B_{t,ik}$: Entry $(i, k)$ of $\mathbf{B}_{t}$.
  • $s_{ti} = (\mathbf{B}_{t} \boldsymbol{f}_{t})_{i}$: Systematic return of asset $i$ at observation $t$.
  • $\mathrm{VC}_{ik}$, $\mathrm{MC}_{ik}$: Volatility contribution and mean return contribution of the pair.
  • $\mathbf{B}_{t}$: Exposure slice of observation $t$, $N \times K$, the exposures the factor returns of $t$ are read against.
  • $\boldsymbol{w}_{t}$: Portfolio weights held over observation $t$, $N \times 1$, with entry $w_{ti}$ for asset $i$. A constant weight vector is the same at every $t$.
  • $\boldsymbol{g}_{t} = \mathbf{B}_{t}^{\intercal} \boldsymbol{w}_{t}$: Portfolio factor exposure of observation $t$, $K \times 1$, with entry $g_{tk}$ for factor $k$.
  • $\boldsymbol{f}_{t}$: Factor returns of observation $t$, $K \times 1$, with entry $f_{tk}$ for factor $k$.
  • $\mathrm{VC}(c)$, $\mathrm{PV}(c)$, $\mathrm{MC}(c)$, $\rho(c)$: Volatility contribution, variance share, mean return contribution and correlation with the portfolio of a return series $c$, as attribution_series_component states them.

Arguments

  • W: The constant weights, or the weight history.
  • al: The aligned factor model history.
  • retc: The centred portfolio return series.
  • total_vol: The portfolio volatility.
  • sc: The two annualisation factors.
  • T: The number of aligned observations.
  • N: The number of assets.
  • K: The number of raw factors.

Returns

  • afc::AssetFactorContribution: The two asset-by-factor matrices.

Related

source
PortfolioOptimisers.attribution_rolling — Function
attribution_rolling(W::VecNum_MatNum, ret::VecNum, al::AlignedAttributionBlock, fam, assets::Bool,
                    se::Bool, ppy::Number, window::Integer, step::Integer,
                    ddof::Integer, unknown::AbstractUnknownEntryRule)
    -> Vector{<:FactorAttributionResult}

Roll a realised attribution over the windows of an aligned history.

The alignment runs once over the whole history, and each window is a slice of the aligned axis, so a window carries window effective observations and spends the exposure lag once rather than once per window.

Mathematical definition

\[\begin{align} \mathcal{W}_{j} &= \{\tau_{j} - m + 1, \ldots, \tau_{j}\}\,, \\ \tau_{j} &= m + (j - 1)\, h\,, \quad j = 1, \ldots, \left\lfloor \frac{T - m}{h} \right\rfloor + 1\,. \end{align}\]

Attribution $j$ is the realised attribution over the observations of $\mathcal{W}_{j}$. Two windows that share observations are not independent.

Where:

  • $\mathcal{W}_{j}$, $\tau_{j}$: Observations of window $j$, and its last observation.
  • $m$: Size of the window, window.
  • $h$: Stride between two consecutive windows, step.
  • $T$: Number of observations.

Arguments

  • W: The constant weights, or the weight history.
  • ret: The net portfolio return series, already aligned.
  • al: The aligned factor model history.
  • fam: The family label of each raw factor, or nothing.
  • assets: Whether to fill the asset axis and the asset-by-factor matrices.
  • se: Whether to fill the standard errors of the mean return contributions.
  • ppy: Periods per year the numbers are scaled to.
  • window: Size of the rolling window, in observations.
  • step: Stride between two consecutive windows.
  • ddof: Degrees-of-freedom correction, an integer that the library subtracts from the number of observations itself.
  • unknown: Rule for an entry the factor model does not state, and for the variance split of a Leverage-One Pair, a subtype of AbstractUnknownEntryRule. EntrywiseUnknown gives NaN for every number that reads one, ZeroUnknown reads it as zero, and KindwiseUnknown applies one rule to each kind.

Validation

  • 2 <= window <= T, else a DomainError is raised. A window of one observation has no sample volatility.
  • step >= 1, else a DomainError is raised.
  • 0 <= ddof < window, else a DomainError is raised.

Returns

  • fas::Vector{<:FactorAttributionResult}: One attribution per window.

Related

source
PortfolioOptimisers.attribution_finite_series — Function
attribution_finite_series(ret::VecNum)

Refuse a portfolio return series that carries a non-finite value, naming the observations.

The methods that form the series themselves route a non-finite return through attribution_net_returns, so a NaN that reaches here came in the caller's own series or in a fold's. It is refused before the alignment, so the observations named are the caller's and not the aligned window's, and the refusal names the cause rather than the undefined volatility that the value would give.

Arguments

  • ret: The net portfolio return series.

Validation

  • ret is finite throughout, else an IsNonFiniteError naming the observations is raised.

Returns

  • Nothing is returned.

Related

source
PortfolioOptimisers.attribution_realised_entry — Function
attribution_realised_entry(W::VecNum_MatNum, blk::AttributionBlock, ret::VecNum;
                           assets::Bool = false, se::Bool = false, ppy::Number = 1,
                           key::Option{<:AttributionRowKey} = nothing, ddof::Integer = 1,
                           unknown::AbstractUnknownEntryRule = EntrywiseUnknown())
    -> FactorAttributionResult

Align a factor model block against a realised return series and decompose it.

Every realised method of factor_attribution that is not rolling forms its net return series, its weights and the block as bare arrays, then calls this function. A prior method reads the bare arrays off the block with attribution_block_arrays, and the bare-array method builds them with attribution_array_block.

Algorithm

  1. Refuse a non-finite entry of ret through attribution_finite_series.
  2. Align blk against the length(ret) observations of the caller with attribution_key_align, by the row key key of ret when the block shares it, giving al.
  3. Take the mean weight and the weight spread over the rows al.rows with attribution_weight_moments.
  4. Decompose the rows al.rows of ret, and of W when it is a history, with realised_attribution.

Arguments

  • W: The constant weights, or the weight history.
  • blk: The block as bare arrays.
  • ret: The net portfolio return series.
  • assets: Whether to fill the asset axis and the asset-by-factor matrices.
  • se: Whether to fill the standard errors of the mean return contributions.
  • ppy: Periods per year the numbers are scaled to.
  • key: The position idx and the timestamp ts of each observation of ret, or nothing when ret names no row.
  • ddof: Degrees-of-freedom correction, an integer that the library subtracts from the number of observations itself.
  • unknown: Rule for an entry the factor model does not state, and for the variance split of a Leverage-One Pair, a subtype of AbstractUnknownEntryRule. EntrywiseUnknown gives NaN for every number that reads one, ZeroUnknown reads it as zero, and KindwiseUnknown applies one rule to each kind.

Validation

  • ret is finite throughout, else an IsNonFiniteError naming the observations is raised.
  • The rules of attribution_key_align.
  • 0 <= ddof < T over the aligned observations, else a DomainError is raised.
  • The portfolio volatility is positive, and ppy > 0, else a DomainError is raised.

Returns

  • fa::FactorAttributionResult: The attribution of the series.

Related

source
PortfolioOptimisers.attribution_rolling_entry — Function
attribution_rolling_entry(W::VecNum_MatNum, blk::AttributionBlock, ret::VecNum,
                          window::Integer; step::Integer = 1, assets::Bool = false,
                          se::Bool = false, ppy::Number = 1,
                          key::Option{<:AttributionRowKey} = nothing, ddof::Integer = 1,
                          unknown::AbstractUnknownEntryRule = EntrywiseUnknown())
    -> Vector{<:FactorAttributionResult}

Align a factor model block against a realised return series and roll the decomposition.

Every rolling method of factor_attribution forms its net return series, its weights and the block as bare arrays, then calls this function. A prior method reads the bare arrays off the block with attribution_block_arrays, and the bare-array method builds them with attribution_array_block.

Algorithm

  1. Refuse a non-finite entry of ret through attribution_finite_series.
  2. Align blk against the length(ret) observations of the caller with attribution_key_align, by the row key key of ret when the block shares it, giving al.
  3. Roll the decomposition over the windows of the rows al.rows with attribution_rolling, which checks window and step against the aligned length.

Arguments

  • W: The constant weights, or the weight history.
  • blk: The block as bare arrays.
  • ret: The net portfolio return series.
  • window: Size of the rolling window, in observations.
  • step: Stride between two consecutive windows.
  • assets: Whether to fill the asset axis and the asset-by-factor matrices.
  • se: Whether to fill the standard errors of the mean return contributions.
  • ppy: Periods per year the numbers are scaled to.
  • key: The position idx and the timestamp ts of each observation of ret, or nothing when ret names no row.
  • ddof: Degrees-of-freedom correction, an integer that the library subtracts from the number of observations itself.
  • unknown: Rule for an entry the factor model does not state, and for the variance split of a Leverage-One Pair, a subtype of AbstractUnknownEntryRule. EntrywiseUnknown gives NaN for every number that reads one, ZeroUnknown reads it as zero, and KindwiseUnknown applies one rule to each kind.

Validation

  • ret is finite throughout, else an IsNonFiniteError naming the observations is raised.
  • The rules of attribution_key_align.
  • The portfolio volatility is positive, and ppy > 0, else a DomainError is raised.
  • 2 <= window <= T over the aligned observations, else a DomainError is raised.
  • step >= 1, else a DomainError is raised.
  • 0 <= ddof < window, else a DomainError is raised.

Returns

  • fas::Vector{<:FactorAttributionResult}: One attribution per window.

Related

source