Base Risk Measures: private API
PortfolioOptimisers.AbstractBaseRiskMeasure — Type
abstract type AbstractBaseRiskMeasure <: AbstractEstimatorAbstract 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
PortfolioOptimisers.NonOptimisationRiskMeasure — Type
abstract type NonOptimisationRiskMeasure <: AbstractBaseRiskMeasureAbstract 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
PortfolioOptimisers.OptimisationRiskMeasure — Type
abstract type OptimisationRiskMeasure <: AbstractBaseRiskMeasureAbstract supertype for risk measures that are intended for use in portfolio optimisation routines.
Every concrete risk measure that an optimiser takes as an objective or as a constraint subtypes OptimisationRiskMeasure, through RiskMeasure or HierarchicalRiskMeasure.
Related
PortfolioOptimisers.JuMPRiskMeasureSettings — Type
abstract type JuMPRiskMeasureSettings <: AbstractRiskMeasureSettingsAbstract supertype for risk measure settings used in JuMP-based optimisation routines.
Every concrete settings type that a JuMP optimisation reads subtypes JuMPRiskMeasureSettings. RiskMeasureSettings and MaxRiskMeasureSettings are the two that the library defines.
Related
PortfolioOptimisers.NonHierarchicalScalariser — Type
abstract type NonHierarchicalScalariser <: ScalariserAbstract 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
PortfolioOptimisers.HierarchicalScalariser — Type
abstract type HierarchicalScalariser <: ScalariserAbstract 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
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
PortfolioOptimisers.MuSlot — Type
const MuSlot = Union{Num_VecNum_VecScalar, AbstractExpectedReturnsEstimator, AbstractPriorEstimator}Field bound for an expected-returns slot: the value itself, or the Estimator that computes it. See DeferredQuantity.
Related
PortfolioOptimisers.SigmaSlot — Type
const SigmaSlot = Union{MatNum, StatsBase.CovarianceEstimator, AbstractPriorEstimator}Field bound for a covariance slot: the matrix itself, or the Estimator that computes it. See DeferredQuantity.
Related
PortfolioOptimisers.KtSlot — Type
const KtSlot = Union{MatNum, CokurtosisEstimator, AbstractPriorEstimator}Field bound for a cokurtosis slot: the matrix itself, or the Estimator that computes it. See DeferredQuantity.
Related
PortfolioOptimisers.SkSlot — Type
const SkSlot = Union{MatNum, CoskewnessEstimator, AbstractPriorEstimator}Field bound for a coskewness slot: the matrix itself, or the Estimator that computes it. See DeferredQuantity.
Related
PortfolioOptimisers.VecBaseRM — Type
const VecBaseRM = AbstractVector{<:AbstractBaseRiskMeasure}Alias for an abstract vector of AbstractBaseRiskMeasure elements.
Related
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
PortfolioOptimisers.VecOptRM — Type
const VecOptRM = AbstractVector{<:OptimisationRiskMeasure}Alias for an abstract vector of OptimisationRiskMeasure elements.
Related
PortfolioOptimisers.OptRM_VecOptRM — Type
const OptRM_VecOptRM = Union{OptimisationRiskMeasure, VecOptRM}Union type accepting a single OptimisationRiskMeasure or a vector of them.
Related
PortfolioOptimisers.VecRM — Type
const VecRM = AbstractVector{<:RiskMeasure}Alias for an abstract vector of RiskMeasure elements.
Related
PortfolioOptimisers.RM_VecRM — Type
const RM_VecRM = Union{RiskMeasure, VecRM}Union type accepting a single RiskMeasure or a vector of them.
Related
PortfolioOptimisers.RkRtBounds — Type
const RkRtBounds = Union{Num_VecNum, Frontier}Union type for risk-measure upper bound specifications.
Accepts either a scalar/vector numeric bound or a Frontier sweep configuration. Used in RiskMeasureSettings to set the upper bound field.
Related
PortfolioOptimisers.Front_NumVec — Type
const Front_NumVec = Union{VecNum, Frontier}Union type for frontier or numeric-vector specifications used internally for risk bounds.
Related
PortfolioOptimisers.RiskInputKind — Type
abstract type RiskInputKindAbstract supertype for the input-shape classification of a risk measure, used by expected_risk to decide what to feed a measure's functor.
Each concrete AbstractBaseRiskMeasure declares its kind via risk_input_kind. The three kinds correspond to the three functor call shapes:
NetReturnsInput:r(calc_net_returns(w, X, fees)).WeightsReturnsFeesInput:r(w, X, fees).WeightsInput:r(w).
Related
PortfolioOptimisers.NetReturnsInput — Type
struct NetReturnsInput <: RiskInputKindInput kind for risk measures whose expected risk is computed on net returns (returns after fees). The measure's functor is called as r(calc_net_returns(w, X, fees)).
Related
PortfolioOptimisers.WeightsReturnsFeesInput — Type
struct WeightsReturnsFeesInput <: RiskInputKindInput kind for risk measures whose expected risk depends on weights, the returns matrix, and fees. The measure's functor is called as r(w, X, fees).
Related
PortfolioOptimisers.WeightsInput — Type
struct WeightsInput <: RiskInputKindInput kind for risk measures whose expected risk depends only on portfolio weights. The measure's functor is called as r(w).
Related
PortfolioOptimisers.scalarise_combine — Function
scalarise_combine(op, a, b)Combine two scalarised risk values slot-wise.
Numbers combine directly via op, arrays elementwise, and tuples recursively per slot. Used by scalarise to accumulate values that may be scalars, vectors, or tuples mixing both.
Related
PortfolioOptimisers.scalarise_map — Function
scalarise_map(op, x)Apply op slot-wise to a scalarised risk value.
Numbers are transformed directly, arrays elementwise, and tuples recursively per slot.
Related
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
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
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
nothingreturnsnothing. - If
risk_variableis notnothing, returnsrisk_variable. - If
risk_variableisnothingandprior_variableis notnothing, returnsprior_variable.
Related
PortfolioOptimisers.deferred_factors — Function
deferred_factors(pr::AbstractPriorResult)Return the factor returns matrix carried by prior result pr, or nothing when pr has no factor block. This is the only channel through which factors reach a risk-measure slot: no moment estimator takes an F, so a slot that must see factors has to hold an AbstractPriorEstimator.
Related
PortfolioOptimisers.CoskewnessFit — Type
struct CoskewnessFit{__T_sk, __T_V, __T_skmp} <: AbstractResultHolds 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.
skmp: The matrix-processing estimator that builtV, fromcoskewness_processor, ornothing.
Related
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
- Rebuild
dqagainst the prior's observation weights withfactory(dq, pr.w). The two co-moment arms bind the rebuilt estimator askteandske. - Run the rebuilt estimator on
pr.original_X, through the verb of its own family:Statistics.meanfor an expected-returns estimator,Statistics.covfor a covariance estimator,cokurtosisfor a cokurtosis estimator,coskewnessfor a coskewness estimator, andpriorfor a prior estimator, which also takesdeferred_factors(pr). - Return the quantity the verb gave. The coskewness arm returns a
CoskewnessFitinstead, becauseVcomes out of the same call andcoskewness_processornames 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
AbstractPriorResultfor a prior estimator, and aCoskewnessFitfor a coskewness estimator.
Related
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
ArgumentErrorwhenfittedis aCoskewnessFitcarrying no fieldkey, and whenfittedis anAbstractPriorResultcarrying no propertykey. The slot named an estimator that computes something else, and a silentnothingwould reach the model builders as though the caller had stated none. This is the difference fromdeferred_derived_quantity, which answersnothingfor a key its fit does not carry.
Returns
- The quantity named by
key, or the whole fit when a moment estimator produced it.
Related
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
- Return
slotunchanged when it is notnothing. A slot the caller stated wins over the fan-out. - Read the quantity named by
keyofffittedwithdeferred_quantity, and return it.
Returns
- The stated slot, or the quantity named by
key.
Related
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
peisnothing: rebuildxwithslots.- Otherwise fit
peagainstprone time. Fill each slot ofslotswithfan_out_slotunder its own name, and rebuildxwith the filled slots andpe = nothing.
Arguments
x: The measure, or the algorithm of a measure, that holds the slots.pe: The fan-out estimator ofx, ornothing.pr: The prior result thatpeis fitted against.slots: The resolved slots, keyed by field name.
Returns
- The rebuilt
x.
Related
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
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
- Return
slotunchanged when it is not aDeferredQuantity. A stated value,nothingand a centring strategy all take that arm. - Run the Deferred Quantity against
prwithfit_deferred_quantity, givingfitted. - Read the quantity named by
keyofffittedwithdeferred_quantity, and return it.
Returns
- A plain value: the slot's own occupant, or the quantity the fit produced.
Related
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
- Return
sigmaandcholunchanged whensigmais not aDeferredQuantity. - Run the Deferred Quantity against
prwithfit_deferred_quantity, givingfitted. - Read
sigmaofffittedwithdeferred_quantity, andcholwithdeferred_derived_quantity.
Returns
(; sigma, chol): the pair, to give torebuild_with_slots.
Related
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
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
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
- Read the slots
xdeclares withcalibration_slots, givingslots. - Return an empty
NamedTuplewhenis_calibration_ruleanswersfalsefor every entry ofslots. A stated number resolves to itself, so the walk would move nothing. - Read every field of
xintoprops, by index, which is the shaperebuild_with_slotsbuilds. A field read by name would name a field some type reaching this method does not carry. - Settle the effective observation weights
w, assel(props.w, pr.w)wherexcarries the field andsel(nothing, pr.w)where it does not. - Settle the effective solver
sv, assel(props.slv, slv)wherexcarries the field andsel(nothing, slv)where it does not. - Resolve every entry of
slotswithresolve_calibration_slot, giving each its own name as the key and threadingpr,wandsv.
Returns
slots::NamedTuple: The resolved calibration slots, and an emptyNamedTuplewhere none held a role.
Related
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
- Read the slots
xdeclares withdeferred_slots, givingslots. - Read the resolved calibration slots with
resolve_calibration_slots, givingcalibrated. - Return
xunchanged when both are empty. A type with neither kind of slot needs no method of its own. - Resolve every entry of
slotswithresolve_deferred_quantities, threadingprandslvto each, givingresolved. 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,nothingor a Deferred Quantity that the enclosing type resolves itself. - Refuse a slot the recursion left unresolved with
assert_declared_slot_resolver. - Hand
merge(calibrated, resolved)torebuild_with_slots, which returnsxitself when no entry moved and a rebuilt copy when one did.
Returns
xitself when no slot moved, and a rebuilt copy ofxwhen one did.
Related
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
- Read the slots
xdeclares withdeferred_slots, givingslots. - Read the resolved calibration slots with
resolve_calibration_slots, givingcalibrated. - Return
xunchanged when both are empty. A type with neither kind of slot needs no method of its own. - Resolve every entry of
slotswithresolve_deferred_quantities, threadingprandslvto each, givingresolved. 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,nothingor a Deferred Quantity that the enclosing type resolves itself. - Refuse a slot the recursion left unresolved with
assert_declared_slot_resolver. - Hand
merge(calibrated, resolved)torebuild_with_slots, which returnsxitself when no entry moved and a rebuilt copy when one did.
Returns
xitself when no slot moved, and a rebuilt copy ofxwhen one did.
Related
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
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
- Read the type of
xintoT. - Read every field of
xinto the named tupleprops, in declaration order. - Return
xitself when every entry ofslotsis the value the field of that name already held, so the common case allocates nothing. - Merge
slotsoverprops, so a named slot carries its new value and every other field survives. - Call
T.name.wrapperpositionally on the merged values, so the inner constructor runs and re-applies every guard the type states.
Validation
- Throws whatever the inner constructor of
Tthrows for the merged values, so a slot that moved out of its admitted range is refused here.
Returns
xitself when no slot moved, and a value of the same type asxholding the values inslotswhen one did.
Related
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
- Walk the pairs of
slots, giving each slot's namekeyand its occupantslot. - Refuse an occupant that is still a
DeferredQuantity. - Return
nothingonce the walk is spent.
Validation
- Throws an
ArgumentErrorwhen an entry ofslotsstill holds aDeferredQuantity. The message names the type, the slot and the method to declare.
Returns
nothing.
Related
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
- Walk the pairs that
deferred_slotsdeclares forx, giving each slot's namekeyand its occupantslot, and refuse an occupant that holds aDeferredQuantity. - 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.
- Walk the pairs that
functor_slotsdeclares forx, and refuse an occupant that isnothing, withassert_filled_functor_slots. - Return
nothingonce 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
ArgumentErrorwhen a slot ofx, or of any child the walk reaches, holds aDeferredQuantity. The message names the slot, the Estimator standing in it and the two ways out. - Throws an
IsNothingErrorwhen a slot thatfunctor_slotsdeclares forx, or for any child the walk reaches, holdsnothing. 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 slotslv, the way out is aSolverstated on the measure.
Returns
nothing.
Related
PortfolioOptimisers.assert_filled_functor_slots — Function
assert_filled_functor_slots(x) -> NothingRefuse 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
- Walk the pairs that
functor_slotsdeclares forx, and throw on the first occupant that isnothing. - Return
nothing.
Arguments
x: The measure, or the child of a measure, to check.
Validation
- Throws an
IsNothingErrorthat names the slot and the way out, when a declared slot holdsnothing.
Returns
nothing.
Related
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
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
ArgumentErrorwhensourceholds aDeferredQuantityandderivedis notnothing. That fit supplies the pair. - Throws an
ArgumentErrorwhenderivedis notnothingandsourceisnothing. The prior would supply the source, and the caller's derived value would pair with a source the caller never saw.
Returns
nothing.
Related
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, ornothing).prior_variable: Prior variable (array ornothing).i: Index or range to slice.
Validation
- Throws an
ArgumentErrorwhenrisk_variableandprior_variableare bothnothing. There is then nothing to slice, and the caller named no source.
Returns
- Sliced or unchanged value.
Related
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
wis not empty, finite and nonnegative, throughassert_nonempty_nonneg_finite_val.sum(w) > 0, so at least one observation carries weight. Otherwise aDomainErroris raised.::Option{<:UnresolvedValue}: No rule, so the call always passes.
Returns
nothing.
Related
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
- Resolve
wwithget_observation_weights.nothingstaysnothing. - Validate the values of the resolved weights with
assert_observation_weights. AStatsBase.AbstractWeightswas validated by the constructor of its measure, but aDynamicAbstractWeightsand the weights of a prior result were not. - Check that the length of the weights equals
size(X, 1).
Arguments
w: Optional observation weights vectorobservations × 1, or a concrete subtype ofDynamicAbstractWeights. Ifnothing, the computation is unweighted.X: Returns matrixobservations × assets, or a return series of lengthobservations.
Validation
- The resolved weights pass
assert_observation_weights. length(w) == size(X, 1). Otherwise aDimensionMismatchis raised.
Returns
w::Option{<:VecNum}: The resolved observation weights, ornothingwhenwisnothing. The vector is borrowed, asget_observation_weightsstates.
Related
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 aDomainErroris raised.::Option{<:UnresolvedValue}: No rule, so the call always passes.
Returns
nothing.
Related
PortfolioOptimisers.worst_positive_weight_loss — Function
worst_positive_weight_loss(x::VecNum, ::Nothing) -> Number
worst_positive_weight_loss(x::VecNum, w::VecNum) -> NumberReturn 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 fromchecked_observation_weights, ornothing. The weights have at least one positive entry.
Returns
Number: The largest loss,-minimum(x[t] for t with w[t] > 0).
Related
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
w: Resolved observation weights fromchecked_observation_weights, ornothing.T: Number of observations.
Returns
- The indices
1:Twhenwisnothing. Otherwise, the indicestwithw[t] > 0.
Related
PortfolioOptimisers.weight_independent_target — Method
weight_independent_target(_::Nothing) -> Bool
Return true. A nothing target reads no weights, so a bare return series is enough to evaluate it.
Related
PortfolioOptimisers.weight_independent_target — Method
weight_independent_target(_::Number) -> Bool
Return true. A scalar target reads no portfolio weights, so a bare return series is enough to evaluate it.
Related
PortfolioOptimisers.weight_independent_target — Method
weight_independent_target(_) -> Bool
Return false. The target reads the portfolio weights, as a per-asset mu does through dot(w, mu), so a bare return series is not enough to evaluate it.
Related
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, ornothing.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 ofwotherwise.
Related