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.
| Type | Name (Alias) | Compatibility | Requirements | Rec. Solver |
|---|---|---|---|---|
| Dispersion | Variance | JuMP + Hierarchical | QP, SOC | Clarabel |
| Dispersion | SDP graph / Risk contribution Variance | JuMP + Hierarchical | SDP | Clarabel, SCS |
| Dispersion | StandardDeviation (SD) | JuMP + Hierarchical | SOC | Clarabel |
| Dispersion | Box UncertaintySetVariance (UcVariance) | JuMP + Hierarchical | Sym | Clarabel |
| Dispersion | Ellipse UncertaintySetVariance (UcVariance) | JuMP + Hierarchical | Sym, PSD, SOC | Clarabel, SCS |
| Dispersion | LowOrderMoment (FLM) | JuMP + Hierarchical | - | Clarabel |
| Dispersion | LowOrderMoment (MAD) | JuMP + Hierarchical | - | Clarabel |
| Dispersion | Direct / Squared SOC LowOrderMoment (SCM, SLM) | JuMP + Hierarchical | QP, SOC | Clarabel |
| Dispersion | Sum of Squares LowOrderMoment (SCM, SLM) | JuMP + Hierarchical | SOC, RSOC | Clarabel |
| Dispersion | SOC LowOrderMoment (SCM, SLM) | JuMP + Hierarchical | SOC | Clarabel |
| Dispersion | LowOrderMoment (ECM, ELM) | JuMP + Hierarchical | PC | Clarabel |
| Dispersion | HighOrderMoment (TLM, SSK, FTCM, FTLM, KT, SKT) | Hierarchical | - | - |
| Dispersion | Direct / Squared SOC Exact Kurtosis | JuMP + Hierarchical | QP, SOC, PSD | Clarabel, SCS |
| Dispersion | Sum of Squares Exact Kurtosis | JuMP + Hierarchical | SOC, RSOC, PSD | Clarabel, SCS |
| Dispersion | SOC Exact Kurtosis | JuMP + Hierarchical | SOC, PSD | Clarabel, SCS |
| Dispersion | Direct / Squared SOC Approx Kurtosis | JuMP + Hierarchical | QP, SOC | Clarabel |
| Dispersion | Sum of Squares Approx Kurtosis | JuMP + Hierarchical | SOC, RSOC | Clarabel |
| Dispersion | SOC Approx Kurtosis | JuMP + Hierarchical | SOC | Clarabel |
| Dispersion | NegativeSkewness | JuMP + Hierarchical | QP, SOC | Clarabel |
| Dispersion | Square Root NegativeSkewness | JuMP + Hierarchical | SOC | Clarabel |
| Tail loss | Exact ValueatRisk (VaR) | JuMP + Hierarchical | MIP | Pajarito (Clarabel + HiGHS) |
| Tail loss | Approx ValueatRisk (VaR) | JuMP + Hierarchical | SOC | Clarabel |
| Tail drawdown | DrawdownatRisk (DaR) | JuMP + Hierarchical | MIP | Pajarito (Clarabel + HiGHS) |
| Tail drawdown | RelativeDrawdownatRisk (R_DaR) | Hierarchical | - | Clarabel |
| Dispersion | Exact ValueatRiskRange (VaR_RG) | JuMP + Hierarchical | MIP | Pajarito (Clarabel + HiGHS) |
| Dispersion | Approx ValueatRiskRange (VaR_RG) | JuMP + Hierarchical | SOC | Clarabel |
| Tail loss | ConditionalValueatRisk (CVaR) | JuMP + Hierarchical | - | Clarabel |
| Tail loss | DistributionallyRobustConditionalValueatRisk (DRCVaR) | JuMP + Hierarchical | NIC | Clarabel |
| Tail drawdown | ConditionalDrawdownatRisk (CDaR) | JuMP + Hierarchical | - | Clarabel |
| Tail drawdown | DistributionallyRobustConditionalDrawdownatRisk (DRCDaR) | JuMP + Hierarchical | NIC | Clarabel |
| Tail drawdown | RelativeConditionalDrawdownatRisk (R_CDaR) | Hierarchical | - | Clarabel |
| Dispersion | ConditionalValueatRiskRange (CVaR_RG) | JuMP + Hierarchical | - | Clarabel |
| Dispersion | DistributionallyRobustConditionalValueatRiskRange (DRCVaR_RG) | JuMP + Hierarchical | NIC | Clarabel |
| Tail loss | EntropicValueatRisk (EVaR) | JuMP + Hierarchical | EC | Clarabel |
| Tail drawdown | EntropicDrawdownatRisk (EDaR) | JuMP + Hierarchical | EC | Clarabel |
| Tail drawdown | RelativeEntropicDrawdownatRisk (R_EDaR) | Hierarchical | EC | Clarabel |
| Dispersion | EntropicValueatRiskRange (EVaR_RG) | JuMP + Hierarchical | EC | Clarabel |
| Tail loss | RelativisticValueatRisk (RLVaR) | JuMP + Hierarchical | PC | Clarabel |
| Tail drawdown | RelativisticDrawdownatRisk (RLDaR) | JuMP + Hierarchical | PC | Clarabel |
| Tail drawdown | RelativeRelativisticDrawdownatRisk (R_RLDaR) | Hierarchical | PC | Clarabel |
| Dispersion | RelativisticValueatRiskRange (RLVaR_RG) | JuMP + Hierarchical | PC | Clarabel |
| Tail loss | PowerNormValueatRisk (PNVaR) | JuMP + Hierarchical | PC | Clarabel |
| Tail drawdown | PowerNormDrawdownatRisk (PNDaR) | JuMP + Hierarchical | PC | Clarabel |
| Tail drawdown | RelativePowerNormDrawdownatRisk (R_PNDaR) | Hierarchical | PC | Clarabel |
| Dispersion | PowerNormValueatRiskRange (PNVaR_RG) | JuMP + Hierarchical | PC | Clarabel |
| Dispersion | Exact OrderedWeightsArray (OWA_GMD, OWA_LMoment) | JuMP + Hierarchical | - | Clarabel |
| Dispersion | Approx OrderedWeightsArray (OWA_GMD, OWA_LMoment) | JuMP + Hierarchical | PC | Clarabel |
| Tail loss | Exact OrderedWeightsArray (OWA_CVaR, OWA_TG, OWA_WR) | JuMP + Hierarchical | - | Clarabel |
| Tail loss | Approx OrderedWeightsArray (OWA_CVaR, OWA_TG, OWA_WR) | JuMP + Hierarchical | PC | Clarabel |
| Dispersion | Exact OrderedWeightsArrayRange (OWA_RG, OWA_CVaR_RG, OWA_TG_RG) | JuMP + Hierarchical | - | Clarabel |
| Dispersion | Approx OrderedWeightsArrayRange (OWA_RG, OWA_CVaR_RG, OWA_TG_RG) | JuMP + Hierarchical | PC | Clarabel |
| Drawdown | AverageDrawdown (ADD) | JuMP + Hierarchical | - | Clarabel |
| Drawdown | RelativeAverageDrawdown (R_ADD) | Hierarchical | - | - |
| Drawdown | UlcerIndex (UCI) | JuMP + Hierarchical | SOC | Clarabel |
| Drawdown | RelativeUlcerIndex (R_UCI) | Hierarchical | - | - |
| Tail drawdown | MaximumDrawdown (MDD) | JuMP + Hierarchical | - | Clarabel |
| Tail drawdown | RelativeMaximumDrawdown (R_MDD) | Hierarchical | - | - |
| Dispersion | Direct BrownianDistanceVariance (BDVariance) | JuMP + Hierarchical | QP | Clarabel |
| Dispersion | Sum of Squares BrownianDistanceVariance (BDVariance) | JuMP + Hierarchical | QP, RSOC | Clarabel |
| Tail loss | WorstRealisation (WR) | JuMP + Hierarchical | - | Clarabel |
| Dispersion | Range (RG) | JuMP + Hierarchical | - | Clarabel |
| Turnover | TurnoverRiskMeasure (TnRM) | JuMP + Hierarchical | NOC | Clarabel |
| Tracking | L1 Norm TrackingRiskMeasure (TrRM) | JuMP + Hierarchical | NOC | Clarabel |
| Tracking | L2 Norm TrackingRiskMeasure (TrRM) | JuMP + Hierarchical | SOC | Clarabel |
| Tracking | Squared L2 Norm TrackingRiskMeasure (TrRM) | JuMP + Hierarchical | QP, SOC | Clarabel |
| Tracking | Lp Norm TrackingRiskMeasure (TrRM) | JuMP + Hierarchical | PC | Clarabel |
| Tracking | Infinity Norm TrackingRiskMeasure (TrRM) | JuMP + Hierarchical | NIC | Clarabel |
| Risk tracking | Independent variable RiskTrackingRiskMeasure (RkTrRM) | JuMP + Hierarchical | * | Clarabel |
| Risk tracking | Dependent variable RiskTrackingRiskMeasure (RkTrRM) | JuMP + Hierarchical | NOC, * | Clarabel |
| Dispersion | VarianceSkewKurtosis (VSK) | JuMP + Hierarchical | Sym, PSD | SCS |
| Dispersion | GenericValueatRiskRange (GVaR_RG) | JuMP + Hierarchical | * | Clarabel |
| Ratio | RiskRatio | Hierarchical | * | * |
| Ratio | NonOptimisationRiskRatio (NonOptRkRatio) | - | * | * |
| Flat | EqualRisk | - | - | - |
| Dispersion | MedianAbsoluteDeviation | Hierarchical | - | - |
| Performance | MeanReturn | - | - | - |
| Performance | MeanReturnRiskRatio | - | - | - |
| Performance | ExpectedReturn | - | - | - |
| Performance | ExpectedReturnRiskRatio | - | - | - |
| Dispersion | ThirdCentralMoment | - | - | - |
| Dispersion | Skewness | - | - | - |
PortfolioOptimisers.RiskMeasure — Type
abstract type RiskMeasure <: OptimisationRiskMeasureAbstract 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 ofNetReturnsInput(),WeightsReturnsFeesInput()orWeightsInput().
The functor
expected_risk evaluates the measure as a functor, in the shape its kind declares:
(r::MyRiskMeasure)(x::VecNum) -> NumberunderNetReturnsInput, wherexis the net portfolio return seriescalc_net_returnsbuilds.(r::MyRiskMeasure)(w::VecNum, X::MatNum, fees::Option{<:Fees}) -> NumberunderWeightsReturnsFeesInput.(r::MyRiskMeasure)(w::VecNum) -> NumberunderWeightsInput.
supports_precomputed_returns
supports_precomputed_returns(r::MyRiskMeasure) -> Bool: Whether the risk of the measure is a function of the net return series alone. AWeightsReturnsFeesInputmeasure 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 aJuMPoptimiser, 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:truefor a measure that reads the previous weights; the fallback answersfalse.bigger_is_better(r::MyRiskMeasure) -> Bool:truefor a measure a caller maximises; the fallback answersfalse.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
PortfolioOptimisers.RangeRiskMeasure — Type
abstract type RangeRiskMeasure <: RiskMeasureAbstract 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 carriesrke = 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
PortfolioOptimisers.HierarchicalRiskMeasure — Type
abstract type HierarchicalRiskMeasure <: OptimisationRiskMeasureAbstract 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 ofNetReturnsInput(),WeightsReturnsFeesInput()orWeightsInput().
The functor
expected_risk evaluates the measure as a functor, in the shape its kind declares:
(r::MyRiskMeasure)(x::VecNum) -> NumberunderNetReturnsInput, wherexis the net portfolio return seriescalc_net_returnsbuilds.(r::MyRiskMeasure)(w::VecNum, X::MatNum, fees::Option{<:Fees}) -> NumberunderWeightsReturnsFeesInput.(r::MyRiskMeasure)(w::VecNum) -> NumberunderWeightsInput.
supports_precomputed_returns
supports_precomputed_returns(r::MyRiskMeasure) -> Bool: Whether the risk of the measure is a function of the net return series alone. AWeightsReturnsFeesInputmeasure 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:truefor a measure that reads the previous weights; the fallback answersfalse.bigger_is_better(r::MyRiskMeasure) -> Bool:truefor a measure a caller maximises; the fallback answersfalse.factory: rebuild the measure against a prior result before it is evaluated, for a measure whose slots are filled from the prior.
Related
PortfolioOptimisers.Frontier — Type
struct Frontier{__T_N, __T_factor, __T_bound} <: AbstractAlgorithmSweeps 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.
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 modelNtimes, atNevenly spaced bound values.
factor: Multiplier applied to both ends of the sweep span afterboundhas transformed them. It carries a formulation's own correction factor, such as theinv(1 / (T - ddof))of a second-moment bound.
bound:FrontierBoundEstimatorthat 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()) -> FrontierCreates 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()) -> FrontierCreates 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 > 1andN <= 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, seeRESOURCE_LIMITS. This is the cheap early check on one bound. The sweep across several swept bounds is their product, capped separately at Model Assembly byassert_frontier_sweep_cap.isfinite(factor)andfactor > 0.
Examples
julia> Frontier(; N = 15)Frontier N ┼ Int64: 15 factor ┼ Int64: 1 bound ┴ LinearBound()Related
FrontierBoundEstimatorLinearBoundSquareRootBoundSquaredBoundRiskMeasureSettingsrebuild_risk_frontier
References
PortfolioOptimisers.AbstractRiskMeasureSettings — Type
abstract type AbstractRiskMeasureSettings <: AbstractEstimatorAbstract 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 byset_risk_expression!and by the value-level readers.rke::Bool: Whether the measure contributes to the model's aggregate risk expression.
Optional field
- A bound field.
RiskMeasureSettingsnames ituband bounds the expression from above;MaxRiskMeasureSettingsnames itlband bounds it from below.HierarchicalRiskMeasureSettingshas none, because a clustering optimiser builds no model to bound.
Related
PortfolioOptimisers.RiskMeasureSettings — Type
struct RiskMeasureSettings{__T_scale, __T_ub, __T_rke} <: JuMPRiskMeasureSettingsWeights 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 inubbinds on the measure's own expression, beforescaleis applied.
ub: Upper bound(s) on the measure's own risk expression. A scalar bounds one model. A vector and aFrontierare sweep axes, one solve per entry, so the optimisation returns one portfolio per bound value.
rke: Whether to include the risk measure value in theJuMPrisk expression.
Constructors
RiskMeasureSettings(; scale::Number = 1.0, ub::Option{<:RkRtBounds} = nothing, rke::Bool = true,) -> RiskMeasureSettingsCreates a RiskMeasureSettings instance with the specified scale, upper bound, and risk evaluation flag.
Validation
isfinite(scale).ubis validated withassert_nonempty_nonneg_finite_val.
Examples
julia> RiskMeasureSettings()RiskMeasureSettings scale ┼ Float64: 1.0 ub ┼ nothing rke ┴ Bool: trueRelated
JuMPRiskMeasureSettingsRiskMeasureFrontierHierarchicalRiskMeasureSettingsMaxRiskMeasureSettingsset_risk_bounds_and_expression!
References
PortfolioOptimisers.HierarchicalRiskMeasureSettings — Type
struct HierarchicalRiskMeasureSettings{__T_scale} <: AbstractRiskMeasureSettingsWeights 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 inubbinds on the measure's own expression, beforescaleis applied.
Constructors
HierarchicalRiskMeasureSettings(; scale::Number = 1.0) -> HierarchicalRiskMeasureSettingsCreates a HierarchicalRiskMeasureSettings instance with the specified scaling factor.
Validation
scalemust be finite.
Examples
julia> HierarchicalRiskMeasureSettings()HierarchicalRiskMeasureSettings scale ┴ Float64: 1.0Related
PortfolioOptimisers.Scalariser — Type
abstract type Scalariser <: AbstractEstimatorAbstract 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
JuMPoptimiser builds the aggregation into the model as an expression, so the strategy must have a convex form.NonHierarchicalScalariserandHierarchicalScalariserseparate 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.scais bounded toNonHierarchicalScalariser, so it refuses the hierarchical half. The clustering optimisers compute the risk of each cluster separately and accept either half. - The value level.
expected_riskand 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. Everyscakeyword and everyscaresult field at this level is bounded toScalariser, and all four scalarisers are admitted,MinScalariserincluded.
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 valuesfreturns 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
freturns.
Required for a NonHierarchicalScalariser
scalarise_risk_expression!(model::JuMP.Model, sca::MyScalariser): Collapse the model'srisk_vecarray into the singleriskexpression. AHierarchicalScalariserdeclares 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.
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:
SumScalariserandnothing: slot-wise sum of all values.fis expected to include the measure'ssettings.scaleweight in its result.nothingis the default of everyscafield and keyword, and it gives the sum.by === nothing: slot-wise (elementwise) maximum/minimum across values.bygiven: returns the onefresult whoseby(result)is the largest or the smallest. A tie keeps the earliest result.
LogSumExpScalariser: slot-wiselogsumexpofgamma-scaled values, divided bygamma.
Algorithm
- Start the accumulator
accatnothing, and the winning keykatnothingbeside it.LogSumExpScalariserstarts neither, and takes steps 5 and 6 instead. - Apply
fto each element ofitrin turn, givingv. - Fold
vintoaccthrough the branch thatscaselects.SumScalarisertakesscalarise_combine(+, acc, v).MaxScalariserandMinScalarisertakescalarise_combine(max, acc, v)andscalarise_combine(min, acc, v)whilebyisnothing. - Given a
by, read the keyki = by(v)in place of step 3, and takevandkias the newaccandkwhenkibeats thekalready held. A tie keeps the earlier element. - Under
LogSumExpScalariser, applyfto every element ofitr, scale each result bysca.gammawithscalarise_map, and collect them intovs. - Reduce
vsslot-wise withscalarise_logsumexp, and divide the reduction bysca.gammawithscalarise_map. - Return
acc, or the value step 6 built.
Arguments
f: Per-element evaluation closure, applied to each element ofitr.sca: Scalarisation strategy.nothinggives the rule ofSumScalariser.itr: Iterable of risk measures (orpairsof them, whenfneeds the index).by: Optional selection key forMaxScalariser/MinScalariser; ignored by the other scalarisers.
Returns
- The scalarised value, with the same shape as the values returned by
f.
Related
PortfolioOptimisers.SumScalariser — Type
struct SumScalariser <: NonHierarchicalScalariserAdds 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
ScalariserMaxScalariserMinScalariserLogSumExpScalariserRiskMeasureSettingsHierarchicalRiskMeasureSettingsscalarise_risk_expression!
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.
PortfolioOptimisers.MaxScalariser — Type
struct MaxScalariser <: NonHierarchicalScalariserReports 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 variablescalarise_risk_expression!creates for this strategy. The rowrisk_msholds it at or above every entry ofrisk_vec, somodel[:risk]stands above the maximum rather than on it. - The bound is tight while the objective pulls
riskdown, which a minimum-risk objective does. UnderMaximumReturnnothing pulls, andmodel[:risk]is then an upper bound. - An
ubon the aggregate is unaffected. It constrainsrisk, and the aggregation stands belowrisk, so the aggregation meets the bound too. Read the exact figure back withexpected_risk.
Related
ScalariserSumScalariserMinScalariserLogSumExpScalariserRiskMeasureSettingsHierarchicalRiskMeasureSettingsscalarise_risk_expression!
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.
PortfolioOptimisers.MinScalariser — Type
struct MinScalariser <: HierarchicalScalariserReports 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
PortfolioOptimisers.LogSumExpScalariser — Type
struct LogSumExpScalariser{__T_gamma} <: NonHierarchicalScalariserSmooths 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.
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.
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 variablescalarise_risk_expression!creates for this strategy. The rowsu_risk_lseandrisk_lsestate the exponential-cone form of the log-sum-exp, which holdsmodel[:risk]at or above the smoothed maximum. - The bound is tight while the objective pulls
riskdown, which a minimum-risk objective does. UnderMaximumReturnnothing pulls, andmodel[: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
ubon the aggregate is unaffected, on the termsMaxScalariserstates. Read the exact figure back withexpected_risk.
Fields
gamma: Log-sum-exp scalariser smoothing parameter.
Constructors
LogSumExpScalariser(; gamma::Number = 1.0,) -> LogSumExpScalariserKeywords correspond to the struct's fields.
Validation
gamma > 0.
Examples
julia> LogSumExpScalariser()LogSumExpScalariser gamma ┴ Float64: 1.0Related
ScalariserSumScalariserMaxScalariserMinScalariserRiskMeasureSettingsHierarchicalRiskMeasureSettingsscalarise_risk_expression!
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.
PortfolioOptimisers.FrontierBoundEstimator — Type
abstract type FrontierBoundEstimator <: AbstractEstimatorAbstract 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
PortfolioOptimisers.LinearBound — Type
struct LinearBound <: FrontierBoundEstimatorPasses 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
PortfolioOptimisers.SquareRootBound — Type
struct SquareRootBound <: FrontierBoundEstimatorApplies 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
PortfolioOptimisers.SquaredBound — Type
struct SquaredBound <: FrontierBoundEstimatorApplies 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
PortfolioOptimisers.risk_input_kind — Function
risk_input_kind(r::AbstractBaseRiskMeasure) -> RiskInputKindReturn 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
ArgumentErrorwhenrdeclares 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
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
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
PortfolioOptimisers.needs_previous_weights — Method
needs_previous_weights(r::AbstractBaseRiskMeasure) -> Bool
needs_previous_weights(r::VecBaseRM) -> BoolReturn 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:trueif prior weights are required;falseotherwise.
Related
PortfolioOptimisers.bigger_is_better — Function
bigger_is_better(r::AbstractBaseRiskMeasure) -> BoolReturn 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:trueif a higher value ofris preferred;falseotherwise.
Related
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
ArgumentErrorwhen the elements disagree.
Related
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
bigger_is_better(r::Union{RiskRatio, NonOptimisationRiskRatio}) -> BoolReturn 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
r1is a vector, its elements agree onbigger_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())falseRelated
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
bigger_is_better(stat::VectorToScalarMeasure) -> Bool
bigger_is_better(stat::Union{StdValue, VarValue}) -> Bool
bigger_is_better(stat::Function) -> BoolReturn 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:truewhen a bigger value ofstatis better.
Related
PortfolioOptimisers.range_tails — Function
range_tails(r::RangeRiskMeasure) -> RangeTailsDecompose 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 aRangeRiskMeasurebuildslosswithloss = trueandgainwithloss = 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
ArgumentErrorwhen the rangerdeclares 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
PortfolioOptimisers.RangeTails — Type
struct RangeTails{__T_loss, __T_gain} <: AbstractEstimatorHolds 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) -> RangeTailsValidation
loss.settings.rkeandgain.settings.rkearefalse. Otherwise anArgumentErroris raised.- The keyword constructor refuses a tail that is not a
RiskMeasurewith aTypeError. The positional constructor checks only a pair ofRiskMeasures: the generic positional method that@concreteadds 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
PortfolioOptimisers.supports_precomputed_returns — Function
supports_precomputed_returns(r::AbstractBaseRiskMeasure,
rk::RiskInputKind = risk_input_kind(r)) -> BoolReturn 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
NetReturnsInputmeasure, of the quantile and the drawdown families, always answerstrue. Its functor is the net-returns functor. - A measure of the moment family,
LowOrderMoment,HighOrderMoment,MedianAbsoluteDeviationandThirdCentralMoment, answerstruewhen its target does not read the weights. That is the case whenmuisnothing, a scalar or a centring function. A per-assetmu, aVecNumor aVecScalar, reduces asdot(w, mu)and needs the weights that the series no longer carries, so the answer isfalse. - A
WeightsInputmeasure, such asVariance,SkewnessandKurtosis, a tracking measure and a composite that carries a variance, such asVarianceSkewKurtosis, answerfalse. 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
WeightsReturnsFeesInputmeasure that reaches this method declared no method of its own. It throws anArgumentErrorthat states the declaration to write.
Related
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
PortfolioOptimisers.supports_precomputed_returns — Method
supports_precomputed_returns(_, _::NetReturnsInput) -> Bool
Return true. A NetReturnsInput measure always supports precomputed returns, because its functor is the net-returns functor.
Related
PortfolioOptimisers.supports_precomputed_returns — Method
supports_precomputed_returns(_, _::WeightsInput) -> Bool
Return false. A WeightsInput measure never supports precomputed returns, because its functor reads portfolio weights, not a return series.
Related
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).