Base Risk Measures: private API

PortfolioOptimisers.AbstractBaseRiskMeasure — Type
abstract type AbstractBaseRiskMeasure <: AbstractEstimator

Abstract supertype for all risk measure estimators.

A risk measure gives one number for the risk of a portfolio. Every concrete risk measure subtypes AbstractBaseRiskMeasure, and the four traits of this file, risk_input_kind, supports_precomputed_returns, bigger_is_better and needs_previous_weights, dispatch on it.

Every concrete risk measure is a functor, a callable struct that computes its risk.

Related

source
PortfolioOptimisers.NonOptimisationRiskMeasure — Type
abstract type NonOptimisationRiskMeasure <: AbstractBaseRiskMeasure

Abstract supertype for risk measures that are not intended for use in portfolio optimisation routines.

These risk measures serve analysis, reports and diagnostics. No optimiser takes one as an objective or as a constraint. Subtype this for a risk measure that an optimiser must not accept.

Related

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

Abstract supertype for scalarisation strategies that combine multiple risk measures into a single scalar value, and that every optimisation estimator can build.

Subtype NonHierarchicalScalariser when the aggregation has a convex JuMP form, so a JuMP optimiser can build it into the model as well as a clustering optimiser can compute it per cluster. JuMPOptimiser.sca is bounded here.

The split names a consumer, not a property of the number. It does not restrict the value-level readers, which admit all four scalarisers, as Scalariser states.

Related

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

Abstract supertype for scalarisation strategies that combine multiple risk measures into a single scalar value, and that only the clustering optimisation estimators can build.

Subtype HierarchicalScalariser when the aggregation has no convex JuMP form. JuMPOptimiser.sca is bounded NonHierarchicalScalariser and refuses this half; the clustering optimisers compute each cluster's risk separately and accept it.

The split names a consumer, not a property of the number. The value level evaluates the measures first and the strategy combines plain numbers, so nothing is built and all four scalarisers are admitted, as Scalariser states.

Related

source
PortfolioOptimisers.DeferredQuantity — Type
const DeferredQuantity = Union{...}

The dynamic half of a Deferred Quantity: an Estimator standing in a risk-measure slot where a prior-derived value goes. isa(x, DeferredQuantity) answers the question "is this slot deferred?". The union holds the four moment-estimator families, each of which computes one of the four deferrable quantities, and AbstractPriorEstimator, which computes all four at once.

The union exists because no supertype already answers the question: AbstractCovarianceEstimator is a StatsBase.CovarianceEstimator and not an AbstractEstimator.

Related

source
PortfolioOptimisers.BaseRM_VecBaseRM — Type
const BaseRM_VecBaseRM = Union{AbstractBaseRiskMeasure, VecBaseRM}

Argument bound for every value-level reader of a risk measure: one measure or several.

Mirrors JRE_VecJRE on the return side. A method bounded here serves a measure and a vector of them with one body, so the value-level surface needs one method per arity rather than two.

A vector is scalarised into one number by the sca keyword, which defaults to nothing, gives the sum of SumScalariser, and is silently inert on a single measure.

Related

source
PortfolioOptimisers.scalarise_logsumexp — Function
scalarise_logsumexp(vs)

Slot-wise log-sum-exp across a vector of scalarised risk values.

For a vector of numbers this is LogExpFunctions.logsumexp; for a vector of same-shaped arrays it is applied elementwise across the vector; for a vector of same-shaped tuples it recurses per slot.

Related

source
PortfolioOptimisers.Sca_VecToScaM — Type
const Sca_VecToScaM = Union{Scalariser, VectorToScalarMeasure, Function}

Union of the reductions that a score of a vector of risk measures accepts: a Scalariser, a VectorToScalarMeasure or a plain function from a vector to a number.

A score reduces numbers that are already computed, so it needs no convex form and no derivative. So it admits the two families and a function, as Num_VecToScaM admits a reduction or a function. The readers of a risk, such as expected_risk, keep the bound Scalariser. Each slot takes Option of its bound, and nothing gives the rule of SumScalariser.

Related

source
PortfolioOptimisers.nothing_scalar_array_selector — Function
nothing_scalar_array_selector(risk_variable::Nothing, prior_variable::Nothing)
nothing_scalar_array_selector(risk_variable::Num_ArrNum_VecScalar_DynWeights, ::Any)
nothing_scalar_array_selector(risk_variable::Nothing, prior_variable::Num_ArrNum_VecScalar_DynWeights)

Select the value that a risk measure states, or fall back to the value of a prior result when the measure states none.

Arguments

  • risk_variable: The risk-side input.
  • prior_variable: The prior-side input.

Returns

  • If both inputs are nothing returns nothing.
  • If risk_variable is not nothing, returns risk_variable.
  • If risk_variable is nothing and prior_variable is not nothing, returns prior_variable.

Related

source
PortfolioOptimisers.CoskewnessFit — Type
struct CoskewnessFit{__T_sk, __T_V, __T_skmp} <: AbstractResult

Holds the fit of a CoskewnessEstimator in a Deferred Quantity: the coskewness matrix, its negative spectral part and the processor that built that part.

sk and V come out of one call of coskewness, and V never travels without sk. fit_deferred_quantity returns it, and deferred_quantity and deferred_derived_quantity read its fields by the name of the slot.

Fields

  • sk: The coskewness matrix of the fit.
  • V: The negative spectral coskewness that the same call gave.

Related

source
PortfolioOptimisers.fit_deferred_quantity — Function
fit_deferred_quantity(dq::DeferredQuantity, pr::AbstractPriorResult)

Run a Deferred Quantity against the optimisation's own prior result and return what it produces: a moment estimator gives its quantity, an AbstractPriorEstimator gives a whole AbstractPriorResult.

The estimator sees pr.original_X, the returns that the caller supplied, sliced by any port_opt_view that the measure crossed. pr.w is threaded through factory, so a weighted prior replaces the estimator's own observation weights and an unweighted prior leaves them alone.

pr.original_X rather than pr.X, because the two differ on a factor route. FactorPrior, FactorBlackLittermanPrior and AugmentedBlackLittermanPrior all overwrite X with the reconstruction F * transpose(M) .+ transpose(b), which spans only the factors: it has rank size(F, 2), and it carries no residual. Fitting a covariance estimator on it returns a singular matrix whenever there are more assets than factors, and a prior estimator in a slot could not regress it against those same factors. Off a factor route original_X === X, so nothing moves.

A CokurtosisEstimator gives its tensor. A CoskewnessEstimator gives the pair (sk, V) and the matrix-processing estimator that built V, as a CoskewnessFit. V is derived from sk and never travels on its own. See coskewness_processor. A co-moment estimator takes its tensor about the centre of its own me.

Algorithm

  1. Rebuild dq against the prior's observation weights with factory(dq, pr.w). The two co-moment arms bind the rebuilt estimator as kte and ske.
  2. Run the rebuilt estimator on pr.original_X, through the verb of its own family: Statistics.mean for an expected-returns estimator, Statistics.cov for a covariance estimator, cokurtosis for a cokurtosis estimator, coskewness for a coskewness estimator, and prior for a prior estimator, which also takes deferred_factors(pr).
  3. Return the quantity the verb gave. The coskewness arm returns a CoskewnessFit instead, because V comes out of the same call and coskewness_processor names the estimator that built it.

Returns

  • The deferred quantity: a vector for an expected-returns estimator, a matrix for a covariance or a cokurtosis estimator, an AbstractPriorResult for a prior estimator, and a CoskewnessFit for a coskewness estimator.

Related

source
PortfolioOptimisers.deferred_quantity — Function
deferred_quantity(fitted, key::Symbol)

Read the quantity named by key off what fit_deferred_quantity produced.

A moment estimator produced the quantity itself, so it is returned and key is inert. A CoskewnessEstimator produced a CoskewnessFit, because sk and V come out of one call. An AbstractPriorEstimator produced a prior result, so key picks the one wanted from the several it computed.

Validation

  • Throws an ArgumentError when fitted is a CoskewnessFit carrying no field key, and when fitted is an AbstractPriorResult carrying no property key. The slot named an estimator that computes something else, and a silent nothing would reach the model builders as though the caller had stated none. This is the difference from deferred_derived_quantity, which answers nothing for a key its fit does not carry.

Returns

  • The quantity named by key, or the whole fit when a moment estimator produced it.

Related

source
PortfolioOptimisers.fan_out_slot — Function
fan_out_slot(fitted, slot, key::Symbol)

Fill one slot from a fan-out fit, unless the caller stated it.

A measure that carries two or more independently deferrable slots takes a pe instead of widening each slot. fit_deferred_quantity runs that estimator once, and this reads one quantity per slot off the single result it produced.

The precedence is the map's: a stated slot wins, pe fills the rest, and a slot that neither names is left nothing so the consumer's own prior fallback still applies.

A measure with exactly one deferrable slot takes no pe. It widens that slot instead. A derived companion, such as chol with sigma or V with sk, comes out of the same fit with it, and is not fanned out separately.

Algorithm

  1. Return slot unchanged when it is not nothing. A slot the caller stated wins over the fan-out.
  2. Read the quantity named by key off fitted with deferred_quantity, and return it.

Returns

  • The stated slot, or the quantity named by key.

Related

source
PortfolioOptimisers.fan_out_pe — Function
fan_out_pe(x, pe::Nothing, pr::AbstractPriorResult, slots::NamedTuple)
fan_out_pe(x, pe::AbstractPriorEstimator, pr::AbstractPriorResult, slots::NamedTuple)

Rebuild a measure with its resolved slots, and fill the slots that are still nothing from its fan-out estimator pe.

A measure with two or more deferrable slots resolves each deferred slot first, and then gives the resolved slots to this function. The type of pe selects the method. Without a pe the measure takes the resolved slots as they are. With a pe the function runs fit_deferred_quantity one time and fills each slot with fan_out_slot, so a resolved slot wins over the fan-out. The rebuilt measure holds pe = nothing, because the fit is done.

A measure whose slots carry a derived quantity, such as chol beside sigma, declares its own method for a pe, because the derived quantity comes from the fan-out only when the fan-out also gives its source.

Algorithm

  1. pe is nothing: rebuild x with slots.
  2. Otherwise fit pe against pr one time. Fill each slot of slots with fan_out_slot under its own name, and rebuild x with the filled slots and pe = nothing.

Arguments

  • x: The measure, or the algorithm of a measure, that holds the slots.
  • pe: The fan-out estimator of x, or nothing.
  • pr: The prior result that pe is fitted against.
  • slots: The resolved slots, keyed by field name.

Returns

  • The rebuilt x.

Related

source
PortfolioOptimisers.deferred_derived_quantity — Function
deferred_derived_quantity(fitted, key::Symbol)

Read a derived quantity named by key off what fit_deferred_quantity produced. The three derived quantities are chol, the factorisation that comes with sigma, V, the negative spectral part that comes with sk, and skmp, the processor that built V.

A prior result carries all three. A coskewness estimator produced a CoskewnessFit carrying V and skmp. Anything else produced only its own quantity, so the answer is nothing and the consumer keeps whatever fallback it already had. This is the difference from deferred_quantity, which refuses a key the fit does not carry.

Related

source
PortfolioOptimisers.resolve_slot — Function
resolve_slot(slot, key::Symbol, pr::AbstractPriorResult)

Resolve one risk-measure slot against prior result pr and return a plain value.

A slot that holds a Deferred Quantity is run against pr, and the quantity named by key is read back. Any other occupant, such as a stated value, nothing or a centring strategy, comes back unchanged, so the caller can apply the ordinary prior fallback of sel after it.

This is the whole of the third state. The other two are unchanged: nothing still falls back to the prior's own field, and a stated value still wins.

Algorithm

  1. Return slot unchanged when it is not a DeferredQuantity. A stated value, nothing and a centring strategy all take that arm.
  2. Run the Deferred Quantity against pr with fit_deferred_quantity, giving fitted.
  3. Read the quantity named by key off fitted with deferred_quantity, and return it.

Returns

  • A plain value: the slot's own occupant, or the quantity the fit produced.

Related

source
PortfolioOptimisers.resolve_sigma_chol — Function
resolve_sigma_chol(sigma, chol, pr::AbstractPriorResult)

Resolve the sigma slot of a measure against prior result pr, and return it with the chol slot as one pair.

chol is a factorisation of sigma, so both come from the same fit. A covariance estimator gives no factorisation, so chol becomes nothing and the model derives it from the resolved sigma. A prior estimator gives both. The type of sigma selects the method, so an analysis of a measure whose sigma is a matrix never reaches the fit.

Algorithm

  1. Return sigma and chol unchanged when sigma is not a DeferredQuantity.
  2. Run the Deferred Quantity against pr with fit_deferred_quantity, giving fitted.
  3. Read sigma off fitted with deferred_quantity, and chol with deferred_derived_quantity.

Returns

Related

source
PortfolioOptimisers.deferred_slots — Function
deferred_slots(x)

Declare the slots of x that may hold a Deferred Quantity, as a NamedTuple mapping each slot's name to its current value. The default is empty: a type with no deferrable slot needs no method.

This is the declaration both consumers read. assert_resolved_slots refuses a slot that a value-level entry point cannot resolve, and resolve_deferred_quantities derives its container recursion from it. A type that names its slots here needs no forwarding method of its own.

A slot that holds a child measure is declared here too. Both consumers recurse into whatever a slot holds, so a container names its children and each child names its own slots; nothing walks fields blindly. This matters because a risk measure holds Estimators that are not deferred slots, such as a variance estimator in ve or an uncertainty-set estimator in ucs, and a walk over every field would refuse them.

A type that resolves a quantity of its own declares a resolve_deferred_quantities method beside this one. A matrix out of a covariance estimator is such a quantity, and so are a tensor and its centre out of a co-moment estimator. The method is per type, because slots that come out of one fit must be resolved together, and no derivation can know which slots those are. A type that declares the slots and no method is refused at the first call.

Related

source
PortfolioOptimisers.functor_slots — Function
functor_slots(x)

Declare the slots of x that its functor reads as they stand, as a NamedTuple mapping each slot's name to its current value. The default is empty: a type whose functor computes every moment from the returns it is handed needs no method.

assert_resolved_slots reads this beside deferred_slots. A slot named here that holds nothing is refused at a value-level entry point with an error that names it, because nothing on that route fills it and the functor would otherwise meet the nothing several frames down, as dot(w, nothing, w) inside LinearAlgebra.

A slot is named here only when nothing there has no value-level reading. The covariance a Variance contracts the weights with is one: the functor is dot(w, r.sigma, w), and a bare matrix cannot stand in. The solver slv of a measure whose functor solves a programme, such as EntropicValueatRisk, is one too: an optimiser fills it through factory, and no data can. assert_scoreable reads the declaration through assert_resolved_slots too, so a selector refuses such a measure, or a container that holds one, in its constructor. A moment measure's mu is not: nothing there means centre on the sample mean, which the functor computes from the returns, so LowOrderMoment declares no method. A slot that holds a child measure is not named here either. The child names its own slots, and assert_resolved_slots reaches it through deferred_slots. So the functor of VarianceSkewKurtosis reads the matrices of its children, and a refusal names the child, such as Skewness.sk.

Related

source
PortfolioOptimisers.resolve_calibration_slots — Method
resolve_calibration_slots(x, pr::AbstractPriorResult, slv = nothing)

Resolve the slots that calibration_slots declared, and return them as a NamedTuple for resolve_deferred_quantities to rebuild from. The answer is empty when no slot held a Calibration Rule.

This is the derived half of the calibration channel, and it is the parallel of the container recursion in resolve_deferred_quantities. A type whose slots carry no order between them declares them once and writes no resolution: the declaration is the whole statement, and this method reads it.

A type whose slots do carry an order writes its own resolve_deferred_quantities method instead, and that method is more specific, so it wins. A CalibrationContext built from a sibling's resolved number is what an order looks like: the slot reads that number off the context, and no derivation can know which sibling or in which direction. That rule reaches the slots that read a sibling and no others.

A type whose slot key is not the field's name declares a method of this verb returning an empty NamedTuple, which takes it out of the derivation. The three regularisation keys are the one case that ships: val is one field under three quantities, and a derivation that read the field name would hand the rule the wrong key.

The effective observation weights and the effective solver are the two quantities a rule reads beyond the prior, and both are read off x by the names the library gives them everywhere: w holds the measure's own observation weights and slv its own solver. A type that carries the field settles it against the caller's with sel; a type that carries none reads nothing and sel then hands over what the caller gave. The read is skipped where no slot holds a role, so a container whose w names a child rather than a weight vector never reaches it.

The empty answer is what keeps a container's key out of the merge. A container names one child in both declarations, the child holds no role, and the answer is therefore empty rather than a restatement of the unresolved child.

Algorithm

  1. Read the slots x declares with calibration_slots, giving slots.
  2. Return an empty NamedTuple when is_calibration_rule answers false for every entry of slots. A stated number resolves to itself, so the walk would move nothing.
  3. Read every field of x into props, by index, which is the shape rebuild_with_slots builds. A field read by name would name a field some type reaching this method does not carry.
  4. Settle the effective observation weights w, as sel(props.w, pr.w) where x carries the field and sel(nothing, pr.w) where it does not.
  5. Settle the effective solver sv, as sel(props.slv, slv) where x carries the field and sel(nothing, slv) where it does not.
  6. Resolve every entry of slots with resolve_calibration_slot, giving each its own name as the key and threading pr, w and sv.

Returns

  • slots::NamedTuple: The resolved calibration slots, and an empty NamedTuple where none held a role.

Related

source
PortfolioOptimisers.resolve_deferred_quantities — Method
resolve_deferred_quantities(x, pr::AbstractPriorResult, slv = nothing)

Resolve the children that deferred_slots declared and the slots that calibration_slots declared, and return x itself when none of them changed.

This is the derived half of the resolution rule. A container declares its children once and both entry points follow: factory reaches them through @fprop, and the JuMP builders reach them through this method. Neither needs a forwarding method per container.

A type that resolves a quantity of its own overrides this with its own method, which is more specific. So the derivation carries container recursion alone, and never guesses how a matrix, a tensor or the centre a moment was taken about comes out of a fit.

Both channels end in one rebuild: a measure that carries both kinds of slot must not be rebuilt twice. resolve_calibration_slots states the calibration half and returns its resolved slots rather than a rebuilt object, and the two answers merge here. The deferred half merges last, so it wins a key both channels declare. A container names one child in both, and the child the recursion resolved is the one to keep.

slv is the effective solver, and the recursion threads it to every child. A container states no solver of its own, so it changes none: each child settles the one it was handed against the one it carries.

Algorithm

  1. Read the slots x declares with deferred_slots, giving slots.
  2. Read the resolved calibration slots with resolve_calibration_slots, giving calibrated.
  3. Return x unchanged when both are empty. A type with neither kind of slot needs no method of its own.
  4. Resolve every entry of slots with resolve_deferred_quantities, threading pr and slv to each, giving resolved. A child measure resolves through its own method, a vector of children through the vector method, and any other occupant comes back unchanged through this method, because it declares no slot: a stated value, nothing or a Deferred Quantity that the enclosing type resolves itself.
  5. Refuse a slot the recursion left unresolved with assert_declared_slot_resolver.
  6. Hand merge(calibrated, resolved) to rebuild_with_slots, which returns x itself when no entry moved and a rebuilt copy when one did.

Returns

  • x itself when no slot moved, and a rebuilt copy of x when one did.

Related

source
PortfolioOptimisers.resolve_deferred_quantities — Method
resolve_deferred_quantities(x, pr::AbstractPriorResult, slv = nothing)

Resolve the children that deferred_slots declared and the slots that calibration_slots declared, and return x itself when none of them changed.

This is the derived half of the resolution rule. A container declares its children once and both entry points follow: factory reaches them through @fprop, and the JuMP builders reach them through this method. Neither needs a forwarding method per container.

A type that resolves a quantity of its own overrides this with its own method, which is more specific. So the derivation carries container recursion alone, and never guesses how a matrix, a tensor or the centre a moment was taken about comes out of a fit.

Both channels end in one rebuild: a measure that carries both kinds of slot must not be rebuilt twice. resolve_calibration_slots states the calibration half and returns its resolved slots rather than a rebuilt object, and the two answers merge here. The deferred half merges last, so it wins a key both channels declare. A container names one child in both, and the child the recursion resolved is the one to keep.

slv is the effective solver, and the recursion threads it to every child. A container states no solver of its own, so it changes none: each child settles the one it was handed against the one it carries.

Algorithm

  1. Read the slots x declares with deferred_slots, giving slots.
  2. Read the resolved calibration slots with resolve_calibration_slots, giving calibrated.
  3. Return x unchanged when both are empty. A type with neither kind of slot needs no method of its own.
  4. Resolve every entry of slots with resolve_deferred_quantities, threading pr and slv to each, giving resolved. A child measure resolves through its own method, a vector of children through the vector method, and any other occupant comes back unchanged through this method, because it declares no slot: a stated value, nothing or a Deferred Quantity that the enclosing type resolves itself.
  5. Refuse a slot the recursion left unresolved with assert_declared_slot_resolver.
  6. Hand merge(calibrated, resolved) to rebuild_with_slots, which returns x itself when no entry moved and a rebuilt copy when one did.

Returns

  • x itself when no slot moved, and a rebuilt copy of x when one did.

Related

source
resolve_deferred_quantities(xs::AbstractArray{<:Union{AbstractEstimator, AbstractAlgorithm}},
                            pr::AbstractPriorResult, slv = nothing)

Resolve a slot that holds a vector of children, element by element, which is the rule factory applies on the other path.

The method is bounded by the element type rather than by AbstractArray, so a matrix slot is a value and never a container of children. slv is the effective solver, and it travels down to each child untouched, so a container hands each child the solver that the enclosing measure was resolved against.

Related

source
PortfolioOptimisers.rebuild_with_slots — Function
rebuild_with_slots(x, slots::NamedTuple)

Return x itself when every field named by slots already holds the value slots gives it, and a copy of x carrying those values when one of them moved.

This is the one rebuild of the resolution channel. The field list is derived from the type and the constructor is recovered from it, so nothing is written per type: a field added to the type joins the rebuild on its own, and no site can drop one. Every resolve_deferred_quantities method ends here, the derived recursion and the per-type overrides alike.

The call is positional, so the inner constructor runs and every guard the type states is re-applied to the rebuilt value. A Calibration Rule that returns a value the slot does not admit is therefore refused at fold time, by the guard a caller's own number meets.

Algorithm

  1. Read the type of x into T.
  2. Read every field of x into the named tuple props, in declaration order.
  3. Return x itself when every entry of slots is the value the field of that name already held, so the common case allocates nothing.
  4. Merge slots over props, so a named slot carries its new value and every other field survives.
  5. Call T.name.wrapper positionally on the merged values, so the inner constructor runs and re-applies every guard the type states.

Validation

  • Throws whatever the inner constructor of T throws for the merged values, so a slot that moved out of its admitted range is refused here.

Returns

  • x itself when no slot moved, and a value of the same type as x holding the values in slots when one did.

Related

source
PortfolioOptimisers.assert_declared_slot_resolver — Function
assert_declared_slot_resolver(x, slots::NamedTuple)

Refuse a type that declares a deferrable slot and no way to resolve it.

slots is what the derived recursion produced. A Deferred Quantity that survives it names a type that declared the slot in deferred_slots and then wrote no resolve_deferred_quantities method, so the estimator would reach the model builders and be multiplied as though it were a matrix. The two declarations are paired; this is where the pair is enforced.

Algorithm

  1. Walk the pairs of slots, giving each slot's name key and its occupant slot.
  2. Refuse an occupant that is still a DeferredQuantity.
  3. Return nothing once the walk is spent.

Validation

  • Throws an ArgumentError when an entry of slots still holds a DeferredQuantity. The message names the type, the slot and the method to declare.

Returns

  • nothing.

Related

source
PortfolioOptimisers.assert_resolved_slots — Function
assert_resolved_slots(x)

Refuse a Deferred Quantity, or an empty slot the functor reads, that reached a value-level entry point, which has no prior result to resolve or fill it with.

expected_risk takes either a prior result or a plain returns matrix. Given the prior it resolves the measure through factory first. Given the matrix it cannot: that call has no pr.w to thread and no factor returns to reach, so resolving there would use a different rule than the settled one. So it refuses, and the error names the slot and the Estimator in it. Without the refusal, the failure happens several frames down, inside a kernel that expected a matrix.

The same check refuses a slot that holds nothing when the functor reads it as it stands. Variance() is built with sigma at nothing, and the prior route fills it through factory; the matrix route has nothing to fill it from, and dot(w, nothing, w) raised a bare MethodError inside LinearAlgebra that named neither the measure nor the slot. functor_slots declares which slots those are, so a slot whose nothing has a value-level reading is never refused. The mu of a moment measure is such a slot, and nothing there means the sample mean. Resolving the slot from the matrix instead would pick an estimator the caller never named, and would make the matrix route and the prior route disagree whenever the prior is not empirical, so the check refuses the slot with an error that names it and states the two ways out.

This is the shape HopCount and PathLength already use: the consumer resolves, the kernel refuses.

The slots come from deferred_slots and the check recurses into whatever they hold, so a container is covered by its children's declarations. A slot that holds a vector of children is recursed element by element, which is the rule that the vector method of resolve_deferred_quantities applies on the resolution path. Every slot of a concretely-typed measure has a concrete field type, so the test is a type-level one and a leaf measure compiles the whole check away. A container pays one small allocation per call for the recursion into its children.

The message names both types with nameof, not by printing the type. A printed type carries a module prefix whenever the name is not visible from Main, which is the case inside an isolated test worker and inside any module that imports the package qualified. Variance.sigma is the path the caller wrote, and the message must read the same in every process.

Algorithm

  1. Walk the pairs that deferred_slots declares for x, giving each slot's name key and its occupant slot, and refuse an occupant that holds a DeferredQuantity.
  2. Recurse into every occupant, so a child measure's own slots are checked as well. A slot that holds a vector of children is walked element by element.
  3. Walk the pairs that functor_slots declares for x, and refuse an occupant that is nothing, with assert_filled_functor_slots.
  4. Return nothing once the three walks are spent.

The order is the precedence. A Deferred Quantity on x is named before anything below it, because its fit is what would fill the empty slots of the children. A VarianceSkewKurtosis whose pe is deferred has an empty sigma on its vr for that reason alone. A child is walked before the slots x reads off it, for the same reason one level down: a Skewness whose pe is deferred has an empty sk, and that is the slot the container reads.

Validation

  • Throws an ArgumentError when a slot of x, or of any child the walk reaches, holds a DeferredQuantity. The message names the slot, the Estimator standing in it and the two ways out.
  • Throws an IsNothingError when a slot that functor_slots declares for x, or for any child the walk reaches, holds nothing. The message names the slot and the ways out: a prior result that carries the quantity, or the quantity stated on the measure. For the solver slot slv, the way out is a Solver stated on the measure.

Returns

  • nothing.

Related

source
PortfolioOptimisers.assert_filled_functor_slots — Function
assert_filled_functor_slots(x) -> Nothing

Refuse a slot that functor_slots declares for x and that holds nothing.

assert_resolved_slots calls it at each level of its walk, and assert_scoreable calls that walk on the measure that a selector scores with, so a child of a container is checked too. Neither route has an optimiser to fill a slot, so the functor would meet the nothing several frames down, with an error that names neither the measure nor the slot.

The message depends on the slot. A moment slot, such as the sigma of a Variance, can come from a prior result, so the message names a prior result and the quantity stated on the measure. A solver slot slv, such as that of an EntropicValueatRisk, comes from no data, so the message names a Solver stated on the measure.

Algorithm

  1. Walk the pairs that functor_slots declares for x, and throw on the first occupant that is nothing.
  2. Return nothing.

Arguments

  • x: The measure, or the child of a measure, to check.

Validation

  • Throws an IsNothingError that names the slot and the way out, when a declared slot holds nothing.

Returns

  • nothing.

Related

source
PortfolioOptimisers.sigma_chol_selector — Function
sigma_chol_selector(sigma, chol, pr::AbstractPriorResult)

Apply the prior fallback to a covariance slot and its factorisation as a pair, so that the two never come from two different sources.

chol is a factorisation of sigma. Pairing a factor with a covariance matrix it does not factorise would let the model optimise one quantity while the functor evaluates another. So the pair falls back to the prior only when the measure names neither; a stated sigma with no factor keeps no factor, and the consumer derives the right one.

The Deferred-Quantity state never reaches here: resolve_deferred_quantities has already turned it into the pair the fit produced. Nor does a stated chol without a matrix sigma beside it. assert_derived_slot_has_source refuses that state at construction, and it refuses a chol stated beside a deferred sigma too, so the two methods below see only value states.

A stated chol is never rebuilt from sigma. Under a factor prior the factorisation is sparse and special, and a rebuild would throw that structure away.

Related

source
PortfolioOptimisers.assert_derived_slot_has_source — Function
assert_derived_slot_has_source(derived, source, dname::Symbol, sname::Symbol)

Refuse a derived slot that was stated without a source the caller can see.

A derived slot is a function of its source, so the two are one pair out of one fit. Two states break that, and both are refused at construction:

  • The source is unstated. The prior supplies it, so the caller's derived value would pair with a source the caller never saw.
  • The source holds a Deferred Quantity. That fit supplies the pair, so the caller's derived value would be discarded, or worse, kept beside a source it does not describe.

chol is a factorisation of sigma, and V is the negative spectral part of sk. Both follow this rule, so a stated derived slot always means a stated source value.

Arguments

  • derived: The derived slot's occupant.
  • source: The source slot's occupant.
  • dname: Name of the derived slot, as the message prints it.
  • sname: Name of the source slot, as the message prints it.

Validation

  • Throws an ArgumentError when source holds a DeferredQuantity and derived is not nothing. That fit supplies the pair.
  • Throws an ArgumentError when derived is not nothing and source is nothing. The prior would supply the source, and the caller's derived value would pair with a source the caller never saw.

Returns

  • nothing.

Related

source
PortfolioOptimisers.risk_measure_nothing_scalar_array_view — Function
risk_measure_nothing_scalar_array_view(risk_variable, prior_variable, i)

Get a view of a risk measure's risk or prior variable for index i.

Internal helper for slicing scalar, array, or nothing risk/prior variables by index. Dispatches on the types of risk_variable and prior_variable.

Arguments

  • risk_variable: Risk variable (scalar, array, or nothing).
  • prior_variable: Prior variable (array or nothing).
  • i: Index or range to slice.

Validation

  • Throws an ArgumentError when risk_variable and prior_variable are both nothing. There is then nothing to slice, and the caller named no source.

Returns

  • Sliced or unchanged value.

Related

source
PortfolioOptimisers.assert_observation_weights — Function
assert_observation_weights(w::VecNum, w_sym::Sym_Str = :w)
assert_observation_weights(::Option{<:UnresolvedValue}, ::Sym_Str = :w)

Validate the observation weights of a risk measure.

A risk measure divides by the sum of its observation weights, so a weight vector that sums to zero has no value to give. This assertion refuses it with the rules of assert_nonempty_nonneg_finite_val and one rule more. A DynamicAbstractWeights is an UnresolvedValue: it has no values until it resolves against the data, so it selects the second method, and checked_observation_weights validates its values after it resolves. nothing selects the second method too. Each other type is a MethodError, so a form that a slot admits with no rule fails at construction.

Arguments

  • w: Observation weights.
  • w_sym: Symbolic name used in the error messages.

Validation

  • w is not empty, finite and nonnegative, through assert_nonempty_nonneg_finite_val.
  • sum(w) > 0, so at least one observation carries weight. Otherwise a DomainError is raised.
  • ::Option{<:UnresolvedValue}: No rule, so the call always passes.

Returns

  • nothing.

Related

source
PortfolioOptimisers.checked_observation_weights — Function
checked_observation_weights(w::Option{<:ObsWeights}, X::VecNum_MatNum) -> Option{<:VecNum}

Resolve the observation weights of a risk measure against its data, and check that they fit the data.

The rows of X, or the entries of a return series X, are the observations. A risk measure reads one weight for each of them, and a weighted quantile reads the weights through the sort permutation of the returns. A weight vector with the wrong length therefore gives a wrong value in silence, or an error that does not name the weights. This function names them.

Algorithm

  1. Resolve w with get_observation_weights. nothing stays nothing.
  2. Validate the values of the resolved weights with assert_observation_weights. A StatsBase.AbstractWeights was validated by the constructor of its measure, but a DynamicAbstractWeights and the weights of a prior result were not.
  3. Check that the length of the weights equals size(X, 1).

Arguments

  • w: Optional observation weights vector observations × 1, or a concrete subtype of DynamicAbstractWeights. If nothing, the computation is unweighted.
  • X: Returns matrix observations × assets, or a return series of length observations.

Validation

Returns

  • w::Option{<:VecNum}: The resolved observation weights, or nothing when w is nothing. The vector is borrowed, as get_observation_weights states.

Related

source
PortfolioOptimisers.assert_half_open_unit_interval — Function
assert_half_open_unit_interval(val::Number, sym::Sym_Str = :val)
assert_half_open_unit_interval(::Option{<:UnresolvedValue}, ::Sym_Str = :val)

Validate that 0 <= val < 1.

The significance level of a tail measure whose limit at zero is defined takes this interval. At val = 0 the tail holds only the worst observation with positive weight, which worst_positive_weight_loss gives. A level of one would hold the whole sample, so it stays open. A Calibration Rule is an UnresolvedValue: it has no value until it resolves, so it selects the second method, and the rebuild after the resolution checks the number. Each other type is a MethodError, so a form that a slot admits with no rule fails at construction.

Arguments

  • val: Input value to validate.
  • sym: Symbolic name used in the error messages.

Validation

  • 0 <= val < 1. Otherwise a DomainError is raised.
  • ::Option{<:UnresolvedValue}: No rule, so the call always passes.

Returns

  • nothing.

Related

source
PortfolioOptimisers.worst_positive_weight_loss — Function
worst_positive_weight_loss(x::VecNum, ::Nothing) -> Number
worst_positive_weight_loss(x::VecNum, w::VecNum) -> Number

Return the largest loss of x among the observations with positive weight.

This is the value of a tail measure at significance level zero. ConditionalValueatRisk and EntropicValueatRisk read it on the returns, PRM reads it as the value of PowerNormValueatRisk under the condition of that measure, and ConditionalDrawdownatRisk and EntropicDrawdownatRisk read it on the drawdowns. An observation with zero weight has no probability, so it cannot be the worst outcome. WorstRealisation and MaximumDrawdown read every observation instead.

Arguments

  • x: Return or drawdown series. A loss is a negative entry. Not modified.
  • w: Resolved observation weights from checked_observation_weights, or nothing. The weights have at least one positive entry.

Returns

  • Number: The largest loss, -minimum(x[t] for t with w[t] > 0).

Related

source
PortfolioOptimisers.positive_weight_rows — Function
positive_weight_rows(::Nothing, T::Integer) -> Base.OneTo
positive_weight_rows(w::VecNum, T::Integer) -> Vector{Int}

Return the indices of the observations with positive weight.

A programme with one row for each observation builds its rows on these indices. An observation with zero weight has no probability, so its row does not change the optimum. But the row of a large loss makes a cone programme harder to solve, and an exponential cone row can stop the solver far from the optimum. ERM, RRM, PRM and the JuMP constraint layer of their measures read it.

Arguments

Returns

  • The indices 1:T when w is nothing. Otherwise, the indices t with w[t] > 0.

Related

source
PortfolioOptimisers.moment_target_fees — Function
moment_target_fees(
    mu,
    w::AbstractVector{<:Union{Number, AbstractJuMPScalar}},
    fees::Union{Nothing, Fees},
    T::Integer
) -> Any

Return the fee that a moment target mu subtracts, so that a per-asset target centres a net series on its net mean.

A per-asset target states a gross expected return, $\boldsymbol{w}^\intercal \boldsymbol{\mu}$. The series a moment measure centres is net of the fee, so the target is the net mean $\boldsymbol{w}^\intercal \boldsymbol{\mu} - \bar{F}(\boldsymbol{w})$, where $\bar{F}$ is the mean fee per period that term_fees charges. A per period fee then cancels from every deviation, and the value of the measure agrees with its JuMP model. A target that weight_independent_target calls weight-independent (the mean or the median of the net series, or a scalar threshold) is already stated on the net series, so it subtracts nothing.

Arguments

  • mu: The target slot of the measure.
  • w: The weights of the target, $\boldsymbol{w}$ in $\boldsymbol{w}^\intercal \boldsymbol{\mu}$.
  • fees: Fee of the portfolio whose series is centred, or nothing.
  • T: Observation count of the series, over which the one-off terms are spread.

Returns

  • f::Number: $\bar{F}(\boldsymbol{w})$ for a per-asset target, and a zero of the element type of w otherwise.

Related

source