Non-Optimisation Risk Measures
PortfolioOptimisers.MeanReturn — Type
struct MeanReturn{__T_settings, __T_w, __T_flag} <: NonOptimisationRiskMeasureMeasures the mean of the portfolio returns, or the mean of their logarithmic returns.
The measure is a NonOptimisationRiskMeasure. It is a return and not a risk, so the type bound of every optimiser refuses it. An optimiser reads the expected return through its objective function, such as MaximumReturn. A larger mean is better, so bigger_is_better returns true, and an asset selection or a parameter search keeps the largest mean. The measure is the numerator of MeanReturnRiskRatio.
Mathematical definition
For flag = false, the arithmetic mean:
\[\begin{align} \bar{x} &= \frac{1}{T} \sum_{t=1}^{T} x_t\,. \end{align}\]
Where:
- $\bar{x}$: Arithmetic mean portfolio return.
- $\boldsymbol{x}$: Portfolio returns vector $T \times 1$.
- $T$: Number of observations.
For flag = true, the mean of the logarithmic returns:
\[\begin{align} \bar{x}_{\log} &= \frac{1}{T} \sum_{t=1}^{T} \log(1 + x_t)\,. \end{align}\]
Where:
- $\bar{x}_{\log}$: Mean of the logarithmic portfolio returns.
- $\boldsymbol{x}$: Portfolio returns vector $T \times 1$.
- $T$: Number of observations.
When w holds observation weights $\omega_t$, each form takes the weighted mean. The first form is then $\sum_{t} \omega_t x_t / \sum_{t} \omega_t$, and the second form puts $\log(1 + x_t)$ in place of $x_t$.
Fields
settings: Risk measure settings.
w: Optional observation weights vectorobservations × 1, or a concrete subtype ofDynamicAbstractWeights. Ifnothing, the computation is unweighted.
flag: Iftrue, the measure takes the mean oflog1p.(x), the logarithmic returns. Iffalse, it takes the mean ofx.
Constructors
MeanReturn(; settings::HierarchicalRiskMeasureSettings = HierarchicalRiskMeasureSettings(), w::Option{<:ObsWeights} = nothing, flag::Bool = false) -> MeanReturnKeywords correspond to the struct's fields.
Validation
- If
wis aStatsBase.AbstractWeights, it is not empty, each entry is finite and>= 0, andsum(w) > 0, throughassert_observation_weights. ADynamicAbstractWeightsholds no weights until it reads the data, sochecked_observation_weightschecks it at evaluation, and also checks there that the weights have one entry for each observation.
Propagated parameters
factory passes its arguments on to these @fprop fields:
w: Replaced with the incomingObsWeights.
Observation weight parameters
obs_weights_view indexes these fields to the selected observations:
w: Indexed to the selected observations throughobs_weights_view.
Functor
(r::MeanReturn)(x::VecNum)Computes the mean return of the net portfolio returns x. expected_risk charges the fees before the call.
Arguments
x::VecNum: Net portfolio returns.
Examples
julia> MeanReturn()MeanReturn settings ┼ HierarchicalRiskMeasureSettings │ scale ┴ Float64: 1.0 w ┼ nothing flag ┴ Bool: falseRelated
NonOptimisationRiskMeasureMeanReturnRiskRatioExpectedReturn: the expected return of a prior, which aJuMPoptimiser reads.factoryobs_weights_view
PortfolioOptimisers.MeanReturnRiskRatio — Type
struct MeanReturnRiskRatio{__T_settings, __T_rt, __T_rk, __T_sca, __T_rf} <: NonOptimisationRiskMeasureMeasures the mean portfolio return in excess of a risk-free rate, per unit of risk.
The numerator is the mean of MeanReturn rt less the risk-free rate rf, and the denominator is the risk of rk. With a StandardDeviation in rk and the arithmetic mean in rt, the ratio is the reward-to-variability ratio of [222], the Sharpe ratio. Another risk measure in rk gives a generalisation of that ratio.
A larger ratio is better, so bigger_is_better returns true. The ratio is a NonOptimisationRiskMeasure, because it is not a risk, and the type bound of every optimiser refuses it. The objective MaximumRatio of a JuMP optimiser maximises a ratio of this kind. The quotient follows IEEE division. A zero risk gives Inf for a positive numerator, NaN for a zero numerator and -Inf for a negative numerator. needs_previous_weights answers as rk does.
Mathematical definition
\[\begin{align} \mathrm{MRRR}(\boldsymbol{x}) &= \frac{\bar{x} - r_f}{\rho(\boldsymbol{x})}\,. \end{align}\]
Where:
- $\mathrm{MRRR}(\boldsymbol{x})$: Mean return to risk ratio.
- $\boldsymbol{x}$: Portfolio returns vector $T \times 1$.
- $\bar{x}$: Mean portfolio return of
rt. - $r_f$: Risk-free rate
rf. - $\rho(\boldsymbol{x})$: Risk of
rk. A vectorrkgives one number throughsca.
Fields
settings: Risk measure settings.
rt: Mean return estimator.
rk: Risk measure for ratio computation, or a vector of them scalarised bysca.
sca: Scalariser combining the risk measures inrkinto one number.nothinggives the sum ofSumScalariser. Inert whenrkholds a single measure. The field beats ascakeyword supplied at the call site.
rf: Risk-free rate.
Constructors
MeanReturnRiskRatio(; settings::HierarchicalRiskMeasureSettings = HierarchicalRiskMeasureSettings(), rt::MeanReturn = MeanReturn(), rk::BaseRM_VecBaseRM = ConditionalValueatRisk(), sca::Option{<:Scalariser} = nothing, rf::Number = 0.0) -> MeanReturnRiskRatioKeywords correspond to the struct's fields.
Multiplicity
rk takes one risk measure or a vector of them. sca scalarises a vector into one number, and weights each element by its own settings.scale. The field beats the sca keyword of a caller, so a value that this type reports always uses the scalariser that the type names.
Validation
- If
rkis a vector:!isempty(rk). isfinite(rf).
Propagated parameters
factory passes its arguments on to these @fprop fields:
Examples
julia> MeanReturnRiskRatio()MeanReturnRiskRatio settings ┼ HierarchicalRiskMeasureSettings │ scale ┴ Float64: 1.0 rt ┼ MeanReturn │ settings ┼ HierarchicalRiskMeasureSettings │ │ scale ┴ Float64: 1.0 │ w ┼ nothing │ flag ┴ Bool: false rk ┼ ConditionalValueatRisk │ settings ┼ RiskMeasureSettings │ │ scale ┼ Float64: 1.0 │ │ ub ┼ nothing │ │ rke ┴ Bool: true │ alpha ┼ Float64: 0.05 │ w ┴ nothing sca ┼ nothing rf ┴ Float64: 0.0Related
NonOptimisationRiskMeasureMeanReturnAbstractBaseRiskMeasureNonOptimisationRiskRatio: a ratio of any two measures.MaximumRatio
References
- [222] W. F. Sharpe. Mutual fund performance. The Journal of Business 39, 119–138 (1966). Pages 122–123.
PortfolioOptimisers.ThirdCentralMoment — Type
struct ThirdCentralMoment{__T_settings, __T_w, __T_mu, __T_ve} <: NonOptimisationRiskMeasureMeasures the third central moment of the portfolio returns, or the standardised skewness when ve is a variance estimator.
The moment has the divisor $T$. When ve is nothing, the measure reports the moment as it is. When ve is a variance estimator, the measure divides the moment by the cube of the standard deviation of the same deviations, so it reports the skewness coefficient, which has no units. The field ve of HighOrderMoment makes the same choice for the moments of order three and four. Both values measure the asymmetry of the returns, and a larger value is better, so bigger_is_better returns true.
The measure is a NonOptimisationRiskMeasure. The library has no JuMP model of it, so the type bound of every optimiser refuses it. Each value can be negative, so neither value is a risk that a hierarchical optimiser can allocate by. It serves reports, and the scores of an asset selection or a parameter search. Skewness reads the third moment from a coskewness matrix instead, which is the term that VarianceSkewKurtosis bounds.
Mathematical definition
\[\begin{align} \delta_t &= x_t - \mu\,, \\ m_3(\boldsymbol{x}) &= \frac{1}{T} \sum_{t=1}^{T} \delta_t^3\,, \\ \mathrm{Skew}(\boldsymbol{x}) &= \frac{m_3(\boldsymbol{x})}{\hat{\sigma}^3}\,, \\ \hat{\sigma}^2 &= f \sum_{t=1}^{T} \delta_t^2\,. \end{align}\]
Where:
- $m_3(\boldsymbol{x})$: Third central moment of the portfolio returns, the value when
veisnothing. - $\mathrm{Skew}(\boldsymbol{x})$: Standardised skewness of the portfolio returns, the value when
veis a variance estimator. - $\boldsymbol{x}$: Portfolio returns vector $T \times 1$.
- $T$: Number of observations.
- $\mu$: Centre of the moment.
calc_moment_targetstates it for each type ofmu. - $\delta_t$: Centred portfolio return at observation $t$.
- $\hat{\sigma}$: Standard deviation of the deviations about zero, from
ve. - $f$: Variance divisor of the estimator
ve,StatsBase.varcorrectionof $T$, or of the observation weights when the measure holds them, atve.corrected. With no observation weights it is $1/(T-1)$ whenve.correctedistrueand $1/T$ otherwise.
When w holds observation weights $\omega_t$, the weighted mean $\sum_{t} \omega_t \delta_t^3 / \sum_{t} \omega_t$ replaces the mean, the centre takes the same weights, and so does ve. The default SimpleVariance sets corrected = true, so the standard deviation divides by $T - 1$ and the moment by $T$. The value is then $((T - 1)/T)^{3/2}$ times the moment coefficient of skewness. Set ve = SimpleVariance(; me = nothing, corrected = false) for the moment coefficient.
Fields
settings: Risk measure settings.
w: Optional observation weights vectorobservations × 1, or a concrete subtype ofDynamicAbstractWeights. Ifnothing, the computation is unweighted.
mu: Optional centre the moment is taken about, a scalar or a vectorassets × 1. Also admits a Deferred Quantity — an expected returns estimator or a prior estimator that computes the centre against the optimisation's own prior, atfactorytime (seeMuSlotandresolve_deferred_quantities). Ifnothing, the prior supplies it.
ve: Variance estimator of the standard deviation that divides the moment, ornothingfor the moment as it is. The estimator reads the deviations about zero, so its ownmedoes not enter.
Constructors
ThirdCentralMoment(; settings::HierarchicalRiskMeasureSettings = HierarchicalRiskMeasureSettings(), w::Option{<:ObsWeights} = nothing, mu::Option{<:MuSlot} = nothing, ve::Option{<:AbstractVarianceEstimator} = nothing) -> ThirdCentralMomentKeywords correspond to the struct's fields. A w that is not nothing is passed to ve with factory, so the variance estimator reads the same weights as the measure.
Validation
- If
muis aVecNum:!isempty(mu)andall(isfinite, mu). - If
muis aNumber:isfinite(mu). - If
wis aStatsBase.AbstractWeights, it is not empty, each entry is finite and>= 0, andsum(w) > 0, throughassert_observation_weights. ADynamicAbstractWeightsholds no weights until it reads the data, sochecked_observation_weightschecks it at evaluation, and also checks there that the weights have one entry for each observation.
A stated mu is pinned. It crosses a Cross-Validation fold or a subset view as the value of the whole universe, so it does not follow the refit that the optimisation runs on. A caller who wants it to follow the fit names a Deferred Quantity in mu, or leaves the slot nothing and lets the prior supply it.
Propagated parameters
factory passes its arguments on to these @fprop fields:
w: Replaced with the incomingObsWeights.
Observation weight parameters
obs_weights_view indexes these fields to the selected observations:
w: Indexed to the selected observations throughobs_weights_view.
Functor
(r::ThirdCentralMoment)(w::VecNum, X::MatNum, fees = nothing)(r::ThirdCentralMoment)(x::VecNum)Computes the third central moment, or the standardised skewness, of the portfolio returns X * w net of fees, or of the net portfolio returns x. The second form needs a centre that does not read the weights, which supports_precomputed_returns reports.
Arguments
w::VecNum: Portfolio weights vector.X::MatNum: Asset returns matrix ($T \times N$).fees: Optional fee structure.x::VecNum: Net portfolio returns.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
mu: A stated value is sliced to the selected indices throughport_opt_view. A Deferred Quantity passes through unsliced, and then fits on the subset.
Examples
julia> ThirdCentralMoment()ThirdCentralMoment settings ┼ HierarchicalRiskMeasureSettings │ scale ┴ Float64: 1.0 w ┼ nothing mu ┼ nothing ve ┴ nothingjulia> x = [0.02, -0.01, 0.03, -0.04, 0.01];julia> ThirdCentralMoment()(x)-9.504000000000004e-6julia> ThirdCentralMoment(; ve = SimpleVariance())(x)-0.44480569586797897The second value is the first divided by the cube of the standard deviation of x, with the divisor $T - 1$.
Related
NonOptimisationRiskMeasureAbstractVarianceEstimatorHighOrderMoment: the same choice for the moments of order three and four, through itsve.Skewness: the third moment read from a coskewness matrix.calc_moment_targetbigger_is_betterfactoryobs_weights_view
PortfolioOptimisers.port_opt_view — Method
port_opt_view(x, i, args...; kwargs...) -> nothing_scalar_array_view(x, i)Select the assets i of an estimator, a result or an algorithm.
port_opt_view is the index-selection counterpart of factory. factory passes runtime values down a tree of composed structs, and port_opt_view passes an index selection down the same tree. It restricts every field that holds data, and every composed child, to the subset i. The meta-optimisers, such as NestedClustered and SubsetResampling, and the cross-validation variants use it to solve sub-problems with structs of the same shape.
A caller does not usually call port_opt_view. The meta-optimisers and the cross-validation internals call it. It is public and not exported, because the author of a new composed estimator can need to define a method. Tag each field that holds data with @vprop, and @propagatable makes the method.
This universal fallback handles leaf values. It views an array through nothing_scalar_array_view. It returns a scalar, nothing, an estimator with no data fields and an algorithm with no change. A composed struct that recurses into its children has its own, more specific method, which @propagatable makes from the @vprop tags or which the author writes by hand.
This method accepts and drops the threaded tail args... and all kwargs. The tail is usually the returns matrix X of the JuMP families. With this method, a call port_opt_view(child, i, X) that a macro makes never raises a MethodError on a leaf field.
Algorithm
- Drop
args...andkwargs.... This method is the leaf of the recursion, so it passes nothing further. - Return
nothing_scalar_array_viewofxati. The algorithm of that function gives the rule for each leaf type.
Related
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
AbstractResult, StatsBase.CovarianceEstimator}},
args...; kwargs...) -> AbstractArrayRebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.
factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.
factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.
The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.
Algorithm
The leaf method:
- Return
awith no change, and dropargs...andkwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.
The array method:
- For each element
aiofa, callfactoryonai, and forwardargs...andkwargs...with no change. - Collect the results into a new array of the shape of
a, in the order ofa, and return it.
A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.
The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.
Arguments
a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators ornothing, which it rebuilds one element at a time.args...: Positional arguments. The leaf method ignores them, and the array method forwards them.kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.
Returns
a: The input with no change, for the leaf method.v::AbstractArray: The rebuilt elements, in an array of the shape ofa, for the array method.
Examples
julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue w ┴ nothingRelated
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
AbstractResult, StatsBase.CovarianceEstimator}},
args...; kwargs...) -> AbstractArrayRebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.
factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.
factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.
The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.
Algorithm
The leaf method:
- Return
awith no change, and dropargs...andkwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.
The array method:
- For each element
aiofa, callfactoryonai, and forwardargs...andkwargs...with no change. - Collect the results into a new array of the shape of
a, in the order ofa, and return it.
A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.
The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.
Arguments
a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators ornothing, which it rebuilds one element at a time.args...: Positional arguments. The leaf method ignores them, and the array method forwards them.kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.
Returns
a: The input with no change, for the leaf method.v::AbstractArray: The rebuilt elements, in an array of the shape ofa, for the array method.
Examples
julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue w ┴ nothingRelated
PortfolioOptimisers.port_opt_view — Method
port_opt_view(x, i, args...; kwargs...) -> nothing_scalar_array_view(x, i)Select the assets i of an estimator, a result or an algorithm.
port_opt_view is the index-selection counterpart of factory. factory passes runtime values down a tree of composed structs, and port_opt_view passes an index selection down the same tree. It restricts every field that holds data, and every composed child, to the subset i. The meta-optimisers, such as NestedClustered and SubsetResampling, and the cross-validation variants use it to solve sub-problems with structs of the same shape.
A caller does not usually call port_opt_view. The meta-optimisers and the cross-validation internals call it. It is public and not exported, because the author of a new composed estimator can need to define a method. Tag each field that holds data with @vprop, and @propagatable makes the method.
This universal fallback handles leaf values. It views an array through nothing_scalar_array_view. It returns a scalar, nothing, an estimator with no data fields and an algorithm with no change. A composed struct that recurses into its children has its own, more specific method, which @propagatable makes from the @vprop tags or which the author writes by hand.
This method accepts and drops the threaded tail args... and all kwargs. The tail is usually the returns matrix X of the JuMP families. With this method, a call port_opt_view(child, i, X) that a macro makes never raises a MethodError on a leaf field.
Algorithm
- Drop
args...andkwargs.... This method is the leaf of the recursion, so it passes nothing further. - Return
nothing_scalar_array_viewofxati. The algorithm of that function gives the rule for each leaf type.
Related
PortfolioOptimisers.needs_previous_weights — Method
needs_previous_weights(r::MeanReturnRiskRatio) -> Any
Return whether MeanReturnRiskRatio r reads the previous portfolio weights.
The method returns needs_previous_weights(r.rk). The return side rt is a MeanReturn, which never reads them. A vector rk reads them when one of its measures does, such as a TurnoverRiskMeasure whose fixed is false.
Related
PortfolioOptimisers.supports_precomputed_returns — Method
supports_precomputed_returns(r::MeanReturnRiskRatio) -> Any
Return whether MeanReturnRiskRatio r supports evaluation on a precomputed return series.
Returns true only when both the return measure rt and the risk measure rk support precomputed returns.
Related
PortfolioOptimisers.supports_precomputed_returns — Method
supports_precomputed_returns(r::ThirdCentralMoment) -> Any
Return whether ThirdCentralMoment r supports precomputed-return evaluation.
The method returns weight_independent_target of r.mu. That is true when mu is nothing or a number, and false for a per-asset mu, which reads the asset weights.
Related
PortfolioOptimisers.bigger_is_better — Method
bigger_is_better(_::ThirdCentralMoment) -> Bool
Return true, because a larger third central moment is better, standardised or not.
The moment has the sign of the skewness, and bigger_is_better of Skewness also returns true. The standard deviation is positive, so the standardised value has the sign of the moment. The generic method for an AbstractBaseRiskMeasure returns false. The asset selection, the parameter search and the ranking of cross-validation results read this trait to choose the direction of the score.
Related
References
- [222]
- W. F. Sharpe. Mutual Fund Performance. The Journal of Business 39, 119–138 (1966).