Weight bounds constraint generation

PortfolioOptimisers.WeightBounds — Type
struct WeightBounds{__T_lb, __T_ub} <: AbstractConstraintResult

Holds 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) -> WeightBounds

Keywords 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, IsEmptyError otherwise.
  • Two vector bounds must have the same length, DimensionMismatch otherwise.
  • lb must not be above ub, entry by entry if both are vectors, DomainError otherwise.
  • 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 <= ub holds. The constructor accepts WeightBounds(; lb = Inf, ub = Inf) and WeightBounds(; 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:

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

source
PortfolioOptimisers.UniformValues — Type
struct UniformValues <: VectorAbstractEstimatorValueAlgorithm

Fills 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

source
PortfolioOptimisers.AbstractWeightBoundsEstimator — Type
abstract type AbstractWeightBoundsEstimator <: AbstractConstraintEstimator

Abstract 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 the N assets of sets.

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: UniverseSets of the assets of the fit.
  • rd: The returns of the fit, or nothing on 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 that sets does not hold raises an error. When it is false, 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 of sets.

Related

source
PortfolioOptimisers.WeightBoundsEstimator — Type
struct WeightBoundsEstimator{__T_lb, __T_ub, __T_dlb, __T_dub} <: AbstractWeightBoundsEstimator

Resolves 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 in lb does not name. nothing resolves to zero(datatype).
  • dub: Upper bound of an asset that a dictionary or a pair in ub does not name. nothing resolves to one(datatype).

Constructors

WeightBoundsEstimator(;    lb::Option{<:VectorEstValType} = 0.0,    ub::Option{<:VectorEstValType} = 1.0,    dlb::Option{<:Number} = nothing,    dub::Option{<:Number} = nothing) -> WeightBoundsEstimator

Keywords correspond to the struct's fields.

Validation

  • If lb or ub is an AbstractDict or an AbstractVector, it must not be empty, IsEmptyError otherwise.
  • Two vector bounds must have the same length, DimensionMismatch otherwise. validate_bounds does this check.
  • If both bounds are numbers or vectors of numbers, lb must not be above ub, DomainError otherwise. validate_bounds does this check.
  • If one side is an AbstractDict, a Pair or an algorithmic rule, the constructor does not compare the two sides, because that side has no values yet. weight_bounds_constraints builds a WeightBounds from the resolved pair, and that constructor compares them.
  • If neither dlb nor dub is nothing, dlb <= dub must hold, DomainError otherwise.

View parameters

port_opt_view takes the view of these @vprop fields at the selected indices:

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 ┴ nothing

Related

source
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

  1. Resolve the lower side with estimator_to_val. The result is lb. An asset that the estimator does not name gets wb.dlb, or zero(datatype) if wb.dlb is nothing.
  2. Resolve the upper side the same way. The result is ub. An asset that the estimator does not name gets wb.dub, or one(datatype) if wb.dub is nothing.
  3. Build WeightBounds(; lb = lb, ub = ub). That constructor runs validate_bounds on the resolved pair. This is the first comparison of an AbstractDict bound on one side with a scalar on the other.

Arguments

  • wb: WeightBoundsEstimator that states the lower and upper bounds.
  • sets: UniverseSets that holds the asset names and the groups.
  • strict: Whether a constraint that names an asset or a group that sets does not hold raises an error. When it is false, the constraint generator warns and skips the entry.
  • datatype: Number type of the resolved bounds, and of the fill values zero(datatype) and one(datatype).
  • kwargs: More keyword arguments, which the method ignores.

Validation

  • The resolved pair must pass validate_bounds, which the WeightBounds constructor of step 3 runs. A resolved lb above a resolved ub raises DomainError there. estimator_to_val raises DimensionMismatch for a vector bound of the wrong length.

Returns

  • wb::WeightBounds: The resolved bounds, in the asset order of sets.

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

source
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

  1. Expand the lower side with weight_bounds_constraints_side(wb.lb, N, -Inf). The result is lb. The free bound -Inf has the type datatype, so a side with no bound takes the number type of the data, not Float64.
  2. Expand the upper side with weight_bounds_constraints_side(wb.ub, N, Inf). The result is ub, and its free bound Inf has the type datatype.
  3. Build WeightBounds(; lb = lb, ub = ub). Its constructor checks the expanded pair.

Arguments

  • wb: WeightBounds to 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 a nothing side expands to.
  • kwargs: More keyword arguments, which the method ignores.

Validation

  • A vector bound must have length N, DimensionMismatch otherwise. weight_bounds_constraints_side does this check.
  • The expanded pair must pass validate_bounds, which the WeightBounds constructor of step 3 runs. With the default N = 0, every scalar or nothing side expands to an empty vector, and that constructor raises IsEmptyError.

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

source
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

  1. If N is not zero, check length(wb.lb) == N. The constructor of wb already checked that the two sides have the same length.
  2. Return wb.

Arguments

  • wb: WeightBounds with 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, DimensionMismatch otherwise.

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

source
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

  1. Fill the lower side with -Inf and the upper side with Inf, each to length N. Both free bounds have the type datatype, so they take the number type of the data, not Float64.
  2. 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 the WeightBounds constructor of step 2 runs. With the default N = 0, both sides are empty, and that constructor raises IsEmptyError.

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

source
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

  1. Score the assets of rd with asset_scores, giving s. A zero N takes the length of s.
  2. Resolve wb.wb with weight_bounds_constraints on the same arguments, then expand it to N entries on each side.
  3. Resolve wb.val, giving v. With sets, estimator_to_val resolves it against the universe, and an asset that wb.val does not name takes wb.dval, or one(datatype) when wb.dval is nothing. With no sets, wb.val names no asset, so the number or the vector of numbers is v.
  4. Compute the score bound of each asset with score_cap, giving c. An asset whose score is not finite takes wb.nonfinite, or +Inf when wb.nonfinite is nothing.
  5. Join the static bounds with c through score_bounds.

Arguments

  • wb: The estimator.
  • sets: UniverseSets of the assets of the fit, or nothing when the estimator is not keyed by name (name_keyed).
  • rd: The returns of the fit, in the order of the assets of sets.
  • N: The number of assets. A zero takes the number of assets of rd.
  • strict: Whether a constraint that names an asset or a group that sets does not hold raises an error. When it is false, the constraint generator warns and skips the entry.
  • datatype: Number type of the resolved bounds, and of the fill value one(datatype).
  • kwargs: More keyword arguments, which the method ignores.

Validation

  • rd is not nothing. An IsNothingError is thrown otherwise. The scores need the returns of the fit.
  • sets is not nothing when the estimator is keyed by name (name_keyed). An IsNothingError is thrown otherwise.
  • length(s) == N. A DimensionMismatch is thrown otherwise.
  • With no sets, a vector of numbers in wb.val holds N entries. A DimensionMismatch is thrown otherwise.
  • The checks of score_bounds: no score bound is negative, no static lower bound is above its score bound, and, when wb.symmetric is true, no static upper bound is below the negative of its score bound. A DomainError is thrown otherwise.

Returns

  • wb::WeightBounds: The resolved bounds, one entry per asset on each side, in the asset order of sets.

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

source