Non-Optimisation Risk Measures

PortfolioOptimisers.MeanReturnType
struct MeanReturn{__T_settings, __T_w, __T_flag} <: NonOptimisationRiskMeasure

Represents a simple mean return measure for use in non-optimisation contexts.

MeanReturn computes the arithmetic mean of portfolio returns, or the mean log return when flag = true. It is used as the numerator in risk-adjusted performance ratios such as MeanReturnRiskRatio.

Mathematical definition

For flag = false (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 (log-return mean):

\[\begin{align} \bar{x}_{\log} &= \frac{1}{T} \sum_{t=1}^{T} \log(1 + x_t)\,. \end{align}\]

Where:

  • $\bar{x}_{\log}$: Log-return mean portfolio return.
  • $\boldsymbol{x}$: Portfolio returns vector $T \times 1$.
  • $T$: Number of observations.

For observation-weighted samples, the weighted mean is used instead.

Fields

  • settings: Risk measure settings.
  • w: Optional observation weights vector observations × 1, or a concrete subtype of DynamicAbstractWeights. If nothing, the computation is unweighted.
  • flag: Algorithm selection flag.

Constructors

MeanReturn(;    settings::HierarchicalRiskMeasureSettings = HierarchicalRiskMeasureSettings(),    w::Option{<:ObsWeights} = nothing,    flag::Bool = false) -> MeanReturn

Keywords correspond to the struct's fields.

Validation

  • If w is not nothing, !isempty(w).

Functor

(r::MeanReturn)(x::VecNum)

Computes the mean return of a portfolio returns vector x.

Arguments

  • x::VecNum: Portfolio returns vector.

Examples

julia> MeanReturn()MeanReturn  settings ┼ HierarchicalRiskMeasureSettings           │   scale ┴ Float64: 1.0         w ┼ nothing      flag ┴ Bool: false

Related

source
PortfolioOptimisers.port_opt_viewMethod
port_opt_view(x, i, args...; kwargs...) -> nothing_scalar_array_view(x, i)

Sub-select an estimator, result, or algorithm to the asset/observation index i.

port_opt_view is the index-selection counterpart of factory: where factory threads runtime values down a composed struct tree, port_opt_view threads an index selection — restricting every data-bearing field and composed child to the subset i. It is the mechanism that makes meta-optimisers (NestedClustered, SubsetResampling) and cross-validation variants operate on subproblems with identical struct shapes.

Callers do not normally call port_opt_view directly; it is driven by meta-optimisers and cross-validation internals. It is public (not exported) because extension authors who implement a new composed estimator may need to define a method. Use @vprop on data-bearing fields to have the method generated automatically.

This universal fallback handles leaf values: arrays are sliced via nothing_scalar_array_view; scalars, nothing, estimators without data fields, and algorithms pass through unchanged. Composed structs that recurse into children define their own (more specific) method — emitted by @vprop or hand-written.

The threaded tail args... (typically the returns matrix X for the JuMP families) and any kwargs are accepted and dropped here, so a macro-threaded port_opt_view(child, i, X) never MethodErrors on a leaf field.

Algorithm

  1. Drop args... and kwargs.... This method is the leaf of the recursion, so it threads nothing further.
  2. Return nothing_scalar_array_view of x at i, whose own algorithm names the rule for each leaf type.

Related

source
PortfolioOptimisers.MeanReturnRiskRatioType
struct MeanReturnRiskRatio{__T_settings, __T_rt, __T_rk, __T_sca, __T_rf} <: NonOptimisationRiskMeasure

Represents a mean return to risk ratio measure.

MeanReturnRiskRatio computes the ratio of the mean portfolio return (minus a risk-free rate) to a risk measure, used for performance analysis and comparison. It generalises the Sharpe ratio by allowing any risk measure in the denominator.

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 (computed by rt).
  • $r_f$: Risk-free rate.
  • $\rho$: Base risk measure (computed by rk).

Fields

  • settings: Risk measure settings.
  • rt: Mean return estimator.
  • rk: Risk measure for ratio computation, or a vector of them scalarised by sca.
  • sca: Scalariser combining the risk measures in rk into one number. Inert when rk holds a single measure. The field beats a sca keyword supplied at the call site.
  • rf: Risk-free rate.

Constructors

MeanReturnRiskRatio(;    settings::HierarchicalRiskMeasureSettings = HierarchicalRiskMeasureSettings(),    rt::MeanReturn = MeanReturn(),    rk::BaseRM_VecBaseRM = ConditionalValueatRisk(),    sca::Scalariser = SumScalariser(),    rf::Number = 0.0) -> MeanReturnRiskRatio

Keywords correspond to the struct's fields.

Multiplicity

rk takes one risk measure or a vector of them. A vector is scalarised into one number by sca, each element weighted by its own settings.scale. The field beats a caller's sca keyword, so a figure reported from this type is always the one the type names.

Validation

  • If rk is a vector: !isempty(rk).
  • isfinite(rf).

Propagated parameters

When factory is called on this type, the following @fprop-tagged fields are automatically propagated:

  • rt: Recursively updated via factory.
  • rk: Recursively updated via factory.

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 ┼ SumScalariser()        rf ┴ Float64: 0.0

Related

source
PortfolioOptimisers.factoryMethod
factory(a::Union{Nothing, <:AbstractEstimator, <:AbstractAlgorithm,
                 <:AbstractResult}, args...; kwargs...) -> a
factory(a::AbstractVector{<:Union{Nothing, <:AbstractEstimator, <:AbstractAlgorithm,
                                  <:AbstractResult}}, args...; kwargs...) -> Vector

No-op factory function for constructing objects with a uniform interface.

Defining methods which dispatch on the first argument allows for a consistent factory interface across different types.

factory and port_opt_view are the two propagation mechanisms in this library. They are duals: factory threads runtime values (prior moments, observation weights, previous portfolio weights) down through a composed struct tree; port_opt_view threads an index selection (a subset of assets or observations) down through the same tree.

The vector method is the one forwarding contract for every vector-valued propagation field: it applies factory to each element and forwards args... and kwargs... unchanged, so a family that admits a vector of estimators, algorithms, or results needs no method of its own. A family that needs more than the forward, such as a concrete element type (concrete_typed_array_if_abstract), defines its own more specific method.

Algorithm

The scalar method:

  1. Return a unchanged, and drop args... and kwargs.... This method is the leaf of the recursion, and it is what makes an untagged type safe to call the verb on.

The vector method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... unchanged.
  2. Collect the results into a new vector, in the order of a, and return it.

A @propagatable struct with at least one @fprop- or @wprop-tagged field carries a generated method that dominates the scalar method. That method rebuilds the struct with its keyword constructor, sending each @fprop field through factory_child and each @wprop field through _wprop.

Arguments

  • a: Indicates no object should be constructed, or a vector whose elements are rebuilt one by one.
  • args...: Arbitrary positional arguments (ignored by the scalar method, forwarded by the vector method).
  • kwargs...: Arbitrary keyword arguments (ignored by the scalar method, forwarded by the vector method).

Returns

  • a: The input unchanged.
  • v::Vector: The element-wise rebuilds, for the vector method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source
factory(
    rs::AbstractBaseRiskMeasure,
    args...;
    kwargs...
) -> GenericValueatRiskRange{RiskMeasureSettings{__T_scale, __T_ub, __T_rke}} where {__T_scale, __T_ub, __T_rke}

Return the risk measure rs unchanged.

Identity pass-through used when a risk measure is provided in a context that calls factory.

Related

source
PortfolioOptimisers.factoryMethod
factory(a::Union{Nothing, <:AbstractEstimator, <:AbstractAlgorithm,
                 <:AbstractResult}, args...; kwargs...) -> a
factory(a::AbstractVector{<:Union{Nothing, <:AbstractEstimator, <:AbstractAlgorithm,
                                  <:AbstractResult}}, args...; kwargs...) -> Vector

No-op factory function for constructing objects with a uniform interface.

Defining methods which dispatch on the first argument allows for a consistent factory interface across different types.

factory and port_opt_view are the two propagation mechanisms in this library. They are duals: factory threads runtime values (prior moments, observation weights, previous portfolio weights) down through a composed struct tree; port_opt_view threads an index selection (a subset of assets or observations) down through the same tree.

The vector method is the one forwarding contract for every vector-valued propagation field: it applies factory to each element and forwards args... and kwargs... unchanged, so a family that admits a vector of estimators, algorithms, or results needs no method of its own. A family that needs more than the forward, such as a concrete element type (concrete_typed_array_if_abstract), defines its own more specific method.

Algorithm

The scalar method:

  1. Return a unchanged, and drop args... and kwargs.... This method is the leaf of the recursion, and it is what makes an untagged type safe to call the verb on.

The vector method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... unchanged.
  2. Collect the results into a new vector, in the order of a, and return it.

A @propagatable struct with at least one @fprop- or @wprop-tagged field carries a generated method that dominates the scalar method. That method rebuilds the struct with its keyword constructor, sending each @fprop field through factory_child and each @wprop field through _wprop.

Arguments

  • a: Indicates no object should be constructed, or a vector whose elements are rebuilt one by one.
  • args...: Arbitrary positional arguments (ignored by the scalar method, forwarded by the vector method).
  • kwargs...: Arbitrary keyword arguments (ignored by the scalar method, forwarded by the vector method).

Returns

  • a: The input unchanged.
  • v::Vector: The element-wise rebuilds, for the vector method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source
factory(
    rs::AbstractBaseRiskMeasure,
    args...;
    kwargs...
) -> GenericValueatRiskRange{RiskMeasureSettings{__T_scale, __T_ub, __T_rke}} where {__T_scale, __T_ub, __T_rke}

Return the risk measure rs unchanged.

Identity pass-through used when a risk measure is provided in a context that calls factory.

Related

source
PortfolioOptimisers.ThirdCentralMomentType
struct ThirdCentralMoment{__T_settings, __T_w, __T_mu} <: NonOptimisationRiskMeasure

Represents the Third Central Moment risk measure.

ThirdCentralMoment computes the third central moment of portfolio returns about a specified centre. It is used as a measure of the asymmetry (skewness) of the return distribution in higher-order portfolio optimisation.

Mathematical definition

Let $\mu$ be the specified centre and $\delta_t = x_t - \mu$ the centred deviations. The third central moment is:

\[\begin{align} m_3(\boldsymbol{x}) &= \frac{1}{T} \sum_{t=1}^{T} \delta_t^3\,. \end{align}\]

Where:

  • $m_3(\boldsymbol{x})$: Third central moment of portfolio returns.
  • $\boldsymbol{x}$: Portfolio returns vector $T \times 1$.
  • $T$: Number of observations.
  • $\mu$: Specified centre of the distribution.
  • $\delta_t = x_t - \mu$: Centred deviation at period $t$.

For observation-weighted samples, the weighted mean is used.

Fields

  • settings: Risk measure settings.
  • w: Optional observation weights vector observations × 1, or a concrete subtype of DynamicAbstractWeights. If nothing, the computation is unweighted.
  • mu: Optional centre the moment is taken about, a scalar or a vector assets × 1. Also admits a Deferred Quantity — an expected returns estimator or a prior estimator that computes the centre against the optimisation's own prior, at factory time (see MuSlot and resolve_deferred_quantities). If nothing, the prior supplies it.

Constructors

ThirdCentralMoment(;    settings::HierarchicalRiskMeasureSettings = HierarchicalRiskMeasureSettings(),    w::Option{<:ObsWeights} = nothing,    mu::Option{<:MuSlot} = nothing) -> ThirdCentralMoment

Keywords correspond to the struct's fields.

Validation

  • If mu is a VecNum: !isempty(mu).
  • If w is not nothing, !isempty(w).
Warning

A stated mu is pinned: it crosses a Cross-Validation fold or a subset view as the whole universe's answer, so it does not follow the refit 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.

Functor

(r::ThirdCentralMoment)(w::VecNum, X::MatNum, fees = nothing)

Computes the third central moment of the portfolio returns.

Arguments

  • w::VecNum: Portfolio weights vector.
  • X::MatNum: Asset returns matrix ($T \times N$).
  • fees: Optional fee structure.

View parameters

When port_opt_view is called on this type, the following @vprop-tagged fields are automatically subset to the selected indices:

  • mu: A stated value is sliced to the selected indices via port_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

Related

source
PortfolioOptimisers.port_opt_viewMethod
port_opt_view(x, i, args...; kwargs...) -> nothing_scalar_array_view(x, i)

Sub-select an estimator, result, or algorithm to the asset/observation index i.

port_opt_view is the index-selection counterpart of factory: where factory threads runtime values down a composed struct tree, port_opt_view threads an index selection — restricting every data-bearing field and composed child to the subset i. It is the mechanism that makes meta-optimisers (NestedClustered, SubsetResampling) and cross-validation variants operate on subproblems with identical struct shapes.

Callers do not normally call port_opt_view directly; it is driven by meta-optimisers and cross-validation internals. It is public (not exported) because extension authors who implement a new composed estimator may need to define a method. Use @vprop on data-bearing fields to have the method generated automatically.

This universal fallback handles leaf values: arrays are sliced via nothing_scalar_array_view; scalars, nothing, estimators without data fields, and algorithms pass through unchanged. Composed structs that recurse into children define their own (more specific) method — emitted by @vprop or hand-written.

The threaded tail args... (typically the returns matrix X for the JuMP families) and any kwargs are accepted and dropped here, so a macro-threaded port_opt_view(child, i, X) never MethodErrors on a leaf field.

Algorithm

  1. Drop args... and kwargs.... This method is the leaf of the recursion, so it threads nothing further.
  2. Return nothing_scalar_array_view of x at i, whose own algorithm names the rule for each leaf type.

Related

source
PortfolioOptimisers.calc_moment_targetMethod
calc_moment_target(::TCM_Sk{Nothing, Nothing}, ::Any, x::VecNum)
calc_moment_target(r::TCM_Sk{<:StatsBase.AbstractWeights, Nothing}, ::Any, x::VecNum)
calc_moment_target(r::TCM_Sk{<:Any, <:VecNum}, w::VecNum, ::Any)
calc_moment_target(r::TCM_Sk{<:Any, <:VecScalar}, w::VecNum, ::Any)
calc_moment_target(r::TCM_Sk{<:Any, <:Number}, ::Any, ::Any)

Compute the centering target for ThirdCentralMoment and Skewness risk measures.

Dispatches on the observation-weight type T1 and mean type T2 of TCM_Sk:

  • No weights, no mu: arithmetic mean of x.
  • AbstractWeights, no mu: weighted mean of x.
  • VecNum mu: dot product $\boldsymbol{w}^\intercal \boldsymbol{\mu}$.
  • VecScalar mu: $\boldsymbol{w}^\intercal \boldsymbol{\mu}_v + \mu_s$.
  • Number mu: the scalar r.mu directly.

Related

source
PortfolioOptimisers.calc_deviations_vecFunction
calc_deviations_vec(
    r::Union{Skewness{<:Any, <:Any, <:Any, T1, T2}, ThirdCentralMoment{<:Any, T1, T2}} where {T1, T2},
    w::AbstractVector{<:Union{var"#s89", var"#s88"} where {var"#s89"<:Number, var"#s88"<:AbstractJuMPScalar}},
    X::AbstractMatrix{<:Union{var"#s89", var"#s88"} where {var"#s89"<:Number, var"#s88"<:AbstractJuMPScalar}}
) -> Any
calc_deviations_vec(
    r::Union{Skewness{<:Any, <:Any, <:Any, T1, T2}, ThirdCentralMoment{<:Any, T1, T2}} where {T1, T2},
    w::AbstractVector{<:Union{var"#s89", var"#s88"} where {var"#s89"<:Number, var"#s88"<:AbstractJuMPScalar}},
    X::AbstractMatrix{<:Union{var"#s89", var"#s88"} where {var"#s89"<:Number, var"#s88"<:AbstractJuMPScalar}},
    fees::Union{Nothing, Fees}
) -> Any

Compute the vector of deviations from the centering target for ThirdCentralMoment and Skewness risk measures.

Related

source
PortfolioOptimisers.calc_deviations_vecMethod
calc_deviations_vec(
    r::Union{Skewness{<:Any, <:Any, <:Any, T1, T2}, ThirdCentralMoment{<:Any, T1, T2}} where {T1, T2},
    x::AbstractVector{<:Union{var"#s89", var"#s88"} where {var"#s89"<:Number, var"#s88"<:AbstractJuMPScalar}}
) -> Any

Compute the vector of deviations from the centering target for a precomputed returns series for ThirdCentralMoment and Skewness risk measures.

Single-argument form used by the precomputed-returns functor r(x::VecNum) (ADR 0007).

Related

source