Expected Risk
PortfolioOptimisers.expected_risk — Function
expected_risk(r, args...; kwargs...)
expected_risk(sca::Option{<:Scalariser}, r, args...; kwargs...)Compute the expected value of a risk measure.
Generic function extended by concrete risk measure types. Each method computes the risk value associated with its risk measure type, given a portfolio (or its return distribution).
A vector of measures takes a Scalariser sca. The keyword form takes it as a keyword and calls the positional form, which takes it first. A single measure ignores it.
Related
PortfolioOptimisers.expected_risk_from_returns — Function
expected_risk_from_returns(r, X; kwargs...)
expected_risk_from_returns(sca::Option{<:Scalariser}, r, X; kwargs...)Compute the expected risk of a measure from a precomputed net-return series.
Generic function extended by concrete risk measure types that support the precomputed-returns contract. Only a measure with supports_precomputed_returns(r) == true implements a method. A vector of measures takes a Scalariser sca, as expected_risk does.
Related
PortfolioOptimisers.expected_risk_from_returns — Method
expected_risk_from_returns(r::AbstractBaseRiskMeasure, X::VecNum; kwargs...) -> NumberEvaluate a risk measure on a net return series that the caller already formed.
For a measure whose supports_precomputed_returns is true, the function returns r(X). For any other measure it raises an ArgumentError that says why. Without the check, a WeightsInput measure would read X as weights, and a moment measure with a per-asset mu would raise a MethodError that does not say what is wrong. The internal callers that hold a series, such as the scoring of a cross-validation prediction, call this function and not the functor.
The series X must be finite. The function does not check it, because every internal caller gives it a finite series, and the three ratio kernels call it for each half at every evaluation. On a series with gaps, a tail measure returns a finite wrong number and not a NaN. partialsort puts a NaN after every real number, so a CVaR reads its order statistic from the finite values and divides by the length of the whole series. Remove the gaps first with x[isfinite.(x)]. To score a panel with gaps, use predict(res::NonFiniteAllocationOptimisationResult, rd::ReturnsResult), which removes the Held Gaps once.
Arguments
r::AbstractBaseRiskMeasure: Risk measure.X::VecNum: Net portfolio return seriesobservations × 1.
Validation
- A measure whose
supports_precomputed_returnsisfalseraises anArgumentError.
Returns
rk::Number: The risk of the series.
Related
PortfolioOptimisers.expected_risk_from_returns — Method
expected_risk_from_returns(r::BaseRM_VecBaseRM, X::VecVecNum;
sca::Option{<:Scalariser} = nothing, kwargs...)
expected_risk_from_returns(sca::Option{<:Scalariser}, r::BaseRM_VecBaseRM, X::VecVecNum; kwargs...)Evaluate a risk measure on each series of a vector of net return series.
The method calls expected_risk_from_returns on each Xi in X, and returns one risk for each series. The keyword form takes sca out of the keywords and calls the positional form, which passes sca to each call.
Related
PortfolioOptimisers.number_effective_assets — Function
number_effective_assets(w::VecNum)Compute the effective number of assets of a portfolio, the participation ratio of its absolute weights.
The result is the number of assets of equal absolute weight that have the same concentration as w. It lies between 1, when one asset holds all of the exposure, and N, at equal absolute weights. The ratio does not change when the book is scaled, so it reads the concentration of the book and not its leverage. A book with one long and one short position of the same size gives 2, at any gross exposure. On weights whose absolute values sum to one, the ratio is the inverse of the Herfindahl-Hirschman index of the weights, $1 / \sum_{i} w_i^2$.
A book whose weights are all zero holds no asset, so the ratio is 0 / 0, a NaN.
Breaking: the function was $1 / \sum_{i} w_i^2$ on every book. That form gives 0.5 for the book [1.0, -1.0] and 2 for the same book at half the scale. The value moves on every book whose absolute weights do not sum to one, and only there.
Mathematical definition
\[\begin{align} N_{\mathrm{eff}} &= \frac{\left(\sum_{i=1}^{N} \lvert w_i \rvert\right)^{2}}{\sum_{i=1}^{N} w_i^2}\,. \end{align}\]
Where:
- $N_{\mathrm{eff}}$: Effective number of assets.
- $w_i$: Weight of asset $i$.
- $N$: Number of assets.
Arguments
w::VecNum: Portfolio weights vectorassets × 1.
Returns
neff::Number: Effective number of assets.
Examples
julia> number_effective_assets([0.5, 0.25, 0.25])2.6666666666666665julia> number_effective_assets([1.0, -1.0]) == number_effective_assets([0.5, -0.5]) == 2trueRelated
PortfolioOptimisers.risk_contribution — Function
risk_contribution(
r::BaseRM_VecBaseRM,
w::VecNum,
X::MatNum_Pr,
fees::Option{<:Fees} = nothing;
delta::Number = 1e-6,
marginal::Bool = false,
sca::Option{<:Scalariser} = nothing,
strict::Bool = false,
kwargs...
) -> VectorCompute the contribution of each asset to the risk of a portfolio with a finite difference.
The contributions sum to the risk that expected_risk reports, because the function divides the gradient of each measure by its degree of homogeneity. homogeneity_degree gives that degree. The sum holds only for a measure that is homogeneous of a degree other than zero. The contributions of a measure of degree 0, such as EqualRisk or Skewness, sum to zero. The contributions of a measure that is not homogeneous in the weights, such as a tracking error or a turnover against a target that is not zero, or a relative drawdown, do not sum to its risk. Such a measure has no degree, so its contributions are the plain marginal contributions. A fee that does not scale with the weights, such as a turnover fee against previous weights that are not zero or a fixed fee, also takes the degree from a measure that reads the net returns, unless the fee cancels from its risk. has_fixed_fee states the rule. A vector of measures decomposes its aggregate. The function corrects each element before the scalariser combines them, through adjusted_risk, so the contributions sum to the aggregate when the elements have different degrees. Under MaxScalariser and MinScalariser, the contributions are those of the element that the scalariser picks at w, and at a tie they are those of the earliest such element. Under LogSumExpScalariser, the contributions sum to the softmax-weighted mean of the scaled risks, which is below the aggregate.
A prior result reduces to the Investable Mask before the finite difference, so no perturbed weight meets a NaN moment, and a non-investable asset reports exactly 0. The prior also resolves the measure once, so a Deferred Quantity is fitted once and not once for each finite difference.
A measure whose value is a solve, of the entropic, the relativistic or the power norm family, solves its programme once at w, and the function takes the finite difference of the expected loss under the Worst-Case Distribution of that solve, from worst_case_distribution. By the envelope theorem, that expected loss has the gradient of the measure at w. A finite difference of the measure itself differences two solves, and the noise of the solver is as large as the change that the step makes, so its contributions can miss the risk by several percent. The contributions of the distribution sum to the risk to the tolerance of the solver, and the function solves one programme for each measure, not 2N. When no solver gives the distribution, the function takes the finite difference of the measure itself.
The contributions are those of the target weights. Under a Weight Drift the return series of a fold is not linear in one weight vector, so the contributions sum to the realised risk of the fold only to first order in the drift. A weight path holds no single vector for the finite difference to move.
Mathematical definition
\[\begin{align} \mathrm{RC}_i &= \frac{w_i}{d} \, \frac{\partial R(\boldsymbol{w})}{\partial w_i}\,, \\ \sum_{i=1}^{N} \mathrm{RC}_i &= R(\boldsymbol{w})\,. \end{align}\]
The second line is Euler's theorem for a measure that is homogeneous of degree $d$. With marginal = true the function returns $\partial R(\boldsymbol{w}) / \partial w_i$ divided by $d$, without the factor $w_i$.
Where:
- $\mathrm{RC}_i$: Risk contribution of asset $i$.
- $w_i$: Weight of asset $i$.
- $d$: Degree of homogeneity of the risk measure, the $d$ for which $R(c \boldsymbol{w}) = c^{d} R(\boldsymbol{w})$ at every $c > 0$.
- $R(\boldsymbol{w})$: Portfolio risk.
- $N$: Number of assets.
Algorithm
- Reduce
X,wandfeesto the Investable Mask withinvestable_reduction, which gives the maskimsk. - Resolve
rand the returns matrixXwithresolve_risk_inputs. - Compute the chain-rule weights
psof a vector of measures atwwithscalariser_element_weights. A single measure getsnothing. - Compute
qs, the Worst-Case Distribution of each measure atw, withelement_worst_case_distributions. - Compute
rc, the finite difference ofadjusted_riskatwwith the stepdelta, throughfinite_difference_gradient. - Unless
marginalistrue, multiplyrcbywelement by element. - Expand
rcto the full universe withexpand_investable_weights, with a zero for each non-investable asset.
Arguments
r: Risk measure or vector of risk measures.w::VecNum: Portfolio weights vectorassets × 1.X::MatNum_Pr: Returns matrix, prior result or returns result.fees: OptionalFeesstructure.
Keyword Arguments
delta::Number = 1e-6: Step of the finite difference.marginal::Bool = false: Whether to return the marginal risks, without the factor $w_i$.sca::Option{<:Scalariser} = nothing: Scalariser that combines a vector of measures. A single measure ignores it.strict::Bool = false: Whether a held non-investable asset raises an error. Only a prior result reads it.
Validation
- On a bare matrix, a Deferred Quantity that is not resolved, and an empty slot that the functor reads, raise through
assert_resolved_slots, as they do inexpected_risk. - Under
strict = true, a held non-investable asset raises throughinvestable_reduction.
Returns
rc::Vector: The risk contribution, or the marginal risk, of each asset of the full universe.
Related
expected_riskadjusted_riskfactor_risk_contributionresolve_risk_inputsrisk_gradient: The gradient of the risk itself, without the homogeneity correction.
risk_contribution(r::BaseRM_VecBaseRM, pred::PredictionResult{<:Any, <:HeldWeightsResult}, fees = nothing; kwargs...)
risk_contribution(r::BaseRM_VecBaseRM, pred::PredictionResult{<:Any, Nothing}, args...; kwargs...)Decompose a fold's risk over its assets.
This is the fold-taking method of risk_contribution. It finds the target weights, the asset returns and the fee of the fold, and hands them to the free function, so the figures are the ones the free function gives.
The three are not on one universe. The Held Weights record and the target weights come back on the caller's universe through expand_held_weights, and the fee of the result stays on the universe the fit solved on. The method therefore views the weights and the asset returns at the Investable Mask of the result before the finite difference, as investable_reduction does for the value-level method, and expands the answer back with a zero at every non-investable asset. A result whose mask is nothing views nothing.
Under a Weight Drift the figures are exact to first order in the drift only. The drifted series is not linear in the target weights, so the contributions sum to the realised risk of the fold approximately. The contributions are still stated against the target weights, because the finite difference perturbs them.
A fold that carries no Held Weights record raises, because pred.rd.X is the portfolio series and the fold keeps no asset matrix.
Algorithm
- Read the Investable Mask of the result with
result_investable_mask, givingimsk. - View the target weights and the asset returns
hw.Xatimskwithinvestable_weights_view. - Resolve the fee with
fold_fees. - Compute the contributions with the free
risk_contribution, givingrc. - Expand
rcto the caller's universe withexpand_investable_weights, with a zero at every non-investable asset.
Arguments
r::BaseRM_VecBaseRM: Risk measure to differentiate, or a vector of them.pred: Single-fold prediction result.fees: A caller'sFeeson the caller's universe, which takes precedence over the result's own and is viewed at the result's Investable Mask throughfold_fees.args...: Additional arguments (ignored by the refusing method).
Validation
- The fold carries a
HeldWeightsResult, else anArgumentErrornaming the two switches.
Returns
Vector: Risk contributions (or marginal risks) for each asset of the caller's universe, exactly0at a non-investable one.
Related
PortfolioOptimisers.risk_gradient — Function
risk_gradient(
r::BaseRM_VecBaseRM,
w::VecNum,
X::MatNum_Pr,
fees::Option{<:Fees} = nothing;
delta::Number = 1e-6,
sca::Option{<:Scalariser} = nothing,
strict::Bool = false,
kwargs...
) -> VectorCompute the gradient of a risk measure with respect to the weights, with one entry for each asset.
The gradient is the derivative of the figure that expected_risk reports, at the weights that the caller gives, without a homogeneity correction. The marginal figure of risk_contribution divides by the degree of the measure, so that Euler's theorem gives the risk back. On a Variance the two differ by a factor of two.
Three measures have a closed form, and the function uses it. Every other measure, and a MeanReturn that is charged fees, takes the two-sided finite difference at the step delta, which costs 2N evaluations of the measure. A measure whose value is a solve, of the entropic, the relativistic or the power norm family, solves its programme once, and the finite difference evaluates the expected loss under the Worst-Case Distribution of that solve, as in risk_contribution. The fee is not linear in the weights, so a MeanReturn with fees has no closed form here. Where the gradient is not defined at the point, such as at a tie inside a maximum, at a scenario on a Value-at-Risk atom, or at a zero variance under the square root, the finite difference returns the chord across the kink. The closed form of the standard deviation falls back to the finite difference at a zero variance.
A vector of measures differentiates the scalarised aggregate by the chain rule, with each element at its own settings.scale. Under SumScalariser it sums the gradients of the elements. Under MaxScalariser and MinScalariser it takes the gradient of the element that the scalariser picks, and at a tie the earliest such element, where the subgradient is a set. Under LogSumExpScalariser it takes the softmax-weighted sum, which is smooth everywhere. An element with a closed form keeps it inside a vector whose other elements use the finite difference.
Mathematical definition
\[\begin{align} \nabla \left( \boldsymbol{w}^\intercal \hat{\mathbf{\Sigma}} \boldsymbol{w} \right) &= 2 \hat{\mathbf{\Sigma}} \boldsymbol{w}\,, \\ \nabla \sqrt{\boldsymbol{w}^\intercal \hat{\mathbf{\Sigma}} \boldsymbol{w}} &= \frac{\hat{\mathbf{\Sigma}} \boldsymbol{w}}{\sqrt{\boldsymbol{w}^\intercal \hat{\mathbf{\Sigma}} \boldsymbol{w}}}\,, \\ \nabla \sum_{t=1}^{T} \omega_t \, r_t(\boldsymbol{w}) &= \sum_{t=1}^{T} \omega_t \, \nabla r_t(\boldsymbol{w})\,, \\ \nabla S\left( s_1 R_1(\boldsymbol{w}),\, \ldots,\, s_n R_n(\boldsymbol{w}) \right) &= \sum_{k=1}^{n} p_k \, s_k \, \nabla R_k(\boldsymbol{w})\,. \end{align}\]
The first line is the gradient of a Variance, the second of a StandardDeviation, and the third of a MeanReturn. The return of observation $t$ is $r_t(\boldsymbol{w}) = \boldsymbol{x}_t^\intercal \boldsymbol{w}$, with $\nabla r_t = \boldsymbol{x}_t$. Under the log flag of the measure it is $r_t(\boldsymbol{w}) = \log(1 + \boldsymbol{x}_t^\intercal \boldsymbol{w})$, with $\nabla r_t = \boldsymbol{x}_t / (1 + \boldsymbol{x}_t^\intercal \boldsymbol{w})$. The observation weights are normalised, $\omega_t = w_t / \sum_{s=1}^{T} w_s$, and they are $\omega_t = 1 / T$ when the measure states none. The last line is the chain rule for a vector of measures.
Where:
- $\hat{\mathbf{\Sigma}}$: Estimated covariance matrix.
- $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
- $\omega_t$: Normalised observation weight of observation $t$.
- $r_t(\boldsymbol{w})$: Portfolio return of observation $t$.
- $\boldsymbol{x}_t$: Asset returns for observation $t$, the $t$-th row of the returns matrix.
- $w_{t}$: Observation weight of observation $t$.
- $T$: Number of observations.
- $S$: Scalariser that combines the scaled risks of a vector of risk measures into one number.
- $p_k$: Chain-rule weight of the $k$-th risk measure of a vector, the partial derivative of $S$ with respect to its $k$-th argument at $s_k R_k(\boldsymbol{w})$.
- $s_k$:
scaleof the $k$-th risk measure of a vector, its weight in the combination. - $R_k(\boldsymbol{w})$: Element risk, the risk of the $k$-th risk measure of a vector.
- $n$: Size of the vector of risk measures.
Algorithm
The vector route, risk_gradient(rs::VecBaseRM, w, X, fees):
- Compute the chain-rule weights
psatwwithscalariser_element_weights. - Set the gradient
gto zero. - For each element
rwhose weightpis not zero, addp * r.settings.scaletimes the gradient ofrtog.
The prior route reduces the prior, the weights and the fees to the Investable Mask with investable_reduction, resolves the measure once with resolve_risk_inputs, and expands the gradient back to the full universe, as risk_contribution does.
Arguments
r: Risk measure or vector of risk measures.w::VecNum: Portfolio weights vectorassets × 1.X::MatNum_Pr: Returns matrix, prior result or returns result.fees: OptionalFeesstructure.
Keyword Arguments
delta::Number = 1e-6: Step of the finite difference.sca::Option{<:Scalariser} = nothing: Scalariser that combines a vector of measures. A single measure ignores it.strict::Bool = false: Whether a held non-investable asset raises an error. Only a prior result reads it.
Validation
- On a bare matrix, a Deferred Quantity that is not resolved, and an empty slot that the functor reads, raise through
assert_resolved_slots, as they do inexpected_risk. - A Calibration Rule that is not calibrated raises through
assert_calibrated_slots. - Under
strict = true, a held non-investable asset raises throughinvestable_reduction.
Returns
g::Vector: The gradient, one entry for each asset of the full universe. A non-investable asset reports exactly0.
Examples
julia> risk_gradient(Variance(; sigma = [0.04 0.02; 0.02 0.16]), [0.5, 0.5], zeros(2, 2))2-element Vector{Float64}: 0.06 0.18Related
PortfolioOptimisers.factor_risk_contribution — Function
factor_risk_contribution(
r::BaseRM_VecBaseRM,
w::VecNum,
X::MatNum_Pr,
fees::Option{<:Fees} = nothing;
re::RegE_Reg = StepwiseRegression(),
rd::ReturnsResult = ReturnsResult(),
delta::Number = 1e-6,
strict::Bool = false,
kwargs...
) -> VectorCompute the contribution of each risk factor, and of the directions that no factor spans, to the risk of a portfolio.
The function splits the Euler decomposition of the risk between the factor exposures $\mathbf{B}^\intercal \boldsymbol{w}$ and the exposures to the null space of $\mathbf{B}^\intercal$. The last entry sums the contributions of that null space, the off-factor part. The entries sum to the risk of the portfolio on the returns matrix that the function measures, because the marginal risks come from risk_contribution with its homogeneity correction.
A prior result reduces to the Investable Mask at the entry, through investable_reduction, and the function reduces rd with it, so the regression fits the loadings over the investable assets alone. A held non-investable asset warns and its weight is dropped, or it raises under strict. The result has one entry for each factor and not one for each asset, so nothing expands.
The gradient is taken on original_returns, the returns that the caller supplied, and not on pr.X. The two differ under a factor prior, where pr.X is the reconstruction F * transpose(M) .+ transpose(b). That matrix has the rank of F and no residual, so on it the off-factor part of a measure that reads the series reports the share of the intercept and not the idiosyncratic risk, and it can be negative. So under a factor prior the entries sum to the risk on the returns of the caller, and not to expected_risk(r, w, pr). A measure whose kernel reads a moment and not the series, such as Variance, StandardDeviation or DistributionValueatRisk, gives the same answer on both matrices.
The loadings come from resolve_factor_regression, which takes the loadings of the prior before it fits re. So a regression estimator in re has no effect when the prior carries a factor block.
The contributions are those of the target weights. Under a Weight Drift the return series of a fold is not linear in one weight vector, so the contributions sum to the realised risk of the fold only to first order in the drift.
Mathematical definition
\[\begin{align} \mathrm{FRC}_j &= \left[ \mathbf{B}^\intercal \boldsymbol{w} \right]_j \left[ \mathbf{B}^{+} \boldsymbol{g} \right]_j\,, \quad j = 1, \ldots, K\,, \\ \mathrm{FRC}_{K+1} &= \left( \tilde{\mathbf{B}} \boldsymbol{w} \right)^\intercal \left( \tilde{\mathbf{B}}^{+} \right)^\intercal \boldsymbol{g}\,, \\ \boldsymbol{g} &= \frac{1}{d} \nabla R(\boldsymbol{w})\,, \\ \sum_{j=1}^{K+1} \mathrm{FRC}_j &= R(\boldsymbol{w})\,. \end{align}\]
The rows of $\tilde{\mathbf{B}}$ are an orthonormal basis of the null space of $\mathbf{B}^\intercal$. So $\mathbf{B} \mathbf{B}^{+} + \tilde{\mathbf{B}}^\intercal \tilde{\mathbf{B}}$ is the identity, the entries sum to $\boldsymbol{w}^\intercal \boldsymbol{g}$, and Euler's theorem gives the last line.
This is the decomposition of Section 3 of [223], whose matrix $\mathbf{A}$ is $\mathbf{B}$ here. That work takes the completion by the null space from Section 4 and Appendix A.1 of [224]. The factor exposures are $\mathbf{B}^\intercal \boldsymbol{w}$, and not the regression exposures of Section 5 of [224]. The homogeneity correction and the finite-difference gradient are the library's own.
Where:
- $\mathrm{FRC}_j$: Risk contribution of factor $j$, and of the off-factor part at $j = K + 1$.
- $\mathbf{B}$: Factor loading matrix $N \times K$.
- $\tilde{\mathbf{B}}$: Basis of the null space of $\mathbf{B}^\intercal$, $(N - K) \times N$.
- $(\cdot)^{+}$: Moore-Penrose pseudoinverse.
- $\boldsymbol{g}$: Marginal risk of each asset, with the homogeneity correction.
- $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
- $d$: Degree of homogeneity of the risk measure, the $d$ for which $R(c \boldsymbol{w}) = c^{d} R(\boldsymbol{w})$ at every $c > 0$.
- $R(\boldsymbol{w})$: Portfolio risk.
- $N$: Number of assets.
- $K$: Number of factors.
Algorithm
- Reduce
X,wandfeesto the Investable Mask withinvestable_reduction, which gives the maskimsk, and reducerdto the same assets withinvestable_returns_view. - Pick the loadings
rrwithresolve_factor_regression. - Resolve
rand the returns that the caller supplied withresolve_factor_risk_inputs. - Form
Bt, the transpose of the loadings,b2t, the basis of the null space ofBt, andb3t, the transpose of the pseudoinverse ofb2t. - Compute the marginal risks
mrwithrisk_contributionandmarginal = true. - Compute the factor contributions
rc_fand the off-factor contributionrc_of, and return[rc_f; rc_of].
Arguments
r: Risk measure or vector of risk measures.w::VecNum: Portfolio weights vectorassets × 1.X::MatNum_Pr: Returns matrix, prior result or returns result.fees: OptionalFeesstructure.
Keyword Arguments
re::RegE_Reg = StepwiseRegression(): Regression estimator or result for the factor loadings.rd::ReturnsResult = ReturnsResult(): Returns result that carries the factor returnsF, which a regression estimator reads.delta::Number = 1e-6: Step of the finite difference.sca::Option{<:Scalariser} = nothing: Scalariser that combines a vector of measures. A single measure ignores it.strict::Bool = false: Whether a held non-investable asset raises an error. Only a prior result reads it.
Validation
- When none of
re,Xandrdsupplies the loadings,resolve_factor_regressionraises anIsNothingError. - Under
strict = true, a held non-investable asset raises throughinvestable_reduction.
Returns
frc::Vector: The contribution of each factor, with the off-factor contribution as the last entry.
Related
risk_contributionexpected_riskresolve_factor_risk_inputsresolve_factor_regressionoriginal_returnsFactorRiskContribution: The optimiser that sets a budget on these contributions.
References
- [223] T. Roncalli and G. Weisang. Risk parity portfolios with risk factors. Available at SSRN 2155159 (2012). Section 3, Equations 2 and 3, and Theorems 1 and 2.
- [224] A. Meucci. Risk contributions from generic user-defined factors. Available at SSRN 930034 (2007). Section 4, Equations 20 and 21, and Appendix A.1.
factor_risk_contribution(r::BaseRM_VecBaseRM, pred::PredictionResult{<:Any, <:HeldWeightsResult}, fees = nothing; rd, kwargs...)
factor_risk_contribution(r::BaseRM_VecBaseRM, pred::PredictionResult{<:Any, Nothing}, args...; kwargs...)Decompose a fold's risk over its factors.
This is the fold-taking method of factor_risk_contribution, and the twin of the fold-taking risk_contribution method. It finds the target weights, the asset returns and the fee of the fold, and views them at the Investable Mask of the result, as that method does. It also builds the rd that the loadings are fitted from, out of the fold itself: the asset returns of the fold beside the factor block that reconstruct_rd kept. A caller who wants other loadings passes its own rd, or a precomputed Regression as re.
The first-order caveat of the fold-taking risk_contribution method holds here unchanged, and a fold that carries no Held Weights record raises for the same reason.
Algorithm
- Read the Investable Mask of the result, giving
imsk. - View the target weights and the asset returns
hw.Xatimskwithinvestable_weights_view. - Resolve the fee with
fold_fees. - Resolve the returns result of the loadings on the live assets with
fold_factor_returns. - Compute the factor contributions with the free
factor_risk_contribution.
Arguments
r::BaseRM_VecBaseRM: Risk measure to decompose, or a vector of them.pred: Single-fold prediction result.fees: A caller'sFeeson the caller's universe, which takes precedence over the result's own and is viewed at the result's Investable Mask throughfold_fees.args...: Additional arguments (ignored by the refusing method).
Keyword Arguments
rd::Option{<:ReturnsResult} = nothing: Returns result the loadings are fitted from, on the caller's universe, ornothingfor the fold's own asset returns and factor block.
Validation
- The fold carries a
HeldWeightsResult, else anArgumentErrornaming the two switches.
Returns
Vector: Risk contributions for each factor, with the last element being the idiosyncratic (off-factor) contribution.
Related
PortfolioOptimisers.rolling_window_measure — Function
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
w::AbstractVector{<:Union{Number, AbstractJuMPScalar}},
X::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
fees::Union{Nothing, Fees},
window::Integer;
sca,
kwargs...
) -> Any
Compute the risk of a portfolio over each rolling window of the returns matrix, at constant weights.
The method scores the one vector w on every window, so each number is a property of that weight vector and not of a history. The (r, ret::VecNum, window) method reads the realised history instead, because it rolls a net return series that the caller already formed. The two answer different questions, so they are two methods.
The (r, w::MatNum, X, fees, window) method scores each window against the weights of a weight path at the last row of the window. The type of the weight argument picks the method, so a vector reads one target and a matrix reads a path.
Mathematical definition
\[\begin{align} R_t &= R\left( \boldsymbol{w};\, \mathbf{X}_{t-W+1:t} \right)\,, \quad t = W, \ldots, T\,. \end{align}\]
Where:
- $R_t$: Rolling risk, the risk of the window that ends at observation $t$.
- $R(\boldsymbol{w};\, \mathbf{X}_{a:b})$: Window risk, the risk of the portfolio on the rows $a$ to $b$ of the returns matrix.
- $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
- $W$: Rolling window size, in observations.
- $T$: Number of observations.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.w::VecNum: Portfolio weights vector.X::MatNum: Asset returns matrix.fees::Option{<:Fees}: Optional fee structure.window::Integer: Size of the rolling window (number of periods).
Keyword Arguments
sca::Option{<:Scalariser} = nothing: Scalariser combining a vectorr. Inert on a single measure.
Validation
1 <= window <= size(X, 1), else aDomainErrornamingwindow.
The function checks the window itself. Without the check, a window that is not positive indexes X out of bounds and raises a BoundsError from inside the measure, and a window longer than the sample gives an empty vector that looks like a valid result. plot_rolling_measure checks its rolling keyword by the same rule.
Returns
risks::VecNum: The risk of each rolling window,T - window + 1values.
Related
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
w::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
X::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
fees::Union{Nothing, Fees},
window::Integer;
sca,
kwargs...
) -> Any
Compute the risk of a portfolio over each rolling window of the returns matrix, against a weight path.
w is a T × N weight path. The method scores the window that ends at row t against row t of the path, the weights that the portfolio held when that window closed. The rest of the library reads ending weights in the same way.
Each window gets one set of weights, so the result is not the realised risk of the window. The weights moved inside the window, and the method scores the window as if they did not. To score the realised history of each window, use the (r, ret::VecNum, window) method, which rolls the drifted series.
At constant weights every row of the path is the same vector, and this method gives the result of the (r, w::VecNum, X, fees, window) method.
Mathematical definition
\[\begin{align} R_t &= R\left( \boldsymbol{w}_t;\, \mathbf{X}_{t-W+1:t} \right)\,, \quad t = W, \ldots, T\,. \end{align}\]
Where:
- $R_t$: Rolling risk, the risk of the window that ends at observation $t$.
- $R(\boldsymbol{w};\, \mathbf{X}_{a:b})$: Window risk, the risk of the portfolio on the rows $a$ to $b$ of the returns matrix.
- $\boldsymbol{w}_t$: Row $t$ of the weight path, the weights held at observation $t$.
- $W$: Rolling window size, in observations.
- $T$: Number of observations.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.w::MatNum: Weight path (observations × assets), asweight_pathmakes one.X::MatNum: Asset returns matrix.fees::Option{<:Fees}: Optional fee structure.window::Integer: Size of the rolling window (number of periods).
Keyword Arguments
sca::Option{<:Scalariser} = nothing: Scalariser combining a vectorr. Inert on a single measure.
Validation
1 <= window <= size(X, 1), else aDomainErrornamingwindow.size(w, 1) == size(X, 1), else aDimensionMismatchnaming both. A path shorter than the sample indexes out of bounds inside whichever measurernames, which is the caller error the window check already refuses at the boundary.
Returns
risks::VecNum: Expected risk values for each rolling window.
Related
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
ret::AbstractVector{<:Union{Number, AbstractJuMPScalar}},
window::Integer;
sca,
kwargs...
) -> Any
Compute the risk of each rolling window of a net return series that the caller already formed.
The method reads the realised history. A window is a part of the series ret, so under a weight drift the drift does not start again at the first row of a window, and each row reads the weights held on the way to that row. The method takes no fees, because the series is already net of fees. The (r, w::VecNum, X, fees, window) method reads constant weights instead.
Mathematical definition
\[\begin{align} R_t &= R\left( \boldsymbol{r}_{t-W+1:t} \right)\,, \quad t = W, \ldots, T\,. \end{align}\]
Where:
- $R_t$: Rolling risk, the risk of the window that ends at observation $t$.
- $\boldsymbol{r}_{a:b}$: Entries $a$ to $b$ of the net return series.
- $W$: Rolling window size, in observations.
- $T$: Number of observations.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.ret::VecNum: Net portfolio return series.window::Integer: Size of the rolling window (number of periods).
Keyword Arguments
sca::Option{<:Scalariser} = nothing: Scalariser combining a vectorr. Inert on a single measure.
Validation
1 <= window <= length(ret), else aDomainErrornamingwindow.- Each window is scored through
expected_risk_from_returns, so a measure whosesupports_precomputed_returnsisfalseraises that entry's own namedArgumentError.
The function checks the window for the reason that the constant-weight method states. A measure that reads weights raises the ArgumentError of expected_risk_from_returns.
Returns
risks::VecNum: Expected risk values for each rolling window.
Related
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
ret::AbstractVector{<:AbstractVector{<:Union{Number, AbstractJuMPScalar}}},
window::Integer;
kwargs...
) -> Any
Compute the risk of each rolling window of each series of a population of net return series.
A fold whose optimisation result carries a population of weight vectors forms one series for each member. The method rolls each series with the single-series method, as expected_risk_from_returns does on a VecVecNum.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.ret::VecVecNum: Net portfolio return series, one per population member.window::Integer: Size of the rolling window (number of periods).
Returns
risks::Vector{<:VecNum}: Rolling risk values, one vector per population member.
Related
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
pred::PredictionResult,
window::Integer;
kwargs...
) -> Any
Roll a risk measure over the return series a single fold formed.
This is the method of rolling_window_measure over the realised history of a fold. pred.rd.X is the series that predict stored, so the method reads no weights. Under a Weight Drift that series is the drifted one, and each window is a part of the drift of the fold.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.pred::PredictionResult: Single-fold prediction result.window::Integer: Size of the rolling window (number of periods).
Returns
risks::VecNum: Expected risk values for each rolling window.
Related
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
mpred::MultiPeriodPredictionResult,
window::Integer;
kwargs...
) -> Any
Roll a risk measure over the return series a whole path formed.
mpred.mrd.X concatenates the folds of the path into one series, so a window can straddle a rebalance and read observations from two folds. That is the realised history: the fund held one set of weights before the rebalance and another after it, and the window sees both.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.mpred::MultiPeriodPredictionResult: Multi-period prediction result.window::Integer: Size of the rolling window (number of periods).
Returns
risks::VecNum: Expected risk values for each rolling window.
Related
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
preds::AbstractVector{<:MultiPeriodPredictionResult},
window::Integer;
kwargs...
) -> Any
Roll a risk measure over each path of a vector of multi-period prediction results.
Maps the multi-period method over preds, so each path is rolled on its own series. The paths of a combinatorial scheme cover the same calendar, so their windows are comparable across the vector.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.preds::VecMPredRes: Vector of multi-period prediction results.window::Integer: Size of the rolling window (number of periods).
Returns
risks::Vector{<:VecNum}: Rolling risk values, one vector per path.
Related
rolling_window_measure(
r::Union{AbstractBaseRiskMeasure, AbstractVector{<:AbstractBaseRiskMeasure}},
ppred::PopulationPredictionResult,
window::Integer;
kwargs...
) -> Any
Roll a risk measure over every path of a population prediction result.
Rolls r over each member of ppred.pred, as expected_risk does on the same type, so a member can be a single fold or a multi-period result.
Arguments
r::BaseRM_VecBaseRM: Risk measure to evaluate, or a vector of them.ppred::PopulationPredictionResult: Population prediction result.window::Integer: Size of the rolling window (number of periods).
Returns
risks::Vector{<:VecNum}: Rolling risk values, one vector per path.
Related
References
- [223]
- T. Roncalli and G. Weisang. Risk Parity Portfolios with Risk Factors. Available at SSRN 2155159 (2012).
- [224]
- A. Meucci. Risk Contributions from Generic User-Defined Factors. Available at SSRN 930034 (2007).