Greedy finite allocation

PortfolioOptimisers.GreedyAllocationResult — Type
struct GreedyAllocationResult{__T_retcode, __T_shares, __T_cost, __T_w, __T_cash, __T_fees, __T_fb} <: FiniteAllocationOptimisationResult

Result type for GreedyAllocation.

shares, cost and w carry the sign of the position. A short position has a negative share count, a negative cost and a negative weight. fees is the charge that the two sides paid over the whole horizon, and the short side's part of it is not negated. cash is the cash that the account holds after both sides trade, as the collateral algorithm of the input states it. It includes the cash that no side received, and it is negative when the book borrows. Under the default ProceedsCollateral, sum(cost) + cash + fees is the cash of the input.

Fields

  • retcode: Optimisation return code.
  • shares: Number of shares allocated per asset.
  • cost: Cost of the allocation.
  • w: Realised portfolio weights.
  • cash: Remaining uninvested cash after allocation, from the third method of the collateral algorithm of the input. It includes the cash that no side received, and it is negative when the book borrows.
  • fees: Fee the allocation paid over the whole horizon. It is the sum of the two sides' charges, and it is never signed.
  • fb: The fallback chain that answered this result: the (estimator, result) pair of every attempt optimise made before this one, in the order they ran, or nothing when the estimator it was asked of answered (see FbChain).

Constructors

GreedyAllocationResult(;    retcode::OptimisationReturnCode,    shares::VecNum,    cost::VecNum,    w::VecNum,    cash::Number,    fees::Number,    fb::Option{<:FOptE_FOpt_FbChain}) -> GreedyAllocationResult

Keywords correspond to the struct's fields.

Related

References

  • [247] R. A. Martin. PyPortfolioOpt: portfolio optimization in Python. Journal of Open Source Software 6, 3066 (2021). Methods, page 3. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
source
PortfolioOptimisers.GreedyAllocation — Type
struct GreedyAllocation{__T_unit, __T_sets, __T_strict, __T_fb} <: FiniteAllocationOptimisationEstimator

Greedy Allocation portfolio optimiser.

GreedyAllocation converts continuous portfolio weights to discrete share quantities with a greedy allocation in two passes. [247] states only that the package it describes converts optimal weights into a discrete allocation, in its Methods on page 3. It does not state the passes. The first pass buys each asset up to its target weight in whole lots, in descending order of target weight. The second pass spends the leftover cash, one lot at a time, on the asset whose realised weight is furthest below its target.

unit states the lot unit of each asset, so the share count of an asset is a whole number of lots times its lot unit. The default LotUnit(1) buys whole shares. A lot unit below one buys fractional shares, and a lot unit above one buys board lots. A LotUnitEstimator resolves the lot unit against sets.

optimise allocates the long and the short side of a portfolio as two separate sub-problems. Each sub-problem receives its own share of the cash, and renormalises its own weights to sum to one. The definition below describes one sub-problem, so its targets $\boldsymbol{w}$ satisfy $\sum_i w_i = 1$. A side whose target weights are all zero buys nothing. optimise negates the short side's shares when it recombines the two sides.

Mathematical definition

Order the assets so that $w_1 \geq w_2 \geq \ldots \geq w_N$. The first pass goes through that order and buys

\[\begin{align} x_i &= l_i \left\lfloor \frac{w_i C}{p_i l_i} \right\rfloor\,, \\ r &\leftarrow r - x_i p_i - \Delta F_i\,, \end{align}\]

starting from $r = C - F(\boldsymbol{0})$. The pass stops at the first asset it cannot afford. Every later asset in the order then holds zero shares until the second pass.

The second pass repeats, while $r > 0$,

\[\begin{align} \boldsymbol{d} &= \boldsymbol{w} - \frac{\boldsymbol{x} \odot \boldsymbol{p}}{\sum_{j=1}^{N} x_j p_j}\,, \\ i^* &= \underset{i:\, p_i l_i + \Delta F_i \leq r}{\arg\max}\; d_i\,, \\ x_{i^*} &\leftarrow x_{i^*} + l_{i^*}\,, \\ r &\leftarrow r - p_{i^*} l_{i^*} - \Delta F_{i^*}\,. \end{align}\]

While the book holds no shares, $\sum_j x_j p_j = 0$ and the realised weight of every asset is zero, so $\boldsymbol{d} = \boldsymbol{w}$. The pass stops when no affordable asset has a positive deficit. It selects by deficit, not by target weight. An asset that the first pass filled has a small deficit, whatever its target weight is. An asset with a zero target weight never has a positive deficit, so neither pass buys it.

Where:

  • $\boldsymbol{x}$: Share allocation vector.
  • $r$: Cash not yet spent.
  • $\boldsymbol{w}$: Target weight vector of this sub-problem, renormalised to sum to one.
  • $C$: Cash allocated to this sub-problem.
  • $\boldsymbol{p}$: Asset price vector.
  • $\boldsymbol{l}$: Lot unit of each asset of one side of a finite allocation, the number of shares in one lot. A scalar applies to every asset.
  • $\boldsymbol{d}$: Weight deficit, the target weight less the realised weight.
  • $F(\boldsymbol{x})$: Fee of this sub-problem, from allocation_fee. It is zero when the input states no fee, and it includes the constant forced exit of allocation_liquidation_fee when the universe lost an asset.
  • $\Delta F_i$: Amount that a purchase of the asset $i$ adds to the fee, from greedy_fee_delta.
  • $i^*$: Affordable asset with the largest weight deficit.
  • $\odot$: Element-wise (Hadamard) product.
  • $N$: Number of assets in this sub-problem.

The first pass floors the lot count, so it never buys more than the target of an asset. Both passes count whole lots and compute each share count as the lot count times the lot unit. So a share count is a multiple of its lot unit to within one rounding of a product, whatever the lot unit is.

Fields

  • unit: Lot unit of each asset, the number of shares that one purchase buys. A LotUnit states it, and a LotUnitEstimator resolves it against sets. A share count is a non-negative integer multiple of the lot unit of its asset. The default LotUnit(1) buys whole shares.
  • sets: Universe sets that a LotUnitEstimator in unit resolves against, or nothing. The universe must name the assets of the input in the order of w.
  • 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.
  • fb: Fallback result or estimator.

Constructors

GreedyAllocation(;    unit::LuE_Lu = LotUnit(),    sets::Option{<:UniverseSets} = nothing,    strict::Bool = false,    fb::Option{<:FOptE_FOpt} = nothing) -> GreedyAllocation

Keywords correspond to the struct's fields.

Validation

Examples

julia> GreedyAllocation()GreedyAllocation    unit ┼ LotUnit         │   val ┴ Int64: 1    sets ┼ nothing  strict ┼ Bool: false      fb ┴ nothing

Related

References

  • [247] R. A. Martin. PyPortfolioOpt: portfolio optimization in Python. Journal of Open Source Software 6, 3066 (2021). Methods, page 3. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
source
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
                                 AbstractResult, StatsBase.CovarianceEstimator}},
        args...; kwargs...) -> AbstractArray

Rebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.

factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.

factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.

The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.

Algorithm

The leaf method:

  1. Return a with no change, and drop args... and kwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.

The array method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... with no change.
  2. Collect the results into a new array of the shape of a, in the order of a, and return it.

A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.

The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.

Arguments

  • a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators or nothing, which it rebuilds one element at a time.
  • args...: Positional arguments. The leaf method ignores them, and the array method forwards them.
  • kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.

Returns

  • a: The input with no change, for the leaf method.
  • v::AbstractArray: The rebuilt elements, in an array of the shape of a, for the array method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source
factory(res::FiniteAllocationOptimisationResult, fb::Option{<:FOptE_FOpt_FbChain})

Rebuild a finite allocation result with a new fallback record fb.

Every finite allocation result has fb as its last field, as the continuous results do. optimise calls this method with the FbChain of the failed attempts when a fallback answered. A concrete result type can define its own method when a rebuild needs more than a new fb.

Algorithm

  1. Read every field of res, in order, into the tuple flds.
  2. Call the constructor of the type of res, without its type parameters, with every entry of flds except the last, and then fb.

Related

source
PortfolioOptimisers._optimise — Method
_optimise(ga::GreedyAllocation, fai::FiniteAllocationInput; kwargs...) -> GreedyAllocationResult

Run the Greedy Allocation portfolio optimisation.

optimise calls this method, once for an allocator with no fallback, and once for each step of the fallback chain otherwise.

Algorithm

  1. Read the target weights, the long and the short side, and the charge of each side with prepare_finite_allocation. It removes each Unpriced Asset from its side, and gives its target weight to the rule fai.upw.
  2. Resolve the lot unit of each asset with allocation_lot_unit. Each side views a vector lot unit with its own mask.
  3. Start every share count, cost and weight at zero, so an Unpriced Asset holds zero in each.
  4. Allocate the short side on its negated weights with finite_sub_allocation!, with the short cash that fai.ca gives.
  5. Compute the long side's cash with fai.ca, from the money of the shares that the short side sold and the fee that it paid. See AbstractCollateralAlgorithm.
  6. Allocate the long side with finite_sub_allocation!.
  7. Negate the short side's shares, costs and weights, and put the two sides into one vector per quantity, in the caller's asset order.
  8. Return the cash that the account holds after the trade as cash, from the third method of fai.ca, and the sum of the fees of the two sides as fees. The cash includes the cash that no side received, such as the weight of an Unpriced Asset under upw = nothing.

Arguments

  • ga: The greedy allocation optimiser to use.
  • fai: The FiniteAllocationInput that holds the target weights, the prices, the cash, the collateral algorithm, and the optional horizon and fees.
  • kwargs: Ignored.

Returns

  • res::GreedyAllocationResult: The realised allocation. retcode is always an OptimisationSuccess, because the greedy passes cannot fail.

Related

source

References

[247]
R. A. Martin. PyPortfolioOpt: portfolio optimization in Python. Journal of Open Source Software 6, 3066 (2021).