Base finite allocation

A new finite allocation estimator subtypes FiniteAllocationOptimisationEstimator and adds the methods that its docstring states. A new collateral algorithm subtypes AbstractCollateralAlgorithm and adds the two call methods that its docstring states. A new rule for the target weight of an asset with no price on the allocation date subtypes AbstractUnpricedWeightAlgorithm and adds the call method that its docstring states.

PortfolioOptimisers.FiniteAllocationOptimisationEstimator — Type
abstract type FiniteAllocationOptimisationEstimator <: OptimisationEstimator

Abstract supertype for estimators that turn continuous portfolio weights into share counts.

A finite allocation estimator buys share counts with a stated cash budget at stated prices. The library has two. DiscreteAllocation solves a mixed-integer programme, and GreedyAllocation buys in two greedy passes. [247] states only that the package it describes converts optimal weights into a discrete allocation, in its Methods on page 3. It states neither algorithm. optimise takes either one with a FiniteAllocationInput as its second argument, and allocates the long and the short side of the portfolio as two separate sub-problems.

Interfaces

To implement a new finite allocation estimator, subtype FiniteAllocationOptimisationEstimator, give it an fb field, and implement the two methods below. The fb field holds a FOptE_FOpt or nothing.

_optimise

  • _optimise(fa::MyAllocation, fai::FiniteAllocationInput; kwargs...) -> FiniteAllocationOptimisationResult: Buys share counts for the weights and the prices in fai, and returns a result type that subtypes FiniteAllocationOptimisationResult.

Arguments

  • fa: An instance of the concrete subtype.
  • fai: The FiniteAllocationInput that holds the weights, the prices, the cash and the fees.
  • kwargs...: The keyword arguments that optimise forwards.

Returns

  • res::FiniteAllocationOptimisationResult: The realised allocation. Its last field is fb.

optimise

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.AbstractCollateralAlgorithm — Type
abstract type AbstractCollateralAlgorithm <: AbstractAlgorithm

Abstract supertype for the rules that give each side of a finite allocation its cash.

A finite allocation solves the short side first and the long side second. A collateral algorithm states how much cash the short side can spend, and how much cash the long side can spend after the short side trades. It also states how much cash the account holds after both sides trade, because only the rule knows if a short sale gives cash. FiniteAllocationInput holds one in its ca field, so every allocator of a fallback chain reads the same rule.

All concrete subtypes must subtype AbstractCollateralAlgorithm.

Interfaces

To implement a new collateral algorithm, subtype AbstractCollateralAlgorithm and make it callable with these three methods:

  • (ca::MyCollateral)(w::VecNum, prices::VecNum, cash::Number) -> Number: Returns the cash of the short side, before it trades.
  • (ca::MyCollateral)(w::VecNum, prices::VecNum, cash::Number, smoney::Number, sfee::Number) -> Number: Returns the cash of the long side, after the short side trades.
  • (ca::MyCollateral)(w::VecNum, prices::VecNum, cash::Number, smoney::Number, sfee::Number, lmoney::Number, lfee::Number) -> Number: Returns the cash that the account holds uninvested after both sides trade. The allocators report it as the cash of their result. It includes the cash that no side received, such as the cash outside a budget below one, or the weight of an Unpriced Asset under upw = nothing.

Where:

  • w: Target portfolio weights over the full universe. A negative weight is on the short side.
  • prices: Asset prices, in the order of w. A NaN price marks an Unpriced Asset, and its weight in w is zero.
  • cash: Cash of the allocation, the cash of FiniteAllocationInput.
  • smoney: Money of the shares that the short side sold, a non-negative number.
  • sfee: Fee that the short side paid over the whole horizon.
  • lmoney: Money of the shares that the long side bought, a non-negative number.
  • lfee: Fee that the long side paid over the whole horizon.

The first two methods must return a non-negative number. The allocators do not check it. The third method returns a negative number when the book borrows, for example when the long side spends more than the cash. A plain function with the same three methods is also a valid ca, as CollateralAlg_Func states. A rule that has only the first two methods throws a MethodError when an allocator reports its cash.

Examples

julia> struct MyNoShortCollateral <: PortfolioOptimisers.AbstractCollateralAlgorithm endjulia> (::MyNoShortCollateral)(w, prices, cash) = zero(cash)julia> (::MyNoShortCollateral)(w, prices, cash, smoney, sfee) = cash * sum(x -> max(x, zero(x)), w)julia> (::MyNoShortCollateral)(w, prices, cash, smoney, sfee, lmoney, lfee) = cash - lmoney - lfeejulia> fai = FiniteAllocationInput(; w = [0.7, 0.5, -0.2], prices = [10.0, 20.0, 5.0],                                   cash = 1000.0, ca = MyNoShortCollateral());julia> optimise(GreedyAllocation(), fai).shares3-element view(::Matrix{Float64}, :, 1) with eltype Float64: 70.0 25.0 -0.0julia> optimise(GreedyAllocation(), fai).cash-200.0julia> no_short(w, prices, cash) = zero(cash);julia> no_short(w, prices, cash, smoney, sfee) = cash * sum(x -> max(x, zero(x)), w);julia> no_short(w, prices, cash, smoney, sfee, lmoney, lfee) = cash - lmoney - lfee;julia> optimise(GreedyAllocation(),                FiniteAllocationInput(; w = [0.7, 0.5, -0.2], prices = [10.0, 20.0, 5.0],                                      cash = 1000.0, ca = no_short)).shares3-element view(::Matrix{Float64}, :, 1) with eltype Float64: 70.0 25.0 -0.0

Related

source
PortfolioOptimisers.ProceedsCollateral — Type
struct ProceedsCollateral <: AbstractCollateralAlgorithm

Pays for the long side of a finite allocation with the proceeds of its short sales.

A short sale gives cash, and the long side can spend it. The long side receives its target, less the part of the short target that the short side did not sell, less the fee of the short side. So the net money of the book, long less short with both fees, is at most $C_{\text{tot}}\, b$, whatever the short side sells. The account keeps the cash, the short proceeds less the long money and both fees. It is the default ca of FiniteAllocationInput.

Mathematical definition

\[\begin{align} C_S^{\prime} &= C_S\,, \\ C_L^{\prime} &= \max\left(0,\, C_L - C_S + m_S - F_S\right)\,, \\ R &= C_{\text{tot}} + m_S - F_S - m_L - F_L\,. \end{align}\]

$C_L - C_S = C_{\text{tot}}\, b$ is the net money of the book. When the short side sells its whole target and pays no fee, $m_S = C_S$ and $F_S = 0$, so $C_L^{\prime} = C_L$. Each unit of target that the short side does not sell is a unit of cash that the long side does not get. The floor at zero applies to a book with $b < 0$ whose short side sells less than $-C_{\text{tot}}\, b$. Its long side then buys nothing.

$R$ also holds the cash that no side received. When the floor does not apply and the long side spends its whole cash, $m_L + F_L = C_L^{\prime}$, so $R = C_{\text{tot}} (1 - b)$. A book with $b < 1$ then keeps that cash, and a book with $b > 1$ borrows it, so its $R$ is negative. With the signed costs of the result, $\sum_i \mathrm{cost}_i + R + F_L + F_S = C_{\text{tot}}$ for every book.

Where:

  • $C_S^{\prime}$: Short cash, the cash that the short side can spend.
  • $C_L^{\prime}$: Long cash, the cash that the long side can spend after the short side trades.
  • $R$: Uninvested cash, the cash that the account holds after both sides trade, the cash of the allocation result. It is negative when the book borrows.
  • $C_S = C_{\text{tot}}\, b_S$: Short target, the money of the short side at its target weights.
  • $C_L = C_{\text{tot}}\, b_L$: Long target, the money of the long side at its target weights.
  • $C_{\text{tot}}$: Total cash of a finite allocation, the cash of FiniteAllocationInput.
  • $b = \sum_{i=1}^{N} w_i$: Total budget of a finite allocation, the sum of the target weights.
  • $m_S$: Short money, the money of the shares that the short side sold. It is non-negative.
  • $F_S$: Short fee, the fee that the short side paid over the whole horizon.
  • $m_L$: Long money, the money of the shares that the long side bought. It is non-negative.
  • $F_L$: Long fee, the fee that the long side paid over the whole horizon.

Functor

(ca::ProceedsCollateral)(w::VecNum, prices::VecNum, cash::Number)(ca::ProceedsCollateral)(w::VecNum, prices::VecNum, cash::Number, smoney::Number,                         sfee::Number)(ca::ProceedsCollateral)(w::VecNum, prices::VecNum, cash::Number, smoney::Number,                         sfee::Number, lmoney::Number, lfee::Number)

The first method returns $C_S^{\prime}$, with cash as $C_{\text{tot}}$. The second method returns $C_L^{\prime}$, with smoney as $m_S$ and sfee as $F_S$. The third method returns $R$, with lmoney as $m_L$ and lfee as $F_L$. No method reads prices, and the third method does not read w.

Examples

julia> ca = ProceedsCollateral()ProceedsCollateral()julia> ca([1.2, -0.5], [1.0, 1000.0], 100.0)50.0julia> ca([1.2, -0.5], [1.0, 1000.0], 100.0, 0.0, 0.0)70.0julia> ca([1.2, -0.5], [1.0, 1000.0], 100.0, 0.0, 0.0, 70.0, 0.0)30.0

Related

source
PortfolioOptimisers.CashCollateral — Type
struct CashCollateral{__T_amount} <: AbstractCollateralAlgorithm

Caps the money that a finite allocation ties up at a collateral amount.

A short sale gives no cash that the long side can spend, and the short position ties up collateral equal to its money. The long money, the short money and the fees of the two sides are together at most $K$. The long side takes the collateral that the short side did not use, so it buys more than its target when the short side sells less than its target and $K$ is large enough. With amount = nothing, $K$ is the cash of the allocation, so the book never ties up more than its cash. The account keeps the cash less the money of both sides and both fees.

Mathematical definition

\[\begin{align} C_S^{\prime} &= \min\left(C_S,\, K\right)\,, \\ C_L^{\prime} &= \max\left(0,\, \min\left(C_{\text{tot}} \left(b_L + b_S\right),\, K\right) - m_S - F_S\right)\,, \\ R &= C_{\text{tot}} - m_S - F_S - m_L - F_L\,. \end{align}\]

When $K \geq C_{\text{tot}} (b_L + b_S)$, $C_L^{\prime} = C_L + C_S - m_S - F_S$, the long target plus the collateral that the short side did not use. When $K$ is smaller, $K$ binds the whole book.

$R$ also holds the cash that no side received. When the floor does not apply and the long side spends its whole cash, $R = C_{\text{tot}} - \min\left(C_{\text{tot}} (b_L + b_S),\, K\right)$. A $K$ above the cash lets the book borrow, so its $R$ can be negative. With the absolute costs of the result, $\sum_i \left|\mathrm{cost}_i\right| + R + F_L + F_S = C_{\text{tot}}$ for every book.

Where:

  • $C_S^{\prime}$: Short cash, the cash that the short side can spend.
  • $C_L^{\prime}$: Long cash, the cash that the long side can spend after the short side trades.
  • $R$: Uninvested cash, the cash that the account holds after both sides trade, the cash of the allocation result. It is negative when the book borrows.
  • $C_S = C_{\text{tot}}\, b_S$: Short target, the money of the short side at its target weights.
  • $C_L = C_{\text{tot}}\, b_L$: Long target, the money of the long side at its target weights.
  • $K$: Collateral, amount, or $C_{\text{tot}}$ when amount is nothing.
  • $C_{\text{tot}}$: Total cash of a finite allocation, the cash of FiniteAllocationInput.
  • $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.
  • $m_S$: Short money, the money of the shares that the short side sold. It is non-negative.
  • $F_S$: Short fee, the fee that the short side paid over the whole horizon.
  • $m_L$: Long money, the money of the shares that the long side bought. It is non-negative.
  • $F_L$: Long fee, the fee that the long side paid over the whole horizon.

Fields

  • amount: Collateral amount, the most money that the book can tie up. nothing means the cash of the allocation.

Constructors

CashCollateral(;    amount::Option{<:Number} = nothing) -> CashCollateral

Keywords correspond to the struct's fields.

Validation

  • amount > 0 when amount is not nothing, else a DomainError.

Functor

(ca::CashCollateral)(w::VecNum, prices::VecNum, cash::Number)(ca::CashCollateral)(w::VecNum, prices::VecNum, cash::Number, smoney::Number,                     sfee::Number)(ca::CashCollateral)(w::VecNum, prices::VecNum, cash::Number, smoney::Number,                     sfee::Number, lmoney::Number, lfee::Number)

The first method returns $C_S^{\prime}$, with cash as $C_{\text{tot}}$. The second method returns $C_L^{\prime}$, with smoney as $m_S$ and sfee as $F_S$. The third method returns $R$, with lmoney as $m_L$ and lfee as $F_L$. No method reads prices, and the third method reads neither w nor amount.

Examples

julia> ca = CashCollateral()CashCollateral  amount ┴ nothingjulia> ca([1.2, -0.5], [1.0, 1000.0], 100.0)50.0julia> ca([1.2, -0.5], [1.0, 1000.0], 100.0, 0.0, 0.0)100.0julia> ca([1.2, -0.5], [1.0, 1000.0], 100.0, 0.0, 0.0, 100.0, 0.0)0.0

Related

source
PortfolioOptimisers.AbstractUnpricedWeightAlgorithm — Type
abstract type AbstractUnpricedWeightAlgorithm <: AbstractAlgorithm

Abstract supertype for the rules that move the target weight of an Unpriced Asset to other assets of a finite allocation.

An Unpriced Asset has a NaN price on the allocation date, because it has no bar on that date. An example is an asset that was delisted after the date of the weights. No allocator can buy such an asset. With upw = nothing, FiniteAllocationInput reads the weight of an Unpriced Asset as a zero weight, so the allocation does not spend it. That money stays in the cash of the result. A rule of this family moves that weight to priced assets of the same side, so the long and the short budget of the book do not change. The rule is the upw field of the input, not a field of the allocator, so every allocator of a fallback chain reads one rule.

Interfaces

To implement a new rule, subtype AbstractUnpricedWeightAlgorithm and make it callable with this method:

  • (upw::MyRule)(w::VecNum, umsk::AbstractVector{Bool}) -> VecNum: Returns the new target weights.

Where:

  • w: Target portfolio weights over the full universe. A negative weight is on the short side.
  • umsk: Mask of the Unpriced Assets, in the order of w.

The returned vector must have the length of w, and a zero at every Unpriced Asset. The allocators check both conditions, and throw an ArgumentError when one fails. A plain function with the same signature is also a valid upw. unpriced_weights states the zero-weight reading of nothing, which a rule can call to start from.

Examples

julia> struct MyFirstAssetRule <: PortfolioOptimisers.AbstractUnpricedWeightAlgorithm endjulia> function (::MyFirstAssetRule)(w, umsk)           wt = PortfolioOptimisers.unpriced_weights(nothing, w, umsk)           wt[1] += sum(w[umsk])           return wt       endjulia> fai = FiniteAllocationInput(; w = [0.5, 0.3, 0.2], prices = [10.0, 20.0, NaN],                                   cash = 1000.0, upw = MyFirstAssetRule());julia> optimise(GreedyAllocation(), fai).shares3-element view(::Matrix{Float64}, :, 1) with eltype Float64: 70.0 15.0  0.0

Related

source
PortfolioOptimisers.ProportionalRedistribution — Type
struct ProportionalRedistribution <: AbstractUnpricedWeightAlgorithm

Moves the target weight of each Unpriced Asset to the priced assets of its side, in proportion to their target weights.

The rule keeps the ratios of the target weights of the priced assets of each side. A priced asset with a zero target weight gets no weight. A side that has no priced asset with a nonzero target weight keeps the weight of its Unpriced Assets as a zero weight, as upw = nothing does.

Mathematical definition

\[\tilde{w}_i = \begin{cases} 0 & i \in \mathcal{U}\,,\\ w_i \left(1 + \dfrac{d_\sigma}{s_\sigma}\right) & i \in \mathcal{R}_\sigma\,,\\ w_i & \text{otherwise}\,, \end{cases} \qquad s_\sigma = \sum_{j \in \mathcal{R}_\sigma} w_j\,.\]

$\mathcal{R}_\sigma$ is the set of the priced assets of the side $\sigma$ with a nonzero target weight. $s_\sigma$ and $d_\sigma$ have the sign of the side, so the factor is larger than one on both sides, and the sum of the weights of each side does not change.

Where:

  • $\tilde{\boldsymbol{w}}$: New target weights.
  • $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
  • $\mathcal{U}$: Set of the Unpriced Assets.
  • $d_\sigma$: Target weight of the Unpriced Assets of the side, from unpriced_side_weight.
  • $s_\sigma$: Target weight of the priced assets of the side.

Functor

(upw::ProportionalRedistribution)(w::VecNum, umsk::AbstractVector{Bool})

Returns $\tilde{\boldsymbol{w}}$, with umsk as the mask of $\mathcal{U}$.

Examples

julia> ProportionalRedistribution()([0.5, 0.3, 0.2], [false, false, true])3-element Vector{Float64}: 0.625 0.375 0.0

Related

source
PortfolioOptimisers.EvenRedistribution — Type
struct EvenRedistribution <: AbstractUnpricedWeightAlgorithm

Moves the target weight of each Unpriced Asset to the priced assets of its side, in equal parts.

Each priced asset of the side with a nonzero target weight gets the same part. A priced asset with a zero target weight gets no part, because a zero weight marks an asset that the optimisation did not hold, such as an asset that left its universe. A side that has no priced asset with a nonzero target weight keeps the weight of its Unpriced Assets as a zero weight, as upw = nothing does.

Mathematical definition

\[\tilde{w}_i = \begin{cases} 0 & i \in \mathcal{U}\,,\\ w_i + \dfrac{d_\sigma}{\lvert \mathcal{R}_\sigma \rvert} & i \in \mathcal{R}_\sigma\,,\\ w_i & \text{otherwise}\,. \end{cases}\]

$\mathcal{R}_\sigma$ is the set of the priced assets of the side $\sigma$ with a nonzero target weight, and $\lvert \mathcal{R}_\sigma \rvert$ is its size.

Where:

  • $\tilde{\boldsymbol{w}}$: New target weights.
  • $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
  • $\mathcal{U}$: Set of the Unpriced Assets.
  • $d_\sigma$: Target weight of the Unpriced Assets of the side, from unpriced_side_weight.

Functor

(upw::EvenRedistribution)(w::VecNum, umsk::AbstractVector{Bool})

Returns $\tilde{\boldsymbol{w}}$, with umsk as the mask of $\mathcal{U}$.

Examples

julia> EvenRedistribution()([0.5, 0.3, 0.2, 0.0], [false, false, true, false])4-element Vector{Float64}: 0.6 0.4 0.0 0.0

Related

source
PortfolioOptimisers.AssetRedistribution — Type
struct AssetRedistribution{__T_idx} <: AbstractUnpricedWeightAlgorithm

Moves the target weight of each Unpriced Asset to the assets that idx names, in equal parts.

The weight of a side goes to the priced assets of idx on that side. An asset of idx with a zero target weight is on the long side, as in setup_alloc_optim, so it can take the weight of the long side, for example a fund that stands in for cash. A side that has no priced asset of idx keeps the weight of its Unpriced Assets as a zero weight, as upw = nothing does. So a long-short book names one asset of each side to move the weight of both sides.

Mathematical definition

\[\tilde{w}_i = \begin{cases} 0 & i \in \mathcal{U}\,,\\ w_i + \dfrac{d_\sigma}{\lvert \mathcal{R}_\sigma \rvert} & i \in \mathcal{R}_\sigma\,,\\ w_i & \text{otherwise}\,. \end{cases}\]

$\mathcal{R}_\sigma$ is the set of the priced assets of idx on the side $\sigma$, and $\lvert \mathcal{R}_\sigma \rvert$ is its size.

Where:

  • $\tilde{\boldsymbol{w}}$: New target weights.
  • $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
  • $\mathcal{U}$: Set of the Unpriced Assets.
  • $d_\sigma$: Target weight of the Unpriced Assets of the side, from unpriced_side_weight.

Fields

  • idx: Index, or vector of indices, of the assets that take the weight of the Unpriced Assets, in the order of w.

Constructors

AssetRedistribution(;    idx::Union{Integer, VecInt}) -> AssetRedistribution

Keywords correspond to the struct's fields.

Validation

  • idx is not empty, else an IsEmptyError.
  • Every entry of idx is positive, else a DomainError.
  • The functor throws a BoundsError when an entry of idx is larger than the length of w.

Functor

(upw::AssetRedistribution)(w::VecNum, umsk::AbstractVector{Bool})

Returns $\tilde{\boldsymbol{w}}$, with umsk as the mask of $\mathcal{U}$.

Examples

julia> AssetRedistribution(; idx = 4)([0.5, 0.3, 0.2, 0.0], [false, false, true, false])4-element Vector{Float64}: 0.5 0.3 0.0 0.2

Related

source
PortfolioOptimisers.SideRedistribution — Type
struct SideRedistribution{__T_l, __T_s} <: AbstractUnpricedWeightAlgorithm

Moves the target weight of the Unpriced Assets of the long side with one rule, and of the short side with another.

A short position that the book cannot open often needs no replacement, while a long position does. This rule composes two rules of the family, one for each side. nothing on a side reads the weight of the Unpriced Assets of that side as a zero weight. A zero weight is on the long side, as in setup_alloc_optim.

The rule reads only the entries of its own side from each rule. The built-in rules move weight inside each side, so for them the result is exact. A plain function that moves weight from one side to the other gives a result that this rule does not define, because the rule of each side loses the entries of the other side.

Mathematical definition

\[\tilde{w}_i = \begin{cases} \tilde{w}^{L}_i & w_i \geq 0\,,\\ \tilde{w}^{S}_i & w_i < 0\,. \end{cases}\]

Where:

  • $\tilde{\boldsymbol{w}}$: New target weights.
  • $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
  • $\tilde{\boldsymbol{w}}^{L}$, $\tilde{\boldsymbol{w}}^{S}$: New target weights of the rules l and s, from unpriced_weights, which also checks each one.

Fields

  • l: Rule for the weight of the Unpriced Assets of the long side, or nothing for a zero weight.
  • s: Rule for the weight of the Unpriced Assets of the short side, or nothing for a zero weight.

Constructors

SideRedistribution(;    l::Option{<:UnpricedAlg_Func} = nothing,    s::Option{<:UnpricedAlg_Func} = nothing) -> SideRedistribution

Keywords correspond to the struct's fields. With both rules nothing, the rule is equal to upw = nothing.

Validation

  • Neither l nor s is a SideRedistribution, else an ArgumentError. The rule of a side gives only the entries of that side, so a nested rule adds nothing.

Functor

(upw::SideRedistribution)(w::VecNum, umsk::AbstractVector{Bool})

Returns $\tilde{\boldsymbol{w}}$, with umsk as the mask of the Unpriced Assets.

Examples

julia> SideRedistribution(; l = ProportionalRedistribution())([0.6, 0.3, 0.3, -0.1, -0.1],                                                              [false, false, true, false, true])5-element Vector{Float64}:  0.8  0.4  0.0 -0.1  0.0

Related

source
PortfolioOptimisers.unpriced_weights — Function
unpriced_weights(::Nothing, w::VecNum, umsk::AbstractVector{Bool})
unpriced_weights(upw::UnpricedAlg_Func, w::VecNum, umsk::AbstractVector{Bool})

Give the target weights that a finite allocation buys when some of its assets are Unpriced Assets.

The method on nothing sets the weight of each Unpriced Asset to zero, and changes no other weight. The allocation then reads an Unpriced Asset as an asset with a zero target weight, so it does not spend its weight. The method on a rule calls the rule, and checks the vector that it returns. prepare_finite_allocation calls this method only when the prices hold a NaN.

The method on nothing returns a vector of eltype(w). The target weights are continuous.

Validation

  • The vector of a rule has the length of w, and a zero at every Unpriced Asset, else an ArgumentError.

Arguments

  • upw: The rule of the upw field of FiniteAllocationInput, or nothing.
  • w::VecNum: Target portfolio weights over the full universe.
  • umsk::AbstractVector{Bool}: Mask of the Unpriced Assets, in the order of w.

Returns

  • wt::VecNum: The new target weights.

Related

source
PortfolioOptimisers.FiniteAllocationInput — Type
struct FiniteAllocationInput{__T_w, __T_prices, __T_cash, __T_prev_cash, __T_horizon, __T_fees, __T_imsk, __T_ca, __T_upw} <: AbstractEstimator

Holds the target weights, prices and cash that a finite allocation reads.

optimise takes it as the second argument, with a DiscreteAllocation or a GreedyAllocation. It also holds the cash before the trade, an optional horizon, fee and Investable Mask, and the collateral algorithm that gives each side of the book its cash. It subtypes AbstractEstimator and not OptimisationResult, because it is the input of an allocation. The methods that dispatch on a result, such as the plots and the result factory, cannot read its fields.

An optimisation over a reduced universe solves on its Investable Mask, and expands the weights back to the full universe. Its result then has a full-length w and a fee on two reduced axes. imsk records the reduction. allocation_side_fees calls lift_fees to put the fee back on the axis of w and prices, so the allocation charges the forced exit of an asset that left the universe on the money that the exit sold. The fee records its mask in its own imsk field too, and the constructor makes the two agree through mark_fees. A stated imsk marks a fee that has no mask. A marked fee gives its mask when imsk is nothing. The constructor refuses two masks that differ.

An Unpriced Asset has a NaN price, the price of an asset with no bar on the allocation date. Both allocators solve each side over its priced assets only, so they buy no Unpriced Asset, and its shares, cost and realised weight are zero. Its price reaches no other number of the result. upw states what its target weight becomes. With upw = nothing, the weight is read as a zero weight, and the money of that weight stays in the cash of the result. A rule of AbstractUnpricedWeightAlgorithm moves it to priced assets of the same side. A held Unpriced Asset ends the trade with no money, so its turnover fee charges the sale of the whole previous position, as allocation_side_fees states.

Fields

  • w: Target portfolio weights, the continuous weights that the allocation turns into share counts.
  • prices: Asset prices, in the order of w.
  • cash: Cash of the allocation, which the long and the short side share.
  • prev_cash: Cash that the portfolio held before the trade. The money of a position before the trade is prev_cash times its previous weight, which fees.tn.w and fees.lq.w hold. The default is cash.
  • horizon: Horizon of the fee, in periods. l, s, tn and lq are rates per period, so the allocation charges each of them horizon times. fl, fs and flq are charged one time. It can be nothing only when fees is nothing.
  • fees: Fee of the allocation, or nothing. A fee that an optimisation reduced to its Investable Mask is on two reduced axes, and its own imsk records the mask that puts it back on the axis of w.
  • imsk: Investable Mask of the optimisation that gave w, true for each asset that it traded. nothing means that the weights and the fee are on the full universe. The constructor makes it agree with the mask of the fee through mark_fees.
  • ca: Collateral algorithm, which gives the short side its cash, and the long side its cash after the short side trades. It also gives the cash that the account holds after the trade, which is the cash of the result. A rule of AbstractCollateralAlgorithm, or a plain function with its three methods. The default ProceedsCollateral pays for the long side with the proceeds of the short sales.
  • upw: Rule for the target weight of an Unpriced Asset, an asset whose price is NaN. nothing reads the weight as a zero weight, so the allocation does not spend it, and its money stays in the cash of the result. A rule of AbstractUnpricedWeightAlgorithm, or a plain function with its signature, moves the weight to priced assets of the same side.

Constructors

FiniteAllocationInput(;    w::VecNum,    prices::VecNum,    cash::Number = 1e6,    prev_cash::Number = cash,    horizon::Option{<:Number} = nothing,    fees::Option{<:Fees} = nothing,    imsk::Option{<:BitVector} = nothing,    ca::CollateralAlg_Func = ProceedsCollateral(),    upw::Option{<:UnpricedAlg_Func} = nothing) -> FiniteAllocationInput

Keywords correspond to the struct's fields.

FiniteAllocationInput(    res::NonFiniteAllocationOptimisationResult;    prices::VecNum,    cash::Number = 1e6,    prev_cash::Number = cash,    w::Option{<:VecNum} = nothing,    horizon::Option{<:Number} = nothing,    fees::Option{<:Fees} = nothing,    imsk::Option{<:BitVector} = nothing,    ca::CollateralAlg_Func = ProceedsCollateral(),    upw::Option{<:UnpricedAlg_Func} = nothing) -> FiniteAllocationInput

Reads from a fitted optimisation every value that an allocation can take from it, so the caller states only the prices and the cash. A stated keyword takes priority. A value that the result does not carry becomes nothing, so one call serves every optimisation family:

  • w from res.w, which every optimisation result carries on the full universe.
  • fees through extract_fees, from the fees property when the result has one.
  • imsk through result_investable_mask, which gives nothing when the optimisation did not reduce its universe.
  • horizon through allocation_horizon, the number of observations of the result's prior. An equal weighted optimisation without a prior gives none. The constructor then needs a stated horizon, but only when the input also has a fee.

Validation

  • !isempty(w) and !isempty(prices), else an IsEmptyError.
  • length(w) == length(prices), else a DimensionMismatch.
  • No entry of prices is infinite, else a DomainError. An absent price is NaN, as the ingestion layer spells it.
  • cash > 0, else a DomainError.
  • prev_cash >= 0, else a DomainError.
  • horizon is not nothing when fees is not nothing, else an IsNothingError.
  • The mask of fees is nothing or equal to imsk. mark_fees throws an ArgumentError otherwise.
  • imsk, stated or read from the fee, has length(imsk) == length(w), else a DimensionMismatch, and any(imsk), else an IsEmptyError.

Examples

julia> FiniteAllocationInput(; w = [0.6, 0.4], prices = [10.0, 20.0], cash = 1000.0)FiniteAllocationInput          w ┼ Vector{Float64}: [0.6, 0.4]     prices ┼ Vector{Float64}: [10.0, 20.0]       cash ┼ Float64: 1000.0  prev_cash ┼ Float64: 1000.0    horizon ┼ nothing       fees ┼ nothing       imsk ┼ nothing         ca ┼ ProceedsCollateral()        upw ┴ nothing

Related

source
PortfolioOptimisers.factory — Method
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

References

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