Weight bounds constraint generation
PortfolioOptimisers.WeightBounds — Type
struct WeightBounds{__T_lb, __T_ub} <: AbstractConstraintResultHolds the lower bound and the upper bound of every portfolio weight.
A bound is a scalar that applies to every asset, a vector with one bound per asset, or nothing for no bound on that side. The mixed-integer builders also read the bounds as the big-M that links a weight to its held indicator.
Mathematical definition
\[\begin{align} \boldsymbol{l} \leq \boldsymbol{w} \leq \boldsymbol{u}\,. \end{align}\]
Where:
- $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
- $\boldsymbol{l}$: Lower bound vector $N \times 1$. An entry of $-\infty$ leaves that weight unbounded below. An entry of $+\infty$ admits no value of that weight.
- $\boldsymbol{u}$: Upper bound vector $N \times 1$. An entry of $+\infty$ leaves that weight unbounded above. An entry of $-\infty$ admits no value of that weight.
- $N$: Number of assets.
A scalar bound is a vector with the same value in every entry. A nothing bound is a vector with the free bound in every entry, $-\infty$ on the lower side and $+\infty$ on the upper side.
Fields
lb: Lower bound.
ub: Upper bound.
Constructors
WeightBounds( lb::Option{<:Num_VecNum}, ub::Option{<:Num_VecNum}) -> WeightBoundsWeightBounds(; lb::Option{<:Num_VecNum} = 0.0, ub::Option{<:Num_VecNum} = 1.0) -> WeightBoundsKeywords correspond to the struct's fields. Only the keyword form has the defaults. It calls the positional form, so the two forms run the same checks.
Validation
The constructor calls validate_bounds on the pair. The types of the pair decide which of the checks below run.
- A vector bound must not be empty,
IsEmptyErrorotherwise. - Two vector bounds must have the same length,
DimensionMismatchotherwise. lbmust not be aboveub, entry by entry if both are vectors,DomainErrorotherwise.- If one side is
nothing, the constructor does not compare the two sides. It checks only that a vector on the other side is not empty. - If both sides are
nothing, the constructor checks nothing. - Two infinite scalar bounds of the same sign pass, because
lb <= ubholds. The constructor acceptsWeightBounds(; lb = Inf, ub = Inf)andWeightBounds(; lb = -Inf, ub = -Inf), and no weight satisfies either pair.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
lb: Sliced to the selected indices throughport_opt_view.ub: Sliced to the selected indices throughport_opt_view.
weight_bounds_constraints can expand a field to a constant range. port_opt_view slices that field like any other vector, and the slice is a view of the range.
Examples
julia> WeightBounds(0.0, 1.0)WeightBounds lb ┼ Float64: 0.0 ub ┴ Float64: 1.0julia> WeightBounds([0.0, 0.1], [0.8, 1.0])WeightBounds lb ┼ Vector{Float64}: [0.0, 0.1] ub ┴ Vector{Float64}: [0.8, 1.0]Related
w_neg_flagw_finite_flagset_weight_constraints!set_linear_weight_constraints!WeightBoundsEstimatorweight_bounds_constraintsvalidate_bounds: the seven methods that do the checks of this type.port_opt_view
PortfolioOptimisers.UniformValues — Type
struct UniformValues <: VectorAbstractEstimatorValueAlgorithmFills every entry of a value vector with 1/N, where N is the number of assets in the universe.
The value is the same in every slot. lb = UniformValues() floors every weight at the equal-weight level and ub = UniformValues() caps every weight there. Neither slot is a special case in estimator_to_val.
Mathematical definition
\[\begin{align} v_i &= \frac{1}{N}\,, \quad i = 1,\, \ldots,\, N\,. \end{align}\]
Where:
- $v_i$: Entry $i$ of the value vector.
- $N$: Number of assets.
The entries sum to one, so the vector is the equal-weight portfolio whenever the slot it fills is a set of weights.
Examples
julia> sets = UniverseSets(; dict = Dict("nx" => ["A", "B", "C"]));julia> PortfolioOptimisers.estimator_to_val(UniformValues(), sets)StepRangeLen(0.3333333333333333, 0.0, 3)Related
PortfolioOptimisers.AbstractWeightBoundsEstimator — Type
abstract type AbstractWeightBoundsEstimator <: AbstractConstraintEstimatorAbstract supertype for every estimator of weight bounds.
A subtype states the bounds of the weights in a form that needs the universe, and weight_bounds_constraints resolves it to a WeightBounds in each fit. The fit resolves it after it narrows the universe to the investable assets, so the bounds cover the assets of that fit alone. WeightBoundsEstimator reads only the names of the universe. ScoreWeightBounds also reads the returns of the fit.
Each subtype resolves against sets, so an optimiser that holds one in its wb field needs sets. Its constructor refuses sets = nothing with an IsNothingError.
Interfaces
To make a new estimator of weight bounds, subtype AbstractWeightBoundsEstimator, put its parameters in the fields of the struct, and implement the method below.
weight_bounds_constraints(wb::AbstractWeightBoundsEstimator, sets::UniverseSets; rd::Option{<:ReturnsResult} = nothing, N::Integer = 0, strict::Bool = false, datatype::DataType = Float64, kwargs...) -> WeightBounds: Resolve the bounds of theNassets ofsets.
Every optimiser that holds a wb field gives rd, the returns of the fit over the investable assets, in the order of the columns of sets. A subtype that reads no returns ignores rd. A subtype that reads the returns refuses rd = nothing with an IsNothingError. An Allocation Set of an OnlinePortfolioSelection takes only a WeightBoundsEstimator or a WeightBounds. The head resolves the set once for a block of rows, and a bound that reads the returns of the block reads rows after each Online Update. That breaks the Causal Pass.
Arguments
wb: The estimator.sets:UniverseSetsof the assets of the fit.rd: The returns of the fit, ornothingon a route with no returns.N: The number of assets. A zero states that the caller gives no count.strict: Whether a constraint that names an asset or a group thatsetsdoes not hold raises an error. When it isfalse, the constraint generator warns and skips the entry.datatype: Number type of the resolved bounds.
Returns
wb::WeightBounds: The resolved bounds, in the asset order ofsets.
Related
PortfolioOptimisers.WeightBoundsEstimator — Type
struct WeightBoundsEstimator{__T_lb, __T_ub, __T_dlb, __T_dub} <: AbstractWeightBoundsEstimatorResolves weight bounds written in asset or group names against a universe.
weight_bounds_constraints turns it into a WeightBounds. It maps every name to its indices in the universe, and it gives an asset with no name in the bound the value dlb or dub. A bound can also be a scalar, a vector, or an algorithmic rule such as UniformValues. If dlb is nothing, the resolution uses zero(datatype). If dub is nothing, it uses one(datatype).
Fields
lb: Lower bound.
ub: Upper bound.
dlb: Lower bound of an asset that a dictionary or a pair inlbdoes not name.nothingresolves tozero(datatype).
dub: Upper bound of an asset that a dictionary or a pair inubdoes not name.nothingresolves toone(datatype).
Constructors
WeightBoundsEstimator(; lb::Option{<:VectorEstValType} = 0.0, ub::Option{<:VectorEstValType} = 1.0, dlb::Option{<:Number} = nothing, dub::Option{<:Number} = nothing) -> WeightBoundsEstimatorKeywords correspond to the struct's fields.
Validation
- If
lborubis anAbstractDictor anAbstractVector, it must not be empty,IsEmptyErrorotherwise. - Two vector bounds must have the same length,
DimensionMismatchotherwise.validate_boundsdoes this check. - If both bounds are numbers or vectors of numbers,
lbmust not be aboveub,DomainErrorotherwise.validate_boundsdoes this check. - If one side is an
AbstractDict, aPairor an algorithmic rule, the constructor does not compare the two sides, because that side has no values yet.weight_bounds_constraintsbuilds aWeightBoundsfrom the resolved pair, and that constructor compares them. - If neither
dlbnordubisnothing,dlb <= dubmust hold,DomainErrorotherwise.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
lb: Sliced to the selected indices throughport_opt_view.ub: Sliced to the selected indices throughport_opt_view.
port_opt_view slices only a vector bound. A scalar, a Dict, a Pair or an algorithmic rule has no index by asset. The view keeps such a bound unchanged, and the bound resolves against the universe of the view when the estimator runs.
Examples
julia> WeightBoundsEstimator(; lb = Dict("A" => 0.1, "B" => 0.2), ub = Dict("A" => 0.8, "B" => 0.9))WeightBoundsEstimator lb ┼ Dict{String, Float64}: Dict("B" => 0.2, "A" => 0.1) ub ┼ Dict{String, Float64}: Dict("B" => 0.9, "A" => 0.8) dlb ┼ nothing dub ┴ nothingjulia> WeightBoundsEstimator(; lb = UniformValues(), ub = nothing)WeightBoundsEstimator lb ┼ UniformValues() ub ┼ nothing dlb ┼ nothing dub ┴ nothingRelated
WeightBoundsweight_bounds_constraintsvalidate_bounds: the checks that this constructor runs on a pair of numbers or a pair of vectors.port_opt_view
PortfolioOptimisers.weight_bounds_constraints — Function
weight_bounds_constraints(wb::WeightBoundsEstimator, sets::UniverseSets; strict::Bool = false,
datatype::DataType = Float64, kwargs...)Resolve a WeightBoundsEstimator against a universe.
weight_bounds_constraints builds the WeightBounds of the assets in sets from the bounds that wb states. A bound can be a scalar, a vector, a dictionary, a pair, or an algorithmic rule. So one estimator can state one bound for the whole universe and a different bound for each named asset. A nothing bound states no bound on that side, and the resolution keeps it as nothing.
Algorithm
- Resolve the lower side with
estimator_to_val. The result islb. An asset that the estimator does not name getswb.dlb, orzero(datatype)ifwb.dlbisnothing. - Resolve the upper side the same way. The result is
ub. An asset that the estimator does not name getswb.dub, orone(datatype)ifwb.dubisnothing. - Build
WeightBounds(; lb = lb, ub = ub). That constructor runsvalidate_boundson the resolved pair. This is the first comparison of anAbstractDictbound on one side with a scalar on the other.
Arguments
wb:WeightBoundsEstimatorthat states the lower and upper bounds.sets:UniverseSetsthat holds the asset names and the groups.strict: Whether a constraint that names an asset or a group thatsetsdoes not hold raises an error. When it isfalse, the constraint generator warns and skips the entry.datatype: Number type of the resolved bounds, and of the fill valueszero(datatype)andone(datatype).kwargs: More keyword arguments, which the method ignores.
Validation
- The resolved pair must pass
validate_bounds, which theWeightBoundsconstructor of step 3 runs. A resolvedlbabove a resolvedubraisesDomainErrorthere.estimator_to_valraisesDimensionMismatchfor a vector bound of the wrong length.
Returns
wb::WeightBounds: The resolved bounds, in the asset order ofsets.
Examples
julia> sets = UniverseSets(; dict = Dict("nx" => ["A", "B", "C"]));julia> wb = WeightBoundsEstimator(; lb = Dict("A" => 0.1, "B" => 0.2), ub = 1.0);julia> weight_bounds_constraints(wb, sets)WeightBounds lb ┼ Vector{Float64}: [0.1, 0.2, 0.0] ub ┴ Float64: 1.0julia> wb = WeightBoundsEstimator(; lb = Dict("A" => 0.1), ub = Dict("A" => 0.5), dlb = 0.02, dub = 0.7);julia> weight_bounds_constraints(wb, sets)WeightBounds lb ┼ Vector{Float64}: [0.1, 0.02, 0.02] ub ┴ Vector{Float64}: [0.5, 0.7, 0.7]Related
weight_bounds_constraints(wb::WeightBounds{<:Any, <:Any}, args...; N::Integer = 0,
datatype::DataType = Float64, kwargs...)Expand each side of a WeightBounds to N bounds.
weight_bounds_constraints_side expands a scalar or a nothing bound to a vector or range of length N, so the model gets one bound per asset. A vector bound stays unchanged, and its length must equal N.
The caller must give N. With the default N = 0, every scalar or nothing side expands to an empty vector, and the WeightBounds constructor raises IsEmptyError.
Algorithm
- Expand the lower side with
weight_bounds_constraints_side(wb.lb, N, -Inf). The result islb. The free bound-Infhas the typedatatype, so a side with no bound takes the number type of the data, notFloat64. - Expand the upper side with
weight_bounds_constraints_side(wb.ub, N, Inf). The result isub, and its free boundInfhas the typedatatype. - Build
WeightBounds(; lb = lb, ub = ub). Its constructor checks the expanded pair.
Arguments
wb:WeightBoundsto expand.args: More positional arguments, which the method ignores.N: Number of assets, which is the length of each expanded side.datatype: Number type of the free bound that anothingside expands to.kwargs: More keyword arguments, which the method ignores.
Validation
- A vector bound must have length
N,DimensionMismatchotherwise.weight_bounds_constraints_sidedoes this check. - The expanded pair must pass
validate_bounds, which theWeightBoundsconstructor of step 3 runs. With the defaultN = 0, every scalar ornothingside expands to an empty vector, and that constructor raisesIsEmptyError.
Returns
wb::WeightBounds: The expanded bounds.
Examples
julia> weight_bounds_constraints(WeightBounds(0.0, 1.0); N = 3)WeightBounds lb ┼ StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}: StepRangeLen(0.0, 0.0, 3) ub ┴ StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}: StepRangeLen(1.0, 0.0, 3)julia> weight_bounds_constraints(WeightBounds([0.1, 0.2, 0.3], 1.0); N = 3)WeightBounds lb ┼ Vector{Float64}: [0.1, 0.2, 0.3] ub ┴ StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}: StepRangeLen(1.0, 0.0, 3)Related
weight_bounds_constraints(wb::WeightBounds{<:VecNum, <:VecNum}, args...; N::Integer = 0,
kwargs...)Return a WeightBounds with two vector sides unchanged, after a check of its length.
Both sides of wb already hold one bound per asset, so weight_bounds_constraints returns the WeightBounds unchanged. If the caller gives an asset count N, the method first checks the length of wb.lb against it.
Algorithm
- If
Nis not zero, checklength(wb.lb) == N. The constructor ofwbalready checked that the two sides have the same length. - Return
wb.
Arguments
wb:WeightBoundswith a vector on each side.args: More positional arguments, which the method ignores.N: Number of assets. A zero states that the caller knows no asset count, and the method then does not check the length.kwargs: More keyword arguments, which the method ignores.
Validation
iszero(N) || length(wb.lb) == N,DimensionMismatchotherwise.
Returns
wb::WeightBounds: The input bounds, unchanged.
Examples
julia> weight_bounds_constraints(WeightBounds([0.1, 0.2, 0.3], [0.8, 0.9, 1.0]))WeightBounds lb ┼ Vector{Float64}: [0.1, 0.2, 0.3] ub ┴ Vector{Float64}: [0.8, 0.9, 1.0]Related
weight_bounds_constraints(wb::Nothing, args...; N::Integer = 0,
datatype::DataType = Float64, kwargs...)Make free weight bounds for N assets.
weight_bounds_constraints returns a WeightBounds with -Inf in every entry of the lower side and Inf in every entry of the upper side. The caller must give N. With the default N = 0, both sides are empty, and the WeightBounds constructor raises IsEmptyError: lb cannot be empty.
Algorithm
- Fill the lower side with
-Infand the upper side withInf, each to lengthN. Both free bounds have the typedatatype, so they take the number type of the data, notFloat64. - Build
WeightBounds(; lb = lb, ub = ub). Its constructor checks the pair.
Arguments
wb::Nothing: No weight bounds.args: More positional arguments, which the method ignores.N::Integer: Number of assets, which is the length of each side.datatype: Number type of the two free bounds.kwargs: More keyword arguments, which the method ignores.
Validation
- The pair must pass
validate_bounds, which theWeightBoundsconstructor of step 2 runs. With the defaultN = 0, both sides are empty, and that constructor raisesIsEmptyError.
Returns
wb::WeightBounds: Free lower and upper bounds.
Examples
julia> weight_bounds_constraints(nothing; N = 3)WeightBounds lb ┼ Vector{Float64}: [-Inf, -Inf, -Inf] ub ┴ Vector{Float64}: [Inf, Inf, Inf]Related
weight_bounds_constraints(wb::ScoreWeightBounds, sets::Option{<:UniverseSets};
rd::Option{<:ReturnsResult} = nothing, N::Integer = 0,
strict::Bool = false, datatype::DataType = Float64, kwargs...)Resolve a ScoreWeightBounds on the returns of a fit.
Algorithm
- Score the assets of
rdwithasset_scores, givings. A zeroNtakes the length ofs. - Resolve
wb.wbwithweight_bounds_constraintson the same arguments, then expand it toNentries on each side. - Resolve
wb.val, givingv. Withsets,estimator_to_valresolves it against the universe, and an asset thatwb.valdoes not name takeswb.dval, orone(datatype)whenwb.dvalisnothing. With no sets,wb.valnames no asset, so the number or the vector of numbers isv. - Compute the score bound of each asset with
score_cap, givingc. An asset whose score is not finite takeswb.nonfinite, or+Infwhenwb.nonfiniteisnothing. - Join the static bounds with
cthroughscore_bounds.
Arguments
wb: The estimator.sets:UniverseSetsof the assets of the fit, ornothingwhen the estimator is not keyed by name (name_keyed).rd: The returns of the fit, in the order of the assets ofsets.N: The number of assets. A zero takes the number of assets ofrd.strict: Whether a constraint that names an asset or a group thatsetsdoes not hold raises an error. When it isfalse, the constraint generator warns and skips the entry.datatype: Number type of the resolved bounds, and of the fill valueone(datatype).kwargs: More keyword arguments, which the method ignores.
Validation
rdis notnothing. AnIsNothingErroris thrown otherwise. The scores need the returns of the fit.setsis notnothingwhen the estimator is keyed by name (name_keyed). AnIsNothingErroris thrown otherwise.length(s) == N. ADimensionMismatchis thrown otherwise.- With no sets, a vector of numbers in
wb.valholdsNentries. ADimensionMismatchis thrown otherwise. - The checks of
score_bounds: no score bound is negative, no static lower bound is above its score bound, and, whenwb.symmetricistrue, no static upper bound is below the negative of its score bound. ADomainErroris thrown otherwise.
Returns
wb::WeightBounds: The resolved bounds, one entry per asset on each side, in the asset order ofsets.
Examples
julia> pnl = asset_panel([NumericPanelInput(; name = "volume", vals = [1.0 0.5 0.25; 2.0 1.0 0.5; 0.5 0.25 NaN], alg = ForwardPanelFill())]; amsk = trues(3, 3), emsk = trues(3, 3));julia> rd = ReturnsResult(; nx = ["A", "B", "C"], X = zeros(3, 3), pnl = pnl);julia> sets = UniverseSets(; dict = Dict("nx" => ["A", "B", "C"]));julia> wb = ScoreWeightBounds(; score = PanelFieldScorer(; fields = "volume", min_obs = 3), val = 0.5);julia> weight_bounds_constraints(wb, sets; rd = rd)WeightBounds lb ┼ Vector{Float64}: [0.0, 0.0, 0.0] ub ┴ Vector{Float64}: [0.5, 0.25, 0.0]The third volume of C is a fill and not a trade, so C holds two volumes, fewer than min_obs, and has no score. The default nonfinite = 0 then admits no position in C.
Related