Base Risk Measures

Every risk measure has a full type name, and many also have a short alias, which the aliases page lists.

You can call a concrete risk measure as a function to compute its risk. risk_input_kind says what the call takes, such as the portfolio weights or a series of returns. expected_risk also computes the risk of a portfolio.

Choosing a risk measure

The Compatibility column says where you can use each measure:

  • JuMP + Hierarchical: the measure has a JuMP formulation, so a JuMP optimiser can use it as the objective or as a constraint, and a hierarchical optimiser can also use it.
  • Hierarchical: a hierarchical optimiser can use it, but it has no JuMP formulation.
  • -: you can use it only to analyse a portfolio.

The Requirements column names the cones or variables that the measure needs, in a JuMP model or in the solver that computes it:

  • QP: a quadratic expression.
  • NOC: a norm-one cone.
  • SOC: a second-order cone.
  • RSOC: a rotated second-order cone.
  • NIC: a norm-infinity cone.
  • EC: an exponential cone.
  • PC: a three-dimensional power cone.
  • Sym: a symmetric matrix.
  • SDP: a semi-definite constraint.
  • PSD: a positive semi-definite cone.
  • MIP: mixed-integer variables.
  • *: the requirements of the risk measures it holds.
  • -: nothing beyond linear constraints, or not applicable.

The last column names the solver that the library recommends.

TypeName (Alias)CompatibilityRequirementsRec. Solver
DispersionVarianceJuMP + HierarchicalQP, SOCClarabel
DispersionSDP graph / Risk contribution VarianceJuMP + HierarchicalSDPClarabel, SCS
DispersionStandardDeviation (SD)JuMP + HierarchicalSOCClarabel
DispersionBox UncertaintySetVariance (UcVariance)JuMP + HierarchicalSymClarabel
DispersionEllipse UncertaintySetVariance (UcVariance)JuMP + HierarchicalSym, PSD, SOCClarabel, SCS
DispersionLowOrderMoment (FLM)JuMP + Hierarchical-Clarabel
DispersionLowOrderMoment (MAD)JuMP + Hierarchical-Clarabel
DispersionDirect / Squared SOC LowOrderMoment (SCM, SLM)JuMP + HierarchicalQP, SOCClarabel
DispersionSum of Squares LowOrderMoment (SCM, SLM)JuMP + HierarchicalSOC, RSOCClarabel
DispersionSOC LowOrderMoment (SCM, SLM)JuMP + HierarchicalSOCClarabel
DispersionLowOrderMoment (ECM, ELM)JuMP + HierarchicalPCClarabel
DispersionHighOrderMoment (TLM, SSK, FTCM, FTLM, KT, SKT)Hierarchical--
DispersionDirect / Squared SOC Exact KurtosisJuMP + HierarchicalQP, SOC, PSDClarabel, SCS
DispersionSum of Squares Exact KurtosisJuMP + HierarchicalSOC, RSOC, PSDClarabel, SCS
DispersionSOC Exact KurtosisJuMP + HierarchicalSOC, PSDClarabel, SCS
DispersionDirect / Squared SOC Approx KurtosisJuMP + HierarchicalQP, SOCClarabel
DispersionSum of Squares Approx KurtosisJuMP + HierarchicalSOC, RSOCClarabel
DispersionSOC Approx KurtosisJuMP + HierarchicalSOCClarabel
DispersionNegativeSkewnessJuMP + HierarchicalQP, SOCClarabel
DispersionSquare Root NegativeSkewnessJuMP + HierarchicalSOCClarabel
Tail lossExact ValueatRisk (VaR)JuMP + HierarchicalMIPPajarito (Clarabel + HiGHS)
Tail lossApprox ValueatRisk (VaR)JuMP + HierarchicalSOCClarabel
Tail drawdownDrawdownatRisk (DaR)JuMP + HierarchicalMIPPajarito (Clarabel + HiGHS)
Tail drawdownRelativeDrawdownatRisk (R_DaR)Hierarchical-Clarabel
DispersionExact ValueatRiskRange (VaR_RG)JuMP + HierarchicalMIPPajarito (Clarabel + HiGHS)
DispersionApprox ValueatRiskRange (VaR_RG)JuMP + HierarchicalSOCClarabel
Tail lossConditionalValueatRisk (CVaR)JuMP + Hierarchical-Clarabel
Tail lossDistributionallyRobustConditionalValueatRisk (DRCVaR)JuMP + HierarchicalNICClarabel
Tail drawdownConditionalDrawdownatRisk (CDaR)JuMP + Hierarchical-Clarabel
Tail drawdownDistributionallyRobustConditionalDrawdownatRisk (DRCDaR)JuMP + HierarchicalNICClarabel
Tail drawdownRelativeConditionalDrawdownatRisk (R_CDaR)Hierarchical-Clarabel
DispersionConditionalValueatRiskRange (CVaR_RG)JuMP + Hierarchical-Clarabel
DispersionDistributionallyRobustConditionalValueatRiskRange (DRCVaR_RG)JuMP + HierarchicalNICClarabel
Tail lossEntropicValueatRisk (EVaR)JuMP + HierarchicalECClarabel
Tail drawdownEntropicDrawdownatRisk (EDaR)JuMP + HierarchicalECClarabel
Tail drawdownRelativeEntropicDrawdownatRisk (R_EDaR)HierarchicalECClarabel
DispersionEntropicValueatRiskRange (EVaR_RG)JuMP + HierarchicalECClarabel
Tail lossRelativisticValueatRisk (RLVaR)JuMP + HierarchicalPCClarabel
Tail drawdownRelativisticDrawdownatRisk (RLDaR)JuMP + HierarchicalPCClarabel
Tail drawdownRelativeRelativisticDrawdownatRisk (R_RLDaR)HierarchicalPCClarabel
DispersionRelativisticValueatRiskRange (RLVaR_RG)JuMP + HierarchicalPCClarabel
Tail lossPowerNormValueatRisk (PNVaR)JuMP + HierarchicalPCClarabel
Tail drawdownPowerNormDrawdownatRisk (PNDaR)JuMP + HierarchicalPCClarabel
Tail drawdownRelativePowerNormDrawdownatRisk (R_PNDaR)HierarchicalPCClarabel
DispersionPowerNormValueatRiskRange (PNVaR_RG)JuMP + HierarchicalPCClarabel
DispersionExact OrderedWeightsArray (OWA_GMD, OWA_LMoment)JuMP + Hierarchical-Clarabel
DispersionApprox OrderedWeightsArray (OWA_GMD, OWA_LMoment)JuMP + HierarchicalPCClarabel
Tail lossExact OrderedWeightsArray (OWA_CVaR, OWA_TG, OWA_WR)JuMP + Hierarchical-Clarabel
Tail lossApprox OrderedWeightsArray (OWA_CVaR, OWA_TG, OWA_WR)JuMP + HierarchicalPCClarabel
DispersionExact OrderedWeightsArrayRange (OWA_RG, OWA_CVaR_RG, OWA_TG_RG)JuMP + Hierarchical-Clarabel
DispersionApprox OrderedWeightsArrayRange (OWA_RG, OWA_CVaR_RG, OWA_TG_RG)JuMP + HierarchicalPCClarabel
DrawdownAverageDrawdown (ADD)JuMP + Hierarchical-Clarabel
DrawdownRelativeAverageDrawdown (R_ADD)Hierarchical--
DrawdownUlcerIndex (UCI)JuMP + HierarchicalSOCClarabel
DrawdownRelativeUlcerIndex (R_UCI)Hierarchical--
Tail drawdownMaximumDrawdown (MDD)JuMP + Hierarchical-Clarabel
Tail drawdownRelativeMaximumDrawdown (R_MDD)Hierarchical--
DispersionDirect BrownianDistanceVariance (BDVariance)JuMP + HierarchicalQPClarabel
DispersionSum of Squares BrownianDistanceVariance (BDVariance)JuMP + HierarchicalQP, RSOCClarabel
Tail lossWorstRealisation (WR)JuMP + Hierarchical-Clarabel
DispersionRange (RG)JuMP + Hierarchical-Clarabel
TurnoverTurnoverRiskMeasure (TnRM)JuMP + HierarchicalNOCClarabel
TrackingL1 Norm TrackingRiskMeasure (TrRM)JuMP + HierarchicalNOCClarabel
TrackingL2 Norm TrackingRiskMeasure (TrRM)JuMP + HierarchicalSOCClarabel
TrackingSquared L2 Norm TrackingRiskMeasure (TrRM)JuMP + HierarchicalQP, SOCClarabel
TrackingLp Norm TrackingRiskMeasure (TrRM)JuMP + HierarchicalPCClarabel
TrackingInfinity Norm TrackingRiskMeasure (TrRM)JuMP + HierarchicalNICClarabel
Risk trackingIndependent variable RiskTrackingRiskMeasure (RkTrRM)JuMP + Hierarchical*Clarabel
Risk trackingDependent variable RiskTrackingRiskMeasure (RkTrRM)JuMP + HierarchicalNOC, *Clarabel
DispersionVarianceSkewKurtosis (VSK)JuMP + HierarchicalSym, PSDSCS
DispersionGenericValueatRiskRange (GVaR_RG)JuMP + Hierarchical*Clarabel
RatioRiskRatioHierarchical**
RatioNonOptimisationRiskRatio (NonOptRkRatio)-**
FlatEqualRisk---
DispersionMedianAbsoluteDeviationHierarchical--
PerformanceMeanReturn---
PerformanceMeanReturnRiskRatio---
PerformanceExpectedReturn---
PerformanceExpectedReturnRiskRatio---
DispersionThirdCentralMoment---
DispersionSkewness---
PortfolioOptimisers.RiskMeasure — Type
abstract type RiskMeasure <: OptimisationRiskMeasure

Abstract supertype for standard risk measures used in portfolio optimisation.

Subtype RiskMeasure for a concrete risk measure that a JuMP optimiser builds into its model, as an objective or as a constraint. A clustering optimiser accepts it too.

Interfaces

To implement a new risk measure, subtype RiskMeasure with a settings::RiskMeasureSettings field, and implement the methods below. set_risk_expression! reads the scale and the rke of the field, set_risk_upper_bound! reads its ub, and expected_risk reads its scale when several measures combine.

risk_input_kind

  • risk_input_kind(r::MyRiskMeasure) -> RiskInputKind: Declare which of the three functor shapes the measure exposes. There is no default: an undeclared measure throws rather than routing to the wrong input shape.

Arguments

  • r: The concrete subtype instance.

Returns

  • kind::RiskInputKind: One of NetReturnsInput(), WeightsReturnsFeesInput() or WeightsInput().

The functor

expected_risk evaluates the measure as a functor, in the shape its kind declares:

supports_precomputed_returns

  • supports_precomputed_returns(r::MyRiskMeasure) -> Bool: Whether the risk of the measure is a function of the net return series alone. A WeightsReturnsFeesInput measure declares it, and the fallback for that kind throws rather than guessing. The other two kinds answer through the kind itself.

set_risk_constraints!

  • set_risk_constraints!(model::JuMP.Model, i, r::MyRiskMeasure, opt::RiskConstraintOwner, pr::AbstractPriorResult, args...; kwargs...): Builds the measure into the model of a JuMP optimiser, or of a programme Allocation Set. There is no fallback.

The method builds the risk expression from the model's weights, then registers it with set_risk_bounds_and_expression!, which reads the bound and the contribution to the aggregate risk expression off r.settings. Scale every constraint by get_constraint_scale, and multiply any constant bound by get_k, so the bound is compared against unrescaled weights under a ratio objective.

Optional methods

Each has a fallback on AbstractBaseRiskMeasure:

  • needs_previous_weights(r::MyRiskMeasure) -> Bool: true for a measure that reads the previous weights; the fallback answers false.
  • bigger_is_better(r::MyRiskMeasure) -> Bool: true for a measure a caller maximises; the fallback answers false.
  • factory: rebuild the measure against a prior result before it is evaluated, for a measure whose slots are filled from the prior.

A Range variant subtypes RangeRiskMeasure, whose # Interfaces section states two more methods.

Related

source
PortfolioOptimisers.RangeRiskMeasure — Type
abstract type RangeRiskMeasure <: RiskMeasure

Abstract supertype for the Range variants: the risk measures that are the sum of a measure of the losses and a measure of the gains.

A range penalises the spread between the two tails of the net portfolio returns. Its value is $\mathcal{R}_{\mathrm{loss}}(\hat{\boldsymbol{r}}) + \mathcal{R}_{\mathrm{gain}}(-\hat{\boldsymbol{r}})$, so the gain tail reads the negated returns and the two tails add. A formulation of a range either decomposes into two point measures, which the single-tail builders build, or fuses the two tails into one programme.

Interfaces

A range is a RiskMeasure, so it implements the methods of that # Interfaces section. Its set_risk_constraints! comes from one of two forms.

A formulation that decomposes

Implement the two methods below. The method of set_risk_constraints! for a RangeRiskMeasure then builds the range: it builds loss with loss = true and gain with loss = false, and it registers their sum once.

  • range_tails(r::MyRange) -> RangeTails: The two point measures of the range, the Range Tails. Each tail carries rke = false.
  • range_risk_key(r::MyRange) -> Symbol: The Model State key of the sum, by the convention <base>_range_risk_.

A formulation that fuses

Implement a method of set_risk_constraints! for the formulation, and declare no range_tails. Its method is more specific than the method for a RangeRiskMeasure. range_tails then throws an ArgumentError that names the type.

Related

source
PortfolioOptimisers.HierarchicalRiskMeasure — Type
abstract type HierarchicalRiskMeasure <: OptimisationRiskMeasure

Abstract supertype for hierarchical risk measures used in portfolio optimisation.

Subtype HierarchicalRiskMeasure to implement risk measures that operate on hierarchical or clustered portfolio structures. These measures are designed for use as objectives or constraints in optimisation problems that leverage asset clustering, hierarchical risk parity, or similar techniques.

Interfaces

A hierarchical measure is only ever evaluated at the value level, through expected_risk, so it builds no JuMP model and needs no model builder. To implement a new one, subtype HierarchicalRiskMeasure with a settings::HierarchicalRiskMeasureSettings field, and implement the methods below. expected_risk reads the scale of the field when several measures combine.

risk_input_kind

  • risk_input_kind(r::MyRiskMeasure) -> RiskInputKind: Declare which of the three functor shapes the measure exposes. There is no default: an undeclared measure throws rather than routing to the wrong input shape.

Arguments

  • r: The concrete subtype instance.

Returns

  • kind::RiskInputKind: One of NetReturnsInput(), WeightsReturnsFeesInput() or WeightsInput().

The functor

expected_risk evaluates the measure as a functor, in the shape its kind declares:

supports_precomputed_returns

  • supports_precomputed_returns(r::MyRiskMeasure) -> Bool: Whether the risk of the measure is a function of the net return series alone. A WeightsReturnsFeesInput measure declares it, and the fallback for that kind throws rather than guessing. The other two kinds answer through the kind itself.

Optional methods

Each has a fallback on AbstractBaseRiskMeasure:

  • needs_previous_weights(r::MyRiskMeasure) -> Bool: true for a measure that reads the previous weights; the fallback answers false.
  • bigger_is_better(r::MyRiskMeasure) -> Bool: true for a measure a caller maximises; the fallback answers false.
  • factory: rebuild the measure against a prior result before it is evaluated, for a measure whose slots are filled from the prior.

Related

source
PortfolioOptimisers.Frontier — Type
struct Frontier{__T_N, __T_factor, __T_bound} <: AbstractAlgorithm

Sweeps the efficient frontier by solving the model once at each of N evenly spaced bound values.

Stand this in a risk measure's bound slot instead of a number. The optimisation then reads the span off two corner portfolios, divides it into N levels, and returns one portfolio per level. The corners are a minimum-risk solve and a maximum-return solve of the whole model. When the bound is on the measure that the minimum-risk solve minimises, the span covers the whole attainable range of the bound. When the bound is on one term of a composite measure, or on one measure of several, the span runs between the values of the bound at the two corners, and the term can reach a lower value than its value at the minimum-risk corner.

The levels are evenly spaced in the units of the risk expression the bound is applied to, which bound names, and not in the units of the measure. See SquareRootBound for the case where the two differ.

A sweep under `MaximumRatio`

Under MaximumRatio, a sweep needs a solver wrapper. This holds for a Frontier and for a vector of bounds, on a risk ceiling and on a return floor of JuMPReturnsSettings. The objective homogenises the model with one more variable, the ratio factor. A sweep builds the model once and writes each level into a JuMP.Parameter. The bound row multiplies that parameter by the ratio factor. A solver that receives the parameter as a variable sees a product of two variables, and a conic solver such as Clarabel refuses it with MOI.UnsupportedConstraint{MOI.ScalarQuadraticFunction{Float64}, MOI.LessThan{Float64}}. Each point then returns an OptimisationFailure.

Wrap the solver in the Optimizer of ParametricOptInterface. The wrapper puts the value of each parameter into the row before the solve, so the solver receives a linear row. Version 0.15 or later takes the type of the inner solver, and passes the settings of the Solver to it.

import ParametricOptInterface as POIusing Clarabelslv = Solver(; name = :clarabel, solver = () -> POI.Optimizer(Clarabel.Optimizer),             settings = Dict("verbose" => false))

The span of a Frontier does not read the homogenised model. A minimum-risk solve on that model gives the maximum-ratio portfolio, and a maximum-return solve is unbounded. So the span comes from a second model that is not homogenised, with resolve_ratio_frontier!, and it is the span of the same Frontier under MinimumRisk. The second model costs one more model build. A risk ceiling above the risk of the maximum-ratio portfolio does not bind, so every level above that risk returns the maximum-ratio portfolio.

Under every other objective the ratio factor is the number 1, and the sweep needs no wrapper. The efficient frontier example sweeps a MaximumRatio frontier in this way.

Page 82 of [32] states the efficient set for the variance, as the minimum variance for a given expected return and the maximum expected return for a given variance. Equations 8.7 and 8.10 of [12] state the two programmes for a general convex risk measure, and the text of that section builds a frontier by a sweep of the bound.

Fields

  • N: Number of sweep points on the efficient frontier. The sweep solves the model N times, at N evenly spaced bound values.
  • factor: Multiplier applied to both ends of the sweep span after bound has transformed them. It carries a formulation's own correction factor, such as the inv(1 / (T - ddof)) of a second-moment bound.
  • bound: FrontierBoundEstimator that converts a bound value into the units of the risk expression the bound is applied to. The sweep points are evenly spaced in those units, not in the units of the measure.

Constructors

Frontier(;    N::Integer = 20,    bound::FrontierBoundEstimator = LinearBound()) -> Frontier

Creates a Frontier with N points, a scaling factor of 1, and the specified bound strategy. Used to set appropriate frontier bounds in variance_risk_bounds_val and second_moment_bound_val.

Frontier(N::Integer, factor::Number = 1, bound::FrontierBoundEstimator = LinearBound()) -> Frontier

Creates a Frontier whose factor and bound a formulation chose. The keyword form pins factor to 1, because a caller states a bound in the units of the measure and knows nothing of the internal scaling of the model. A formulation does know: it reads the Frontier of the caller, keeps its N, and rebuilds it with the conversion that its own risk expression needs, as variance_risk_bounds_val and second_moment_bound_val do. The sweep values come later, in rebuild_risk_frontier, once the two corner portfolios are known: bound transforms each end of the span, factor multiplies both, and range divides the result into N levels.

Validation

  • N > 1 and N <= RESOURCE_LIMITS[].max_frontier. The sweep runs from the minimum-risk end to the maximum-return end, so it needs two points. Each sweep point runs a full solve, see RESOURCE_LIMITS. This is the cheap early check on one bound. The sweep across several swept bounds is their product, capped separately at Model Assembly by assert_frontier_sweep_cap.
  • isfinite(factor) and factor > 0.

Examples

julia> Frontier(; N = 15)Frontier       N ┼ Int64: 15  factor ┼ Int64: 1   bound ┴ LinearBound()

Related

References

  • [32] H. Markowitz. Portfolio selection. The Journal of Finance 7, 77–91 (1952). Page 82.
  • [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Sections 8.2.1 and 8.2.2, Equations 8.7 and 8.10.
source
PortfolioOptimisers.AbstractRiskMeasureSettings — Type
abstract type AbstractRiskMeasureSettings <: AbstractEstimator

Abstract supertype for all risk measure settings.

A settings object carries the three things a risk measure needs that are not part of the risk itself: the combination weight scale, whether the measure contributes to the model's risk expression (rke), and the bound the optimiser enforces on the measure's own expression. All concrete risk measure settings types should subtype AbstractRiskMeasureSettings.

Interfaces

To implement a new concrete settings type, subtype AbstractRiskMeasureSettings and give it these fields:

Required fields

  • scale::Number: Combination weight, read by set_risk_expression! and by the value-level readers.
  • rke::Bool: Whether the measure contributes to the model's aggregate risk expression.

Optional field

Related

source
PortfolioOptimisers.RiskMeasureSettings — Type
struct RiskMeasureSettings{__T_scale, __T_ub, __T_rke} <: JuMPRiskMeasureSettings

Weights a risk measure inside an aggregate, and bounds its risk expression from above.

This is the settings type of every measure the optimiser minimises. ub is the maximum level of risk the solution may reach. Page 82 of [32] states this bound for the variance, as the maximum expected return for a given variance or less. Equation 8.10 of [12] states it for a general convex risk measure as $\bar{\phi}$, and a sweep of it builds an efficient frontier, which is what a Frontier in that slot does. scale weights the measure against its siblings when several are given, and rke decides whether it reaches the aggregate at all.

Fields

  • scale: Weight of this risk measure in the aggregate risk expression formed from a vector of measures. It is a combination weight, so it is inert on a single measure: an optimiser given one measure drops it before the risk expression is built, and the value-level readers ignore it too. The upper bound in ub binds on the measure's own expression, before scale is applied.
  • ub: Upper bound(s) on the measure's own risk expression. A scalar bounds one model. A vector and a Frontier are sweep axes, one solve per entry, so the optimisation returns one portfolio per bound value.
  • rke: Whether to include the risk measure value in the JuMP risk expression.

Constructors

RiskMeasureSettings(;    scale::Number = 1.0,    ub::Option{<:RkRtBounds} = nothing,    rke::Bool = true,) -> RiskMeasureSettings

Creates a RiskMeasureSettings instance with the specified scale, upper bound, and risk evaluation flag.

Validation

Examples

julia> RiskMeasureSettings()RiskMeasureSettings  scale ┼ Float64: 1.0     ub ┼ nothing    rke ┴ Bool: true

Related

References

  • [32] H. Markowitz. Portfolio selection. The Journal of Finance 7, 77–91 (1952). Page 82.
  • [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Section 8.2.2, Equation 8.10.
source
PortfolioOptimisers.HierarchicalRiskMeasureSettings — Type
struct HierarchicalRiskMeasureSettings{__T_scale} <: AbstractRiskMeasureSettings

Weights a hierarchical risk measure inside an aggregate, and carries no bound.

A clustering optimiser computes each cluster's risk as a number rather than building one model over the whole universe, so there is no risk expression for a bound to constrain and no ub field to hold one. scale is the only setting a HierarchicalRiskMeasure has, and it means what it means everywhere else: the measure's weight against its siblings when several are given.

Fields

  • scale: Weight of this risk measure in the aggregate risk expression formed from a vector of measures. It is a combination weight, so it is inert on a single measure: an optimiser given one measure drops it before the risk expression is built, and the value-level readers ignore it too. The upper bound in ub binds on the measure's own expression, before scale is applied.

Constructors

HierarchicalRiskMeasureSettings(;    scale::Number = 1.0) -> HierarchicalRiskMeasureSettings

Creates a HierarchicalRiskMeasureSettings instance with the specified scaling factor.

Validation

  • scale must be finite.

Examples

julia> HierarchicalRiskMeasureSettings()HierarchicalRiskMeasureSettings  scale ┴ Float64: 1.0

Related

source
PortfolioOptimisers.Scalariser — Type
abstract type Scalariser <: AbstractEstimator

Abstract supertype for scalarisation strategies used to combine multiple risk measures into a single scalar value for optimisation.

Subtype Scalariser to implement different methods for aggregating risk measures. These strategies are used in portfolio optimisation routines that require a single risk value from multiple risk measures.

Section 4.7.4 of [188] states the weighted sum as a scalarisation of a vector objective. No copy of the work that first states it was found. The family ports the cvxpy.transforms.scalarize module of [189], which adds the maximum and the log-sum-exp.

Two consumers, and only one of them is restricted

A scalariser is read at two levels, and they are not equally permissive.

  • The model level. A JuMP optimiser builds the aggregation into the model as an expression, so the strategy must have a convex form. NonHierarchicalScalariser and HierarchicalScalariser separate the strategies on this property. The two subtypes name the consumers that can build a strategy, not a property of the number it gives. JuMPOptimiser.sca is bounded to NonHierarchicalScalariser, so it refuses the hierarchical half. The clustering optimisers compute the risk of each cluster separately and accept either half.
  • The value level. expected_risk and the readers around it evaluate the measures first and combine the numbers they give. Nothing convex is built, so no strategy is refused for its form. Every sca keyword and every sca result field at this level is bounded to Scalariser, and all four scalarisers are admitted, MinScalariser included.

So a HierarchicalScalariser on a value-level call is correct. The word "hierarchical" in the name of the subtype says which estimators accept the strategy, not where its number has a meaning.

The weights are the measures' own scale

Every strategy below is a weighted aggregation, and it reads its weights from one place, the scale field of the settings of each measure. Both levels apply the weight before the strategy runs. The model applies it in set_risk_expression!, which pushes scale * r_expr. The value level applies it in expected_risk, which multiplies each element by r.settings.scale. So no strategy below carries a weight vector of its own.

The model reports an upper bound unless the objective pulls it down

SumScalariser builds an expression, so it adds no gap of its own. model[:risk] is the sum of the entries of risk_vec whatever the objective is. The other two build a variable that the aggregation bounds from below, and a minimising objective pulls the variable down onto the aggregation. Under MaximumReturn nothing pulls, so model[:risk] reports an upper bound of the aggregation. Read the exact figure back with expected_risk.

An entry of risk_vec is exact only when the model of its own measure is exact. Most measures enter through an epigraph variable, and Variance under its default SquaredSOCRiskExpr is one of them. Under MaximumReturn that variable also stands above the value of its measure. So SumScalariser reports an upper bound there too, unless every measure has an exact expression, as Variance under QuadRiskExpr has.

The bound that the model enforces does not change. An ub on the aggregate constrains the variable, and the variable stands above the aggregation, so the aggregation satisfies the bound too. Only the reported figure stands above the aggregation, and expected_risk gives the exact figure.

Interfaces

To implement a new scalarisation strategy, subtype NonHierarchicalScalariser when the aggregation has a convex JuMP form and HierarchicalScalariser when it does not, then implement:

Required method name

  • scalarise(f, sca::MyScalariser, itr; by = nothing): Combine the per-measure values f returns into one.

Arguments

  • f: Per-element evaluation closure.
  • sca: The strategy instance.
  • itr: Iterable of risk measures.
  • by: Optional selection key, for a strategy that picks one element rather than combining all of them.

Returns

  • The combined value, with the same shape as the values f returns.

Required for a NonHierarchicalScalariser

  • scalarise_risk_expression!(model::JuMP.Model, sca::MyScalariser): Collapse the model's risk_vec array into the single risk expression. A HierarchicalScalariser declares no such method, which is what the split means.

Related

References

  • [188] S. Boyd and L. Vandenberghe. Convex Optimization (Cambridge University Press, Cambridge, UK, 2004). Section 4.7.4, page 178. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
  • [189] S. Diamond and S. Boyd. CVXPY: A Python-embedded modeling language for convex optimization. Journal of Machine Learning Research 17, 1–5 (2016). Module cvxpy.transforms.scalarize.
source
PortfolioOptimisers.scalarise — Function
scalarise(f, sca::Option{<:Scalariser}, itr; by = nothing)

Reduce per-risk-measure values into a single scalarised value.

Applies f to every element of itr, a vector of risk measures or the pairs of one, and combines the results by the rule of the scalariser. f must return a Number, an AbstractArray, or a Tuple of these, and must return freshly allocated values (no views into buffers reused across iterations), since results may be retained across iterations.

The combining rules are:

  • SumScalariser and nothing: slot-wise sum of all values. f is expected to include the measure's settings.scale weight in its result. nothing is the default of every sca field and keyword, and it gives the sum.

  • MaxScalariser/MinScalariser:

    • by === nothing: slot-wise (elementwise) maximum/minimum across values.
    • by given: returns the one f result whose by(result) is the largest or the smallest. A tie keeps the earliest result.
  • LogSumExpScalariser: slot-wise logsumexp of gamma-scaled values, divided by gamma.

Algorithm

  1. Start the accumulator acc at nothing, and the winning key k at nothing beside it. LogSumExpScalariser starts neither, and takes steps 5 and 6 instead.
  2. Apply f to each element of itr in turn, giving v.
  3. Fold v into acc through the branch that sca selects. SumScalariser takes scalarise_combine(+, acc, v). MaxScalariser and MinScalariser take scalarise_combine(max, acc, v) and scalarise_combine(min, acc, v) while by is nothing.
  4. Given a by, read the key ki = by(v) in place of step 3, and take v and ki as the new acc and k when ki beats the k already held. A tie keeps the earlier element.
  5. Under LogSumExpScalariser, apply f to every element of itr, scale each result by sca.gamma with scalarise_map, and collect them into vs.
  6. Reduce vs slot-wise with scalarise_logsumexp, and divide the reduction by sca.gamma with scalarise_map.
  7. Return acc, or the value step 6 built.

Arguments

  • f: Per-element evaluation closure, applied to each element of itr.
  • sca: Scalarisation strategy. nothing gives the rule of SumScalariser.
  • itr: Iterable of risk measures (or pairs of them, when f needs the index).
  • by: Optional selection key for MaxScalariser/MinScalariser; ignored by the other scalarisers.

Returns

  • The scalarised value, with the same shape as the values returned by f.

Related

source
PortfolioOptimisers.SumScalariser — Type
struct SumScalariser <: NonHierarchicalScalariser

Adds the scaled risk measures together.

Every sca field and keyword defaults to nothing, and nothing gives this sum. It is the only strategy whose model form is an expression rather than a variable with constraints: scalarise_risk_expression! sums risk_vec into one affine or quadratic expression, so it is also the only one that takes a quadratic risk expression without a reformulation.

Mathematical definition

\[\begin{align} \phi &= \sum_{i=1}^{N} w_i \cdot r_i \,. \end{align}\]

Where:

  • $N$: Number of risk measures.
  • $i$: Subscript denoting the i-th risk measure.
  • $r_i$: i-th risk measure value.
  • $w_i$: Weight of the i-th risk measure.

Related

References

  • [188] S. Boyd and L. Vandenberghe. Convex Optimization (Cambridge University Press, Cambridge, UK, 2004). Section 4.7.4, page 178, Equation 4.60. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
  • [189] S. Diamond and S. Boyd. CVXPY: A Python-embedded modeling language for convex optimization. Journal of Machine Learning Research 17, 1–5 (2016). cvxpy.transforms.scalarize.weighted_sum.
source
PortfolioOptimisers.MaxScalariser — Type
struct MaxScalariser <: NonHierarchicalScalariser

Reports the largest of the scaled risk measures, so the aggregate is the worst of them.

The model form is a free variable held above every entry of risk_vec, and the objective pushes it down onto the largest entry. Under a minimum-risk objective the model agrees with expected_risk. Under a maximum-return objective it reports an upper bound, as Scalariser states for every strategy. A clustering optimisation computes the risk of each cluster separately, so a different measure can be the largest in each cluster.

Mathematical definition

\[\begin{align} \phi &= \underset{i \in (1,\,N)}{\max} \left(w_i \cdot r_i \right)\,. \end{align}\]

Where:

  • $N$: Number of risk measures.
  • $i$: Subscript denoting the i-th risk measure.
  • $r_i$: i-th risk measure value.
  • $w_i$: Weight of the i-th risk measure.

JuMP formulation

Relaxation

The encoding is not exact: the entries below bound the quantity instead of reproducing it, and the bound is tight only under the condition stated here.

  • The bounded quantity is risk, the free variable scalarise_risk_expression! creates for this strategy. The row risk_ms holds it at or above every entry of risk_vec, so model[:risk] stands above the maximum rather than on it.
  • The bound is tight while the objective pulls risk down, which a minimum-risk objective does. Under MaximumReturn nothing pulls, and model[:risk] is then an upper bound.
  • An ub on the aggregate is unaffected. It constrains risk, and the aggregation stands below risk, so the aggregation meets the bound too. Read the exact figure back with expected_risk.

Related

References

  • [189] S. Diamond and S. Boyd. CVXPY: A Python-embedded modeling language for convex optimization. Journal of Machine Learning Research 17, 1–5 (2016). cvxpy.transforms.scalarize.max. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
source
PortfolioOptimisers.MinScalariser — Type
struct MinScalariser <: HierarchicalScalariser

Reports the smallest of the scaled risk measures, so the aggregate is the mildest of them.

This library adds it. The source family has a weighted sum, a maximum and a log-sum-exp, and no minimum. A clustering optimisation computes the risk of each cluster separately, so a different measure can be the smallest in each cluster.

It is the one HierarchicalScalariser, because the minimisation of a minimum is not convex and a JuMP optimiser cannot build it. That restriction applies to the model only. At the value level the measures are already numbers, so every sca keyword and every sca result field there admits MinScalariser, as it admits the other three.

Mathematical definition

\[\begin{align} \phi &= \underset{i \in (1,\,N)}{\min} \left( w_i \cdot r_i \right)\,. \end{align}\]

Where:

  • $N$: Number of risk measures.
  • $i$: Subscript denoting the i-th risk measure.
  • $r_i$: i-th risk measure value.
  • $w_i$: Weight of the i-th risk measure.

Related

source
PortfolioOptimisers.LogSumExpScalariser — Type
struct LogSumExpScalariser{__T_gamma} <: NonHierarchicalScalariser

Smooths the maximum of the scaled risk measures, so every measure keeps a share of the aggregate.

Mathematical definition

\[\begin{align} \phi &= \frac{1}{\gamma} \log \left( \sum_{i=1}^{N} \exp \left[ \gamma \cdot w_i \cdot r_i \right] \right)\,. \end{align}\]

Where:

  • $N$: Number of risk measures.
  • $i$: Subscript denoting the i-th risk measure.
  • $r_i$: i-th risk measure value.
  • $w_i$: Weight of the i-th risk measure.
  • $\gamma$: Positive parameter setting how close the aggregate runs to the maximum.

What gamma does

The aggregate is never below the maximum and never more than $\log N / \gamma$ above it:

\[\begin{align} \underset{i \in (1,\,N)}{\max} \left(w_i \cdot r_i\right) \leq \phi &\leq \underset{i \in (1,\,N)}{\max} \left(w_i \cdot r_i\right) + \frac{\log N}{\gamma}\,. \end{align}\]

Section 3.1.5 of [188] states the bound for $\gamma = 1$. No earlier source of it was found. So a large $\gamma$ gives the maximum. Under a minimum-risk objective the model agrees with expected_risk, which states the smoothed maximum. Under a maximum-return objective it reports an upper bound, as Scalariser states for every strategy.

Warning

A small $\gamma$ does not give the weighted sum. The bound above shows why. The aggregate never falls below the maximum, and $\log N / \gamma$ diverges. When that divergent term is subtracted, what is left tends to the weighted mean. An additive constant does not move a minimiser, so the portfolio that a small $\gamma$ selects tends to the portfolio of the weighted sum, but the number that it reports does not. The model fails first: a $\gamma$ small enough to make the divergent term negligible can already fail to solve.

Warning

The model form is an exponential cone, which cannot hold a quadratic risk expression. Both Variance formulations produce one, so a Variance under this scalariser fails to solve. The optimisation warns and returns an OptimisationFailure with NaN weights, and its res holds MOI.UnsupportedConstraint{MOI.ScalarQuadraticFunction{Float64}, MOI.GreaterThan{Float64}} for each solver. Use StandardDeviation instead, or SumScalariser, which sums a quadratic expression directly. Nothing refuses the combination up front.

A clustering optimisation computes the risk of each cluster separately, and the value level builds no cone. It evaluates the measures first and reduces the numbers. A large $\gamma$ is safe there, because LogExpFunctions.logsumexp subtracts the maximum before it exponentiates.

JuMP formulation

Relaxation

The encoding is not exact: the entries below bound the quantity instead of reproducing it, and the bound is tight only under the condition stated here.

  • The bounded quantity is risk, the free variable scalarise_risk_expression! creates for this strategy. The rows u_risk_lse and risk_lse state the exponential-cone form of the log-sum-exp, which holds model[:risk] at or above the smoothed maximum.
  • The bound is tight while the objective pulls risk down, which a minimum-risk objective does. Under MaximumReturn nothing pulls, and model[:risk] is then an upper bound.
  • A tight bound holds the smoothed maximum, not the maximum. The gap to the maximum is at most $\log N / \gamma$, and it is equal to that value when all $N$ scaled measures are equal. The gap closes as $\gamma$ grows, and as one measure exceeds the others by more than a few multiples of $1 / \gamma$.
  • An ub on the aggregate is unaffected, on the terms MaxScalariser states. Read the exact figure back with expected_risk.

Fields

  • gamma: Log-sum-exp scalariser smoothing parameter.

Constructors

LogSumExpScalariser(;    gamma::Number = 1.0,) -> LogSumExpScalariser

Keywords correspond to the struct's fields.

Validation

  • gamma > 0.

Examples

julia> LogSumExpScalariser()LogSumExpScalariser  gamma ┴ Float64: 1.0

Related

References

  • [188] S. Boyd and L. Vandenberghe. Convex Optimization (Cambridge University Press, Cambridge, UK, 2004). Section 3.1.5, page 72. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
  • [189] S. Diamond and S. Boyd. CVXPY: A Python-embedded modeling language for convex optimization. Journal of Machine Learning Research 17, 1–5 (2016). cvxpy.transforms.scalarize.log_sum_exp. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
source
PortfolioOptimisers.FrontierBoundEstimator — Type
abstract type FrontierBoundEstimator <: AbstractEstimator

Abstract supertype for bound-transformation strategies applied to efficient frontier bounds.

A bound and the risk expression it bounds are not always in the same units. A concrete subtype names the conversion between them, and it is used twice: once on a stated bound value, and once on each end of a Frontier sweep span. Because the span is transformed before it is divided, the sweep points are evenly spaced in the units of the expression, not in the units of the measure.

Interfaces

To implement a new bound transformation, subtype FrontierBoundEstimator and implement:

Required method name

  • variance_risk_bounds_val(bound::MyBound, ub::Num_VecNum): Convert a stated bound into the units of the risk expression.

Arguments

  • bound: The bound-transformation instance.
  • ub: The bound value the caller stated.

Returns

  • The converted bound, in the units of the risk expression.

The Frontier arm of variance_risk_bounds_val is generic and needs no method. The sweep applies the same transformation to both ends of its span in rebuild_risk_frontier, which reads bound off the Frontier and branches on it there.

Related

source
PortfolioOptimisers.LinearBound — Type
struct LinearBound <: FrontierBoundEstimator

Passes bound values through unchanged (identity transformation).

The conversion is ub itself. The caller writes the bound against the measure, and the model enforces it against that same quantity. A formulation uses it when the risk expression and the bound of the caller are in the same units, as the semidefinite form of Variance is, with both in variance units. This is the default of Frontier, so a sweep that names no bound is evenly spaced in the units of the measure.

Related

source
PortfolioOptimisers.SquareRootBound — Type
struct SquareRootBound <: FrontierBoundEstimator

Applies a square-root transformation to bound values before enforcing them.

The conversion is sqrt(ub). The caller writes the bound against the measure, and the model enforces it against the square root of that quantity, so a bound on a variance becomes a bound on a standard deviation. A formulation uses it when the risk expression is in standard-deviation units and the bound of the caller is in variance units, as the second-order cone forms of Kurtosis and NegativeSkewness are. This is also the transformation the default Variance formulation takes, so a Variance frontier is evenly spaced in standard-deviation units, and its variances are not evenly spaced.

Related

source
PortfolioOptimisers.SquaredBound — Type
struct SquaredBound <: FrontierBoundEstimator

Applies a squaring transformation to bound values before enforcing them.

The conversion is ub^2. The caller writes the bound against the measure, and the model enforces it against the square of that quantity, so a bound on a standard deviation becomes a bound on a variance. A formulation uses it when the risk expression is in squared units and the bound of the caller is in linear units, as the kurtosis term of VarianceSkewKurtosis is under a second-moment formulation that is not quadratic.

Related

source
PortfolioOptimisers.risk_input_kind — Function
risk_input_kind(r::AbstractBaseRiskMeasure) -> RiskInputKind

Return the RiskInputKind of risk measure r, declaring what its functor consumes when expected_risk evaluates it.

There is no default. Every concrete AbstractBaseRiskMeasure declares its kind beside its type definition, as one of NetReturnsInput, WeightsReturnsFeesInput or WeightsInput. The composite measures that their own expected_risk methods route are the exception. An undeclared measure throws, so it never reaches the wrong input shape.

Validation

  • Throws an ArgumentError when r declares no method of its own. An undeclared measure would otherwise route to the wrong input shape in silence.

Returns

  • RiskInputKind: the declared input kind.

Related

source
PortfolioOptimisers.coskewness_processor — Function
coskewness_processor(ske::CoskewnessEstimator)
coskewness_processor(ske::Coskewness)
coskewness_processor(ske::WindowedCoskewness)

Return the matrix-processing estimator that a CoskewnessEstimator uses to build V, or nothing when the estimator names none.

V = negative_spectral_coskewness(sk, X, mp), so building V always names a processor. When a coskewness estimator stands in a NegativeSkewness sk slot, that estimator's processor is the one that built the V it hands back, and the measure records it in place of its own mp so that a later rebuild uses the same one. This mirrors HighOrderPrior's skmp.

The CoskewnessEstimator interface does not require an mp field, so the default answers nothing and the measure keeps the processor it already holds. Declare a method for an estimator that names one. A WindowedCoskewness answers the processor of its inner estimator, which builds its V.

Related

source
PortfolioOptimisers.port_opt_view — Method
port_opt_view(rs, i, X)

Get a view or subset of a risk measure for asset cluster index i.

Returns the risk measure sliced for the given cluster or asset index. Used internally in hierarchical optimisation to apply risk measures to each cluster.

A vector of risk measures (VecBaseRM) is handled by the generic vector methods of factory and port_opt_view, which rebuild and view each measure in turn.

Arguments

  • rs: Risk measure.
  • i: Cluster or asset index.
  • X: Data matrix (used for dimension-aware slicing).

Returns

  • Sliced risk measure or the original if no slicing is needed.

Related

source
PortfolioOptimisers.needs_previous_weights — Method
needs_previous_weights(r::AbstractBaseRiskMeasure) -> Bool
needs_previous_weights(r::VecBaseRM) -> Bool

Return whether risk measure r requires previous portfolio weights as input.

The default returns false. Override to true for risk measures such as turnover or tracking constraints that depend on prior weights. The VecBaseRM overload returns true if any element returns true.

Returns

  • Bool: true if prior weights are required; false otherwise.

Related

source
PortfolioOptimisers.bigger_is_better — Function
bigger_is_better(r::AbstractBaseRiskMeasure) -> Bool

Return whether a larger value of risk measure r is preferred over a smaller one.

The default returns false, so a lower value is better, for every AbstractBaseRiskMeasure subtype. A ratio or a return-like measure that a caller maximises declares a method that returns true. An AbstractAssetScorer has no default, and each concrete scorer declares its own method.

Returns

  • Bool: true if a higher value of r is preferred; false otherwise.

Related

source
bigger_is_better(
    rs::AbstractVector{<:AbstractBaseRiskMeasure}
) -> Bool

Return whether every element of rs shares the same polarity, and throw when they do not.

The scalarised value of a mixed vector such as [Variance(), ExpectedReturn()] has no defined orientation, so neither all nor any is correct. Both are wrong in silence, and the consumers are load-bearing: RankRule takes a count or a fraction from each tail, and the flag decides which tail is best.

Validation

  • Throws an ArgumentError when the elements disagree.

Related

source
bigger_is_better(_::Skewness) -> Bool

Return true, because a larger third moment is better.

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

source
bigger_is_better(r::Union{RiskRatio, NonOptimisationRiskRatio}) -> Bool

Return whether a larger value of the ratio r is better, which is the answer of its numerator r1.

The ratio grows with its numerator and falls with its denominator. So a return over a risk is better when it is larger, and a risk over a risk, or a risk over a return, is better when it is smaller. MeanReturnRiskRatio follows the same rule, and returns true. A vector r1 answers through the method for a vector, which throws an ArgumentError when its elements disagree.

Arguments

  • r: The ratio measure.

Validation

  • When r1 is a vector, its elements agree on bigger_is_better.

Returns

  • Bool: bigger_is_better(r.r1).

Examples

julia> PortfolioOptimisers.bigger_is_better(NonOptimisationRiskRatio(; r1 = MeanReturn(),                                                                     r2 = Variance()))truejulia> PortfolioOptimisers.bigger_is_better(NonOptimisationRiskRatio(; r1 = Variance(),                                                                     r2 = MeanReturn()))falsejulia> PortfolioOptimisers.bigger_is_better(RiskRatio())false

Related

source
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

source
bigger_is_better(stat::VectorToScalarMeasure) -> Bool
bigger_is_better(stat::Union{StdValue, VarValue}) -> Bool
bigger_is_better(stat::Function) -> Bool

Return whether a bigger value of the statistic stat is a better score.

A PanelFieldScorer with bib = nothing takes the orientation of its score from its statistic. A statistic of location or of size, such as the minimum, the mean, the median, the maximum, the sum or the product, answers true: a bigger traded amount or a bigger capitalisation is better. A statistic of dispersion, StdValue or VarValue, answers false, because a dispersion is a risk, as a variance is for a risk measure. A plain function has no type that can state a trait, and it answers true.

A subtype of VectorToScalarMeasure whose smaller values are better adds a method that answers false.

Arguments

  • stat: The statistic.

Returns

  • bib::Bool: true when a bigger value of stat is better.

Related

source
PortfolioOptimisers.range_tails — Function
range_tails(r::RangeRiskMeasure) -> RangeTails

Decompose a range risk measure into the two point measures it is the sum of.

A range measure is its base measure applied twice: once to the losses at level alpha, and once to the gains at the second level the range carries (beta, w2, …). The two point measures are the whole content of that statement, so a range declares them here once and both of its consumers read them from this one place:

  • The method of set_risk_constraints! for a RangeRiskMeasure builds loss with loss = true and gain with loss = false, then sums the two expressions.
  • The measure's own r(x::VecNum) functor is the value-level twin of the same sum, loss(x) + gain(-x).

The tails carry RiskMeasureSettings(; rke = false): an upper bound and a risk-expression contribution belong to the range as a whole, which registers them once from the composite expression. A range that fuses its two tails into a shared formulation rather than duplicating one (Range, ValueatRiskRange under DistributionValueatRisk, and OrderedWeightsArrayRange under ExactOrderedWeightsArray or SortingNetworkOrderedWeightsArray) declares no tails, because there are no two sub-models to build.

There is no default. A range that fuses throws rather than returning a decomposition that does not describe it. A measure that is not a range has no method.

Arguments

  • r: Range risk measure.

Validation

  • Throws an ArgumentError when the range r declares no method of its own, which a range that fuses its two tails into a single formulation does.

Returns

  • tails::RangeTails: The loss-tail and gain-tail point measures. A method of a range of your own builds it, and its constructor refuses a tail that adds to the risk expression.

Related

source
PortfolioOptimisers.RangeTails — Type
struct RangeTails{__T_loss, __T_gain} <: AbstractEstimator

Holds the Range Tails of a range risk measure: the two point measures whose sum is the range.

range_tails returns it, and a range of your own builds it in its method of that verb. The loss tail reads the net portfolio returns, and the gain tail reads their negation at the second level of the range. An upper bound and a risk-expression contribution belong to the range as a whole, which registers them once from the composite expression. So each tail carries rke = false, and the constructor refuses a tail that does not.

Fields

  • loss: The point measure of the losses, at the first level of the range.
  • gain: The point measure of the gains, read on the negated returns at the second level of the range.

Constructors

RangeTails(loss::RiskMeasure, gain::RiskMeasure) -> RangeTailsRangeTails(; loss::RiskMeasure, gain::RiskMeasure) -> RangeTails

Validation

  • loss.settings.rke and gain.settings.rke are false. Otherwise an ArgumentError is raised.
  • The keyword constructor refuses a tail that is not a RiskMeasure with a TypeError. The positional constructor checks only a pair of RiskMeasures: the generic positional method that @concrete adds takes any other pair with no check.

Examples

julia> off = RiskMeasureSettings(; rke = false);julia> tails = PortfolioOptimisers.RangeTails(;                                              loss = ConditionalValueatRisk(; settings = off,                                                                            alpha = 0.05),                                              gain = ConditionalValueatRisk(; settings = off,                                                                            alpha = 0.1));julia> (tails.loss.alpha, tails.gain.alpha)(0.05, 0.1)julia> PortfolioOptimisers.RangeTails(; loss = ConditionalValueatRisk(),                                      gain = ConditionalValueatRisk())ERROR: ArgumentError: Each tail of a range carries `rke = false`, because the range registers its risk expression once. Gotloss.settings.rke => truegain.settings.rke => trueStacktrace:[...]

Related

source
PortfolioOptimisers.supports_precomputed_returns — Function
supports_precomputed_returns(r::AbstractBaseRiskMeasure,
                             rk::RiskInputKind = risk_input_kind(r)) -> Bool

Return whether risk measure r has a precomputed-returns form, that is, whether the functor r(x::VecNum) can evaluate its expected risk on a net-return series x alone.

The form exists exactly when the value of the measure is a function of the series alone:

  • A NetReturnsInput measure, of the quantile and the drawdown families, always answers true. Its functor is the net-returns functor.
  • A measure of the moment family, LowOrderMoment, HighOrderMoment, MedianAbsoluteDeviation and ThirdCentralMoment, answers true when its target does not read the weights. That is the case when mu is nothing, a scalar or a centring function. A per-asset mu, a VecNum or a VecScalar, reduces as dot(w, mu) and needs the weights that the series no longer carries, so the answer is false.
  • A WeightsInput measure, such as Variance, Skewness and Kurtosis, a tracking measure and a composite that carries a variance, such as VarianceSkewKurtosis, answer false. The risk of a bare return series has no definition for them.

This predicate keeps the precomputed-returns contract safe. The functor r(w) of a WeightsInput measure has the same r(::VecNum) signature as the contract, so dispatch cannot tell weights from returns. expected_risk_from_returns reads this predicate, and it throws an error that explains the refusal for an ineligible measure. It never reads the series as weights.

The kind of the measure is the second slot, and its default is risk_input_kind of the measure. A measure that declares its own one-argument method answers for itself. Every other call dispatches on the kind: (::Any, ::NetReturnsInput) answers true and (::Any, ::WeightsInput) answers false. This method takes a WeightsReturnsFeesInput measure that declares no method of its own. Every such measure declares it beside its definition. A moment measure declares supports_precomputed_returns(r::T) = weight_independent_target(r.mu), and a measure that reads the weights, such as a tracking measure or a composite that carries a variance, declares supports_precomputed_returns(::T) = false. The completeness test in test_09_risk_measures.jl makes the omission fail in CI.

Validation

  • A WeightsReturnsFeesInput measure that reaches this method declared no method of its own. It throws an ArgumentError that states the declaration to write.

Related

source
PortfolioOptimisers.supports_precomputed_returns — Method
supports_precomputed_returns(
    rs::AbstractVector{<:AbstractBaseRiskMeasure}
) -> Bool

Return whether every element of rs supports evaluation on a precomputed return series.

It answers by all, as the && of the two ratio composites does. needs_previous_weights on the same alias answers by any. Both are correct, because the question "does the vector need it" is not the question "can the vector do it".

Related

source

References

[12]
D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025).
[32]
H. Markowitz. Portfolio Selection. The Journal of Finance 7, 77–91 (1952).
[188]
S. Boyd and L. Vandenberghe. Convex Optimization (Cambridge University Press, Cambridge, UK, 2004).
[189]
S. Diamond and S. Boyd. CVXPY: A Python-embedded modeling language for convex optimization. Journal of Machine Learning Research 17, 1–5 (2016).