Base finite allocation: private API
PortfolioOptimisers.FiniteAllocationOptimisationResult — Type
abstract type FiniteAllocationOptimisationResult <: OptimisationResultAbstract supertype for the results of a finite allocation.
Every subtype has the fields shares, cost, w, cash and fees, and its last field is fb. The generic factory method rebuilds a subtype from its fields and replaces the last one alone, so a new subtype must keep fb last.
Related
PortfolioOptimisers.FOptE_FOpt — Type
const FOptE_FOpt = Union{FiniteAllocationOptimisationEstimator,
FiniteAllocationOptimisationResult}Alias for a finite allocation estimator or a finite allocation result.
It is the type of the fb field of a finite allocation estimator. The fallback is an estimator that optimise runs when the first one fails, or a precomputed result that optimise returns as it is.
Related
PortfolioOptimisers.FOptE_FOpt_FbChain — Type
const FOptE_FOpt_FbChain = Union{FOptE_FOpt, FbChain}Alias for the values that the fb field of a finite allocation result can hold.
optimise writes nothing when the estimator that the caller gave answered, and the FbChain of the failed attempts when a fallback answered. The alias also admits a FOptE_FOpt, so factory can put a fallback estimator or result in the field.
Related
PortfolioOptimisers.CollateralAlg_Func — Type
const CollateralAlg_Func = Union{AbstractCollateralAlgorithm, Function}Alias for a rule that gives each side of a finite allocation its cash: a rule of the family, or a plain function with the three methods of the family.
It is the bound of the ca field of FiniteAllocationInput. AbstractCollateralAlgorithm states the three methods.
Related
PortfolioOptimisers.UnpricedAlg_Func — Type
const UnpricedAlg_Func = Union{AbstractUnpricedWeightAlgorithm, Function}Alias for a rule that moves the target weight of an Unpriced Asset: a rule of the family, or a plain function with the signature of the family.
It is the bound of the upw field of FiniteAllocationInput, in the form Option{<:UnpricedAlg_Func}.
Related
PortfolioOptimisers.unpriced_side_weight — Function
unpriced_side_weight(w::VecNum, umsk::AbstractVector{Bool}, long::Bool)Find the priced assets of one side of a book, and the target weight of the Unpriced Assets of that side.
A zero weight is on the long side, as in setup_alloc_optim. The rules of AbstractUnpricedWeightAlgorithm call this method once for each side, so the weight of a side goes to assets of that side only.
Mathematical definition
\[d_\sigma = \sum_{i \in \mathcal{U} \cap \mathcal{S}_\sigma} w_i\,.\]
Where:
- $d_\sigma$: Target weight of the Unpriced Assets of the side $\sigma$. It is negative on the short side.
- $\mathcal{U}$: Set of the Unpriced Assets, where
umskistrue. - $\mathcal{S}_\sigma$: Set of the assets of the side, $w_i \geq 0$ for the long side and $w_i < 0$ for the short side.
- $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
Arguments
w::VecNum: Target portfolio weights over the full universe.umsk::AbstractVector{Bool}: Mask of the Unpriced Assets.long::Bool:truefor the long side.
Returns
r::BitVector: Mask of the priced assets of the side, $\mathcal{S}_\sigma \setminus \mathcal{U}$.d::Number: The weight $d_\sigma$.
Related
PortfolioOptimisers.allocation_horizon — Function
allocation_horizon(res::NonFiniteAllocationOptimisationResult,
horizon::Option{<:Number} = nothing)Read the horizon of a finite allocation from an optimisation result.
The horizon is the number of observations of the result's prior, which is the number of periods over which calc_total_fees charges the rates on the window that the fit saw. A stated horizon takes priority. The method reads the prior with hasproperty and not by dispatch, as extract_fees reads fees. The families that keep a prior keep it under the name pr, and a result that keeps none gives nothing. FiniteAllocationInput then needs a stated horizon, but only when the input also has a fee.
Algorithm
- If
horizonis notnothing, return it. - If
reshas aprproperty, andpris notnothingand has anXproperty, returnsize(pr.X, 1). - Otherwise return
nothing.
Arguments
res: Fitted optimisation result, which can have aprproperty.horizon: Horizon that the caller states, ornothing.
Returns
horizon::Option{<:Number}: The horizon in periods, ornothingwhen the method finds none.
Related
PortfolioOptimisers.setup_alloc_optim — Function
setup_alloc_optim(w::VecNum)Split a portfolio into its long and its short side.
Both finite allocators solve one sub-problem per side. A zero weight is on the long side. The method gives no side its cash. The ca of FiniteAllocationInput does that, through the first two methods of AbstractCollateralAlgorithm. The method charges no fee. Each sub-problem charges the fee of its own side on the money that it buys, through allocation_fee or set_allocation_fees!.
Mathematical definition
\[\begin{align} b_L &= \sum_{i:\, w_i \geq 0} w_i\,, \\ b_S &= -\sum_{i:\, w_i < 0} w_i\,. \end{align}\]
It follows that $b = b_L - b_S$.
Where:
- $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
- $N$: Number of assets.
- $b = \sum_{i=1}^{N} w_i$: Total budget of a finite allocation, the sum of the target weights.
- $b_L$: Long budget, the sum of the non-negative target weights.
- $b_S$: Short budget, the negated sum of the negative target weights. It is non-negative.
Algorithm
- Compute
lidx, the maskw .>= 0. - If every weight is non-negative, set
lbgtto the sum ofw, setsbgtto zero, and setsidxto an empty vector. - Otherwise set
sidx = .!lidx, and computelbgtandsbgtover the two masks.
Arguments
w::VecNum: Target portfolio weights over the full universe.
Returns
lbgt::Number: Long budget $b_L$.sbgt::Number: Short budget $b_S$, which is non-negative.lidx: Mask of the long side,w .>= 0.sidx: Mask of the short side. When every weight is non-negative, it is an empty vector of the element type ofw. Both forms select no asset in that case.
Related
PortfolioOptimisers.prepare_finite_allocation — Function
prepare_finite_allocation(fai::FiniteAllocationInput)Give the target weights, the two sides and the two charges that both finite allocators solve over.
Both allocators call this method first, so they read one definition of an Unpriced Asset, one rule for its weight, and one fee. A NaN price marks an Unpriced Asset, and the method removes each one from its side. So no sub-problem reads its price.
Algorithm
- Compute
umsk, the mask of theNaNprices. - If
umskmarks an asset, replacewwithunpriced_weightsoffai.upw. - Split
winto its two sides withsetup_alloc_optim. An Unpriced Asset now has a zero weight, so it is on the long side, and the method removes it fromlidx. - Split the fee into the charge of each side with
allocation_side_fees, which charges the Unpriced Assets as a constant of the long side.
Arguments
fai::FiniteAllocationInput: The input of the allocation.
Returns
w::VecNum: Target weights that the allocation buys, with a zero at every Unpriced Asset.lbgt::Number: Long budget ofw.sbgt::Number: Short budget ofw.lidx: Mask of the priced assets of the long side.sidx: Mask of the short side.lsf: The long side's charge, ornothing.ssf: The short side's charge, ornothing.
Related
PortfolioOptimisers.allocation_lot_unit — Function
allocation_lot_unit(unit::LuE_Lu, sets::Option{<:UniverseSets}, strict::Bool,
fai::FiniteAllocationInput)Give the lot unit of each asset of a finite allocation, on the axis of w.
Both allocators call this method before they solve a side, so they read one resolution of the lot unit and one check of its length. Each side then views a vector lot unit with its own mask from prepare_finite_allocation, as it views the prices. An Unpriced Asset is on no side, so no side reads its lot unit.
Algorithm
- Resolve
unitto aLotUnitwithlot_unit_constraintsagainstsets, withstrict. The number type of the fill value ispromote_type(eltype(fai.w), eltype(fai.prices)). - If the lot unit is a vector, check that it has one entry for each entry of
fai.w. - Return the
valof theLotUnit.
Arguments
unit::LuE_Lu: Theunitfield of the allocator, aLotUnitor aLotUnitEstimator.sets::Option{<:UniverseSets}: Thesetsfield of the allocator. The constructor of the allocator refusesnothingwhenunitis aLotUnitEstimator.strict::Bool: Thestrictfield of the allocator.fai::FiniteAllocationInput: The input of the allocation.
Validation
- A vector lot unit has
length(fai.w)entries, else aDimensionMismatch.
Returns
lu::Num_VecNum: The lot unit, one scalar for every asset or one value for each asset in the order ofw.
Related
PortfolioOptimisers.allocation_turnover_money — Function
allocation_turnover_money(::Nothing, ::Number, ::Any, ::Bool)
allocation_turnover_money(tn::Turnover, prev_cash::Number, idx, short::Bool)Give one side its turnover rate and the money that each of its positions held before the trade.
The allocator solves the short side on its negated weights, so the method negates the short side's previous money too. A position that is on the same side before and after the trade has a non-negative previous money. A position that changes side has a negative one, and the turnover term $|\boldsymbol{m} - \boldsymbol{m}^{\text{prev}}|$ of allocation_fee is then the money that closes the old position plus the money of the new one. A nothing tn gives nothing for both values.
Mathematical definition
\[\boldsymbol{m}^{\text{prev}} = s\, C^{\text{prev}}\, \boldsymbol{w}^{\text{prev}}\,.\]
Where:
- $\boldsymbol{m}^{\text{prev}}$: Previous money vector, the money in each position of one side before the trade.
- $s$: Sign of the side, $1$ for the long side and $-1$ for the short side.
- $C^{\text{prev}}$: Previous cash, the cash that the portfolio held before the trade, the
prev_cashofFiniteAllocationInput. - $\boldsymbol{w}^{\text{prev}}$: Previous weights of the assets of this side,
tn.wviewed toidx.
Arguments
tn: Turnover of the fee, ornothingwhen the fee has none.prev_cash::Number: Cash that the portfolio held before the trade.idx: Mask of this side.short::Bool:truefor the short side.
Returns
val: Turnover rate of this side, ornothing.prev_money: Previous money $\boldsymbol{m}^{\text{prev}}$ of this side, ornothing.
Related
PortfolioOptimisers.allocation_liquidation_fee — Function
allocation_liquidation_fee(::Nothing, ::Number, ::Number)
allocation_liquidation_fee(fees::Fees, T::Number, prev_cash::Number)Charge the forced exit of every asset that left the universe, as one constant.
A Fees has two liquidation charges, lq and flq. lq is a rate and flq is an amount of money, and the w of each holds the previous weights of the positions that the optimisation had to sell. The allocator solves no share count for these assets, so the charge needs no variable and is a constant of the sub-problem. set_liquidation_fees! and set_fixed_liquidation_fees! add the same charge to the JuMP model as a constant.
The long sub-problem pays the whole charge. Every asset that left has a zero target weight, and setup_alloc_optim puts a zero weight on the long side. The total fee does not depend on the side that pays, but that side has less cash for shares, and a long-only book has no other side.
Mathematical definition
\[L = T\, C^{\text{prev}} \left\lvert \boldsymbol{w}_{\text{lq}} \right\rvert \cdot \boldsymbol{f}_{\text{lq}} + 1\left\{\boldsymbol{w}_{\text{flq}} \neq 0\right\} \cdot \boldsymbol{f}_{\text{flq}}\,.\]
This is $T F_{\text{lq}} + F_{\text{flq}}$ of Fees, with the rate term in money.
Where:
- $L$: Forced-exit charge, the constant fee over the whole horizon for the assets that left the universe.
- $T$: Allocation horizon, the number of periods over which a finite allocation charges its rates, the
horizonofFiniteAllocationInput. - $C^{\text{prev}}$: Previous cash, the cash that the portfolio held before the trade, the
prev_cashofFiniteAllocationInput. - $\boldsymbol{w}_{\text{lq}}$, $\boldsymbol{w}_{\text{flq}}$: Previous weights of the assets that left,
lq.wandflq.w. - $\boldsymbol{f}_{\text{lq}}$: Liquidation rate per period,
lq.val. A scalar applies to every asset. - $\boldsymbol{f}_{\text{flq}}$: Fixed liquidation amount per position,
flq.val. A scalar applies to every asset. - $1\left\{\cdot\right\}$: Elementwise indicator,
1where the condition holds and0elsewhere. $\boldsymbol{w}_{\text{flq}} \neq 0$ is!isapprox(w, 0; kwargs...)with thekwargsof the fee.
Algorithm
- If
feesisnothing, return zero, because no asset left the universe. - Set
feeto zero. - If
lqis notnothing, addTtimes the contraction oflq.valwithabs.(prev_cash * lq.w). - If
flqis notnothing, addcalc_fixed_liquidation_feesofflq, which charges the long and the short positions that left. - Return
fee.
Arguments
fees: Fee with the two liquidation charges,lqandflq, ornothing.T::Number: Horizon, in periods.prev_cash::Number: Cash that the portfolio held before the trade.
Returns
fee::Number: The forced-exit charge $L$ over the whole horizon.
Related
PortfolioOptimisers.SideFees — Type
struct SideFees{__T_T, __T_prop, __T_fixed, __T_tn_val, __T_prev_money, __T_liq}The charge of one side of a finite allocation: the horizon, the proportional and the fixed rates of the side, the turnover rate with the money held before the trade, and the forced exit.
This type is an implementation detail and is not intended for direct use. allocation_side_fees makes it, and permute_side_fees reorders it. allocation_fee reads it.
Fields
T:T: The horizon, in periods.
prop:prop: The proportional rate per period of the side,lon the long side andson the short side, ornothing. A scalar applies to every asset.
fixed:fixed: The fixed amount per position of the side,flon the long side andfson the short side, ornothing.
tn_val:tn_val: The turnover rate per period, ornothing.
prev_money:prev_money: The money that the side held before the trade, per asset, ornothing.
liq:liq: The forced-exit charge, a constant of the whole allocation. It is zero on the short side.
Related
PortfolioOptimisers.allocation_side_fees — Function
allocation_side_fees(::Nothing, ::Option{<:Number}, ::Number, ::Any, ::Any, ::Any)
allocation_side_fees(fees::Fees, T::Number, prev_cash::Number, lidx, sidx, umsk)Split a fee into the charge of the long side and the charge of the short side.
Each sub-problem charges its own side. The long side takes l and fl, the short side takes s and fs, and both take the turnover rate and their previous money from allocation_turnover_money. nothing_scalar_array_view views a vector rate to the side and passes a scalar rate through. A nothing fees gives nothing for both charges.
lidx and sidx are masks of the full universe, because they come from weights that an optimisation expanded back to it. A fee that the same optimisation reduced to its Investable Mask is on a shorter axis and records the mask in imsk, so the method lifts it with lift_fees before it takes a view. lift_fees returns a fee that has no mask unchanged.
The forced exit of allocation_liquidation_fee is a constant of the whole allocation. It is the liq entry of the long side's charge, and the short side's liq is zero, so both charges have the same entries.
An Unpriced Asset is on neither side, because no sub-problem can buy it. It ends the trade with no money, so its fee is a constant too, and the long side's liq adds it. The method charges it with allocation_fee on zero money, so it is the turnover term alone, $T \left\lvert \boldsymbol{m}^{\text{prev}} \right\rvert \cdot \boldsymbol{f}_{\text{Tn}}$ over the Unpriced Assets. The proportional and the fixed term of zero money are zero.
Algorithm
- Lift
feesonto the full universe withlift_fees. - Compute
ltn_valandlprevfor the long side, andstn_valandsprevfor the short side, withallocation_turnover_money. - Compute
liq, the forced-exit charge, withallocation_liquidation_fee. - Add to
liqtheallocation_feeof zero money in the Unpriced Assets, with their turnover rate and previous money fromallocation_turnover_money. - Return the long side's charge, from
l,fl,ltn_val,lprevandliq, and the short side's charge, froms,fs,stn_val,sprevand a zeroliq.
Arguments
fees: Fee to split, ornothing.T: Horizon, in periods.prev_cash::Number: Cash that the portfolio held before the trade.lidx: Mask of the long side. It holds no Unpriced Asset.sidx: Mask of the short side. It holds no Unpriced Asset.umsk: Mask of the Unpriced Assets.
Returns
lsf: The long side's charge, ornothing.ssf: The short side's charge, ornothing.
Each charge is a SideFees.
Related
PortfolioOptimisers.permute_side_fees — Function
permute_side_fees(::Nothing, ::Any)
permute_side_fees(sf::SideFees, idx)Put one side's charge in the order that idx gives.
finite_sub_allocation! sorts its assets by descending target weight, so the rates and the previous money must take the same order. nothing_scalar_array_view views a vector entry to idx and passes a scalar entry through. T and liq are constants of the side, so they do not change. The fee does not change either. allocation_fee of the permuted charge, prices and shares is equal to the fee in the first order.
Arguments
sf: One side's charge, fromallocation_side_fees, ornothing.idx: The new order.
Returns
sf: The charge in the order ofidx, ornothing.
Related
PortfolioOptimisers.allocation_fee — Function
allocation_fee(::Nothing, ::VecNum, shares::VecNum)
allocation_fee(sf::SideFees, p::VecNum, shares::VecNum)Charge the whole fee of one side on a vector of share counts.
The method charges every term on the money in each position, which is exact for share counts. Both allocators report this number. A nothing sf charges zero.
A side that held money before the trade owes a turnover fee when it buys nothing, because a sale to zero is a trade. A book whose universe lost an asset owes the forced exit whatever it buys. For these reasons, both allocators charge this method on the empty book too. On the long side, $L$ also holds the turnover fee of the Unpriced Assets, which allocation_side_fees charges on zero money.
Mathematical definition
\[F(\boldsymbol{x}) = L + T \left(\boldsymbol{m} \cdot \boldsymbol{f}_{\text{p}} + \left\lvert \boldsymbol{m} - \boldsymbol{m}^{\text{prev}} \right\rvert \cdot \boldsymbol{f}_{\text{Tn}}\right) + 1\left\{\boldsymbol{m} \neq 0\right\} \cdot \boldsymbol{f}_{\text{f}}\,.\]
The sum of the two sides is the fee of Fees on the weights of the book. Sign the money of the short side negative, and set $\boldsymbol{w} = \boldsymbol{m} / C^{\text{prev}}$. The sum is then $C^{\text{prev}}\, T F_{\text{r}}(\boldsymbol{w}) + F_{\text{o}}(\boldsymbol{w})$, which calc_periodic_fees and calc_one_off_fees compute.
Where:
- $F(\boldsymbol{x})$: Side fee, the fee that one side pays over the whole horizon. It is zero when the input states no fee.
- $\boldsymbol{x}$: Share count vector of one side,
shares. - $\boldsymbol{p}$: Asset price vector of one side of a finite allocation.
- $\boldsymbol{m} = \boldsymbol{x} \odot \boldsymbol{p}$: Position money vector, the money in each position of one side.
- $\boldsymbol{m}^{\text{prev}}$: Previous money vector, the money in each position of one side before the trade.
- $L$: Forced-exit charge, the constant fee over the whole horizon for the assets that left the universe.
- $T$: Allocation horizon, the number of periods over which a finite allocation charges its rates, the
horizonofFiniteAllocationInput. - $\boldsymbol{f}_{\text{p}}$: Proportional rate per period of the side,
lon the long side andson the short side. - $\boldsymbol{f}_{\text{Tn}}$: Turnover rate per period,
tn.val. - $\boldsymbol{f}_{\text{f}}$: Fixed amount per position of the side,
flon the long side andfson the short side. - $1\left\{\cdot\right\}$: Elementwise indicator,
1where the condition holds and0elsewhere. - $C^{\text{prev}}$: Previous cash, the cash that the portfolio held before the trade, the
prev_cashofFiniteAllocationInput. - $F_{\text{r}}$, $F_{\text{o}}$: Fee per period and one-off fee of
Fees. - $\boldsymbol{w}$: Signed weights of the book on the previous cash.
A scalar rate applies to every asset.
Algorithm
- Compute
money = shares .* p. - Set
feetosf.liq. - If
propis notnothing, addTtimes its contraction withmoney. - If
tn_valis notnothing, addTtimes its contraction withabs.(money - prev_money). - If
fixedis notnothing, add its contraction with the indicator.!iszero.(money). - Return
fee.
Arguments
sf: One side's charge, fromallocation_side_fees, ornothing.p::VecNum: Asset prices of this side.shares::VecNum: Share count per asset.
Returns
fee::Number: The fee of this side over the whole horizon.
Related