Naive optimisation
PortfolioOptimisers.NaiveOptimisationResult — Type
struct NaiveOptimisationResult{__T_pr, __T_wb, __T_fees, __T_retcode, __T_w, __T_imsk, __T_fb} <: NonJuMPOptimisationResultHolds the weights, the bounds, the fee and the return code of a naive optimiser's fit.
Every subtype of NaiveOptimisationEstimator gives this result. pr is the prior result that InverseVolatility fits, or the returns data that a prior-free head reads.
Fields
pr: Prior result.
wb: Weight bounds.
fees: The resolvedFeesthe head was charged with, on the universe it solved on, ornothing. A walk-forward fold charges it throughextract_fees.
retcode: Optimisation return code.
w: Portfolio weights vectorassets × 1.
imsk: The Investable Mask the optimisation reduced on:trueat every asset whose prior moments were finite. It isnothingwhen every asset was investable, and that sentinel is what skips both the reduction and the expansion.investable_maskderives it once from the full-universe prior result, and the result carries it, because the reduced prior can no longer yield it.
fb: The fallback chain that answered this result: the(estimator, result)pair of every attemptoptimisemade before this one, in the order they ran, ornothingwhen the estimator it was asked of answered (seeFbChain).
Constructors
NaiveOptimisationResult(; pr::Option{<:Pr_RR}, wb::Option{<:WeightBounds}, fees::Option{<:Fees} = nothing, retcode::OptimisationReturnCode, w::Option{<:VecNum}, imsk::Option{<:BitVector} = nothing, fb::Option{<:OptE_Opt_FbChain}) -> NaiveOptimisationResultKeywords correspond to the struct's fields. The keyword constructor expands w from the assets of imsk onto the full asset universe with expand_investable_weights, and every _optimise of the family builds its result through it. The positional constructor never expands. fees is the fee of the head, on the universe that it solved on. A walk-forward fold charges it through extract_fees, as it charges the fee of a hierarchical head. It is nothing for a head that carries no fee.
Examples
julia> NaiveOptimisationResult(; pr = nothing, wb = nothing, retcode = OptimisationSuccess(), w = [0.5, 0.5], fb = nothing)NaiveOptimisationResult pr ┼ nothing wb ┼ nothing fees ┼ nothing retcode ┼ OptimisationSuccess │ res ┴ nothing w ┼ Vector{Float64}: [0.5, 0.5] imsk ┼ nothing fb ┴ nothingRelated
PortfolioOptimisers.InverseVolatility — Type
struct InverseVolatility{__T_pe, __T_wb, __T_fees, __T_sets, __T_wf, __T_fb, __T_sq, __T_strict, __T_cache} <: NaiveOptimisationEstimatorAllocates each asset a weight inversely proportional to its volatility, or to its variance when sq = true.
The variances are the diagonal of the covariance matrix that the prior estimator pe gives, so every choice inside pe reaches the weights. The inverse-variance weights, sq = true, are the naive risk parity allocation of Section 12.1.3 of [12]. The inverse-volatility weights are the equal risk contribution weights when every pair of assets has the same correlation, Equation 3 of [147]. The inverse-variance weights are the minimum variance weights when the covariance matrix is diagonal, Appendix A.2 of the online supplementary materials of [112]. HierarchicalRiskParity gives the assets of each half these weights under Variance, and the inverse-volatility weights under StandardDeviation, when it measures the risk of the half.
The weight finaliser wf then imposes the weight bounds, so the weights of the result equal the closed form below only when no bound binds.
Mathematical definition
\[\begin{align} w_i &= \frac{\sigma_i^{-1}}{\sum_{j=1}^N \sigma_j^{-1}} \quad \textrm{when } \texttt{sq = false}\,,\\ w_i &= \frac{\sigma_i^{-2}}{\sum_{j=1}^N \sigma_j^{-2}} \quad \textrm{when } \texttt{sq = true}\,. \end{align}\]
Where:
- $w_i$: Weight of asset $i$.
- $\sigma_i$: Standard deviation of asset $i$. Its square $\sigma_i^2$ is entry $i$ of the diagonal of the prior covariance matrix.
- $N$: Number of assets.
Fields
pe: Prior estimator.
wb: Weight bounds.
fees: Fees estimator or result.
sets: Sets used to map estimator values to assets.
wf: Weight finaliser.
fb: Fallback result or estimator.
sq: Whether to use variance instead of volatility in the inverse weighting.
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.
cache: OptionalReturnsBufferState, the fold context of the online step. It isnothinguntilpartial_fit!writes one, andoptimise(opt)with no returns reads it. The returns themselves are carried by the prior, which owns the rows once; this holds every other column of the returns data and the context pinned at the first step.factorycarries it unchanged andport_opt_viewslices it to the selected assets.
Constructors
InverseVolatility(; pe::Onl{<:TD{<:PrE_Pr}} = EmpiricalPrior(), wb::TD_Option{<:WbE_Wb} = WeightBounds(), fees::TD_Option{<:FeesE_Fees} = nothing, sets::TD_Option{<:UniverseSets} = nothing, wf::TD{<:WeightFinaliser} = IterativeWeightFinaliser(), fb::TDO_Option{<:OptE_Opt} = nothing, sq::Bool = false, strict::Bool = false, cache::Option{<:ReturnsBufferState} = nothing) -> InverseVolatilityKeywords correspond to the struct's fields. A field typed TD, TD_Option or TDO_Option can hold a TimeDependent per-fold schedule in place of a static value. The prior estimator, the weight bounds, the fees, the asset sets, the weight finaliser and the fallback define the problem, so a cross-validation fold loop resolves them for each fold. A fold-less optimise sets each of them to its static default. sq and strict control the run and stay static. The result carries fees, and a walk-forward fold charges it. A turnover fee reads the previous weights that the loop writes through factory.
Validation
- If
wbis keyed by name (name_keyed):!isnothing(sets). AScoreWeightBoundswith a number or a vector of numbers invalnames no asset and needs no sets. - If
feesis aFeesEstimator:!isnothing(sets). fbschedules:bind !== :nearest.- A reader that states no source and reads the raw returns data, beside a reader that states
x_src = ExcessSource(), logs one warning that names its path, seewarn_raw_readers. The head then builds as configured.
Propagated parameters
factory passes its arguments on to these @fprop fields:
fees: Recursively updated throughfactory.fb: Recursively updated throughfactory.cache: Carried unchanged throughfactory.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
pe: Recursively viewed throughport_opt_view.wb: Recursively viewed throughport_opt_view.fees: Recursively viewed throughport_opt_view.sets: Sliced to the selected indices throughport_opt_view.fb: Recursively viewed throughport_opt_view, except a precomputed result, which is kept (seeview_child).cache: Sliced to the selected assets throughport_opt_view.
Observation weight parameters
obs_weights_view indexes these fields to the selected observations:
pe: Recursively indexed throughobs_weights_view.fees: Recursively indexed throughobs_weights_view.fb: Recursively indexed throughobs_weights_view.cache: Removed byobs_weights_view, because a state has no slice on the observation axis.
Examples
julia> InverseVolatility()InverseVolatility pe ┼ EmpiricalPrior │ ce ┼ PortfolioOptimisersCovariance │ │ ce ┼ Covariance │ │ │ me ┼ SimpleExpectedReturns │ │ │ │ w ┴ nothing │ │ │ ce ┼ GeneralCovariance │ │ │ │ ce ┼ StatsBase.SimpleCovariance: StatsBase.SimpleCovariance(true) │ │ │ │ w ┴ nothing │ │ │ alg ┼ FullMoment() │ │ │ w ┴ nothing │ │ mp ┼ MatrixProcessing │ │ │ pdm ┼ Posdef │ │ │ │ alg ┼ UnionAll: NearestCorrelationMatrix.Newton │ │ │ │ kwargs ┴ @NamedTuple{}: NamedTuple() │ │ │ dn ┼ nothing │ │ │ dt ┼ nothing │ │ │ alg ┼ nothing │ │ │ order ┴ NTuple{4, Symbol}: (:pdm, :dn, :dt, :alg) │ me ┼ SimpleExpectedReturns │ │ w ┴ nothing │ horizon ┼ nothing │ fill_limit ┼ nothing │ x_src ┴ nothing wb ┼ WeightBounds │ lb ┼ Float64: 0.0 │ ub ┴ Float64: 1.0 fees ┼ nothing sets ┼ nothing wf ┼ IterativeWeightFinaliser │ iter ┴ Int64: 100 fb ┼ nothing sq ┼ Bool: false strict ┴ Bool: falseRelated
optimiseNaiveOptimisationResultNaiveOptimisationEstimatorEqualWeightedRandomWeightedfactoryport_opt_viewobs_weights_view
References
- [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Section 12.1.3, footnote 5. The original source of this formulation was not found. The formulation follows this work and is not checked against the original.
- [147] S. Maillard, T. Roncalli and J. Teiletche. On the properties of equally-weighted risk contributions portfolios. Available at SSRN 1271972 (2008). Section 3.2, Equation 3.
- [112] M. López de Prado. Building diversified portfolios that outperform out of sample. The Journal of Portfolio Management 42, 59–69 (2016). Online supplementary materials, Appendix A.2.
PortfolioOptimisers.EqualWeighted — Type
struct EqualWeighted{__T_wb, __T_fees, __T_sets, __T_wf, __T_fb, __T_strict, __T_cache} <: NaiveOptimisationEstimatorAllocates the same weight to every asset of the Coverage Universe of the window.
The optimiser fits no prior and reads no covariance matrix. It reads the asset count off the returns data.
$N$ is the size of the Coverage Universe of the window, not of the full asset universe. An asset is in it when its return is finite and the active mask of the AssetPanel is true at every row of the window. So an asset that is not yet listed, that is delisted, or that carries a stale finite price during an inactive spell holds a zero. The result carries the Coverage Universe as its imsk. A window in which no asset is covered throws an IsEmptyError.
The weight finaliser wf then imposes the weight bounds, so the weights of the result equal $1/N$ only when no bound binds.
Mathematical definition
\[\begin{align} w_i &= \frac{1}{N} \quad \forall i\,. \end{align}\]
Where:
- $w_i$: Weight of asset $i$.
- $N$: Number of assets.
Fields
wb: Weight bounds.
fees: Fees estimator or result.
sets: Sets used to map estimator values to assets.
wf: Weight finaliser.
fb: Fallback result or estimator.
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.
cache: OptionalReturnsBufferState, the fold context of the online step. It isnothinguntilpartial_fit!writes one, andoptimise(opt)with no returns reads it. This head holds no prior, so it is the bottom of the chain and its state carries the returns themselves, beside every other column of the returns data and the context pinned at the first step.factorycarries it unchanged andport_opt_viewslices it to the selected assets.
Constructors
EqualWeighted(; wb::TD_Option{<:WbE_Wb} = WeightBounds(), fees::TD_Option{<:FeesE_Fees} = nothing, sets::TD_Option{<:UniverseSets} = nothing, wf::TD{<:WeightFinaliser} = IterativeWeightFinaliser(), fb::TDO_Option{<:OptE_Opt} = nothing, strict::Bool = false, cache::Option{<:ReturnsBufferState} = nothing) -> EqualWeightedKeywords correspond to the struct's fields. A field typed TD, TD_Option or TDO_Option can hold a TimeDependent per-fold schedule in place of a static value. The weight bounds, the fees, the asset sets, the weight finaliser and the fallback define the problem, so a cross-validation fold loop resolves them for each fold. A fold-less optimise sets each of them to its static default. strict controls the run and stays static. The result carries fees, and a walk-forward fold charges it. A turnover fee reads the previous weights that the loop writes through factory.
Validation
- If
wbis keyed by name (name_keyed):!isnothing(sets). AScoreWeightBoundswith a number or a vector of numbers invalnames no asset and needs no sets. - If
feesis aFeesEstimator:!isnothing(sets). fbschedules:bind !== :nearest.
Propagated parameters
factory passes its arguments on to these @fprop fields:
fees: Recursively updated throughfactory.fb: Recursively updated throughfactory.cache: Carried unchanged throughfactory.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
wb: Recursively viewed throughport_opt_view.fees: Recursively viewed throughport_opt_view.sets: Sliced to the selected indices throughport_opt_view.fb: Recursively viewed throughport_opt_view, except a precomputed result, which is kept (seeview_child).cache: Sliced to the selected assets throughport_opt_view.
Examples
julia> EqualWeighted()EqualWeighted wb ┼ WeightBounds │ lb ┼ Float64: 0.0 │ ub ┴ Float64: 1.0 fees ┼ nothing sets ┼ nothing wf ┼ IterativeWeightFinaliser │ iter ┴ Int64: 100 fb ┼ nothing strict ┴ Bool: falseRelated
PortfolioOptimisers.RandomWeighted — Type
struct RandomWeighted{__T_alpha, __T_rng, __T_seed, __T_wb, __T_fees, __T_sets, __T_wf, __T_fb, __T_strict, __T_cache} <: NaiveOptimisationEstimatorDraws portfolio weights at random from a Dirichlet distribution with concentration alpha.
A scalar alpha gives every asset the same concentration, so the draw is from the symmetric Dirichlet distribution. A vector alpha states one concentration per asset of the full universe. The draw takes the float type of alpha, not of the returns data, so the default alpha = 1 gives Float64 weights and alpha = 1.0f0 gives Float32 weights.
$N$ is the size of the Coverage Universe of the window, not of the full asset universe. An asset is in it when its return is finite and the active mask of the AssetPanel is true at every row of the window. So an asset that is not yet listed, that is delisted, or that carries a stale finite price during an inactive spell holds a zero. A vector alpha is sliced to the Coverage Universe. The result carries the Coverage Universe as its imsk. A window in which no asset is covered throws an IsEmptyError.
The weight finaliser wf then imposes the weight bounds. The default wb is nothing, so by default no bound binds and the weights of the result are the draw.
Mathematical definition
\[\begin{align} \boldsymbol{w} &\sim \mathrm{Dirichlet}(\boldsymbol{\alpha})\,, \\ \mathbb{E}[\boldsymbol{w}] &= \frac{\boldsymbol{\alpha}}{\boldsymbol{1}^\intercal \boldsymbol{\alpha}}\,. \end{align}\]
Where:
- $\boldsymbol{w}$: Portfolio weights vector, one entry per asset of the Coverage Universe.
- $\boldsymbol{\alpha}$: Dirichlet concentration, one entry per asset.
- $N$: Number of assets.
A Dirichlet draw is non-negative and sums to one. A larger $\boldsymbol{1}^\intercal \boldsymbol{\alpha}$ concentrates the draws nearer their mean, which is $1/N$ for every asset when all the entries of $\boldsymbol{\alpha}$ are equal.
Fields
alpha: Dirichlet concentration parameter.
rng: Random number generator.
seed: Optional seed. If set, the draws come from a copy ofrngseeded with it, sorngdoes not advance and every call draws the same values. Ifnothing, the draws come fromrngitself.
wb: Weight bounds.
fees: Fees estimator or result.
sets: Sets used to map estimator values to assets.
wf: Weight finaliser.
fb: Fallback result or estimator.
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.
cache: OptionalReturnsBufferState, the fold context of the online step. It isnothinguntilpartial_fit!writes one, andoptimise(opt)with no returns reads it. This head holds no prior, so it is the bottom of the chain and its state carries the returns themselves, beside every other column of the returns data and the context pinned at the first step.factorycarries it unchanged andport_opt_viewslices it to the selected assets.
Constructors
RandomWeighted(; alpha::Num_VecNum = 1, rng::Random.AbstractRNG = Random.default_rng(), seed::Option{<:Integer} = nothing, wb::TD_Option{<:WbE_Wb} = nothing, fees::TD_Option{<:FeesE_Fees} = nothing, sets::TD_Option{<:UniverseSets} = nothing, wf::TD{<:WeightFinaliser} = IterativeWeightFinaliser(), fb::TDO_Option{<:OptE_Opt} = nothing, strict::Bool = false, cache::Option{<:ReturnsBufferState} = nothing) -> RandomWeightedKeywords correspond to the struct's fields. A field typed TD, TD_Option or TDO_Option can hold a TimeDependent per-fold schedule in place of a static value. The weight bounds, the fees, the asset sets, the weight finaliser and the fallback define the problem, so a cross-validation fold loop resolves them for each fold. A fold-less optimise sets each of them to its static default, which is nothing for wb, fees, sets and fb. alpha is static. rng, seed and strict control the run and stay static. The result carries fees, and a walk-forward fold charges it. A turnover fee reads the previous weights that the loop writes through factory.
Validation
alpha: non-empty, and every element is positive and finite.- If
wbis keyed by name (name_keyed):!isnothing(sets). AScoreWeightBoundswith a number or a vector of numbers invalnames no asset and needs no sets. - If
feesis aFeesEstimator:!isnothing(sets). fbschedules:bind !== :nearest.
Propagated parameters
factory passes its arguments on to these @fprop fields:
fees: Recursively updated throughfactory.fb: Recursively updated throughfactory.cache: Carried unchanged throughfactory.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
alpha: Sliced to the selected indices throughport_opt_view.wb: Recursively viewed throughport_opt_view.fees: Recursively viewed throughport_opt_view.sets: Sliced to the selected indices throughport_opt_view.fb: Recursively viewed throughport_opt_view, except a precomputed result, which is kept (seeview_child).cache: Sliced to the selected assets throughport_opt_view.
Examples
julia> RandomWeighted()RandomWeighted alpha ┼ Int64: 1 rng ┼ Random.TaskLocalRNG: Random.TaskLocalRNG() seed ┼ nothing wb ┼ nothing fees ┼ nothing sets ┼ nothing wf ┼ IterativeWeightFinaliser │ iter ┴ Int64: 100 fb ┼ nothing strict ┴ Bool: falseRelated
PortfolioOptimisers.PreviousWeights — Type
struct PreviousWeights{__T_w, __T_fees, __T_fb} <: NaiveOptimisationEstimatorHolds the weights it was handed, and solves nothing.
The fold loop writes the weights of the previous fold into w through factory, as it writes them into a TurnoverEstimator. The head returns w unchanged, on the full asset universe. It fits no prior, takes no Coverage Universe and imposes no weight bounds, so nothing rewrites a hold.
Its main use is as the fallback fb of an optimiser inside a walk-forward. A failed solve then holds the book, and the fold keeps finite weights in place of NaN weights. The head still holds a weight on an asset that left the panel, and the returns of that asset are zeroed as a Held Gap. It is also a primary optimiser: PreviousWeights(; w = w) is a walk-forward that holds w on every fold.
A view to an asset subset, such as a cluster of NestedClustered or the asset subset of a MultipleRandomised fold, slices w to the subset. The head holds that slice as it is, and does not rescale it to the budget of the subset.
The constructor refuses a w with a non-finite entry. A fit with w = nothing gives an OptimisationFailure. Fold 1 of a walk-forward and a fold-less optimise with no w meet that case. needs_previous_weights is true, so an optimiser that carries the head as a fallback runs its folds in sequence, and the loop writes the previous weights into it.
The online step of the head folds the rows into its fallback, and optimise(pw) with no data reads that fallback out when w is nothing. So the fallback answers from the rows that it reads in batch, also when the head is itself the fallback of an OnlinePortfolioSelection head, see step_fallback.
Fields
w: Weights to hold, ornothingbefore the fold loop threads any.
fees: The resolvedFeesthe head was charged with, on the universe it solved on, ornothing. A walk-forward fold charges it throughextract_fees.
fb: Fallback result or estimator.
Constructors
PreviousWeights(; w::Option{<:VecNum} = nothing, fees::Option{<:Fees} = nothing, fb::TDO_Option{<:OptE_Opt} = nothing) -> PreviousWeightsKeywords correspond to the struct's fields. fb can hold a TimeDependent per-fold schedule. fees is a resolved Fees, never an estimator, because the head holds no sets to resolve an estimator over. The result carries fees, and a walk-forward fold charges it. Under a Previous-Weights Source, its turnover term prices the rebalance from the drifted book back to the held target.
Validation
w:all(isfinite, w)whenwis notnothing. The constructor throws aDomainErrorotherwise.fbschedules:bind !== :nearest.
Propagated parameters
factory passes its arguments on to these @fprop fields:
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
w: Sliced to the selected indices throughport_opt_view.fees: Recursively viewed throughport_opt_view.fb: Recursively viewed throughport_opt_view, except a precomputed result, which is kept (seeview_child).
Examples
julia> PreviousWeights()PreviousWeights w ┼ nothing fees ┼ nothing fb ┴ nothingRelated
optimisefactory(pw::PreviousWeights, w::VecNum)NaiveOptimisationResultNaiveOptimisationEstimatorneeds_previous_weightsTurnoverEstimator: Receives the previous weights through the samefactorypass.fold_loop: Threads the previous fold's weights intow.
PortfolioOptimisers.BestConstantRebalancedPortfolio — Type
struct BestConstantRebalancedPortfolio{__T_wb, __T_fees, __T_sets, __T_wf, __T_fb, __T_iters, __T_tol, __T_strict, __T_cache} <: NaiveOptimisationEstimatorAllocates the constant rebalanced portfolio that maximises the log wealth of its window, through Cover's fixed point and without a solver.
It is the Hindsight Comparator of the online selection family that needs no solver. Fit it on the rows that a strategy is scored on, and predict it in sample over the same rows. Its log wealth is then the largest that a constant rebalanced portfolio reaches on those rows, and log_wealth_regret measures a strategy against it. A follow-the-leader rule can also re-solve it on the rows that the rule selects. MeanRisk(; obj = MaximumReturn(), opt = JuMPOptimiser(; slv, ret = LogarithmicReturn())) gives the same portfolio to the tolerance of its solver, with one exponential cone per row.
The fixed point knows no bound other than the simplex. The weight finaliser wf imposes a wb that binds after the fixed point, so the weights of the result are then a repair of the unconstrained optimum, and not the constrained optimum. The default bounds are the simplex, and the finaliser leaves the fixed point unchanged under them. For a bounded or constrained Hindsight Comparator, state the bounds on the MeanRisk form above.
The head fits no prior. It reduces to the Coverage Universe of its window. An asset is kept when its return is finite and the active mask of the AssetPanel is true at every row. Every other asset holds a zero, and the result carries the Coverage Universe as imsk.
The iteration stops when the certificate of the last line below is at most tol * max(1, |log wealth|), or after iters steps. So converged = true means that the log wealth is within that tolerance of the optimum. The certificate bounds the log wealth, not the weights. The weight of an asset that the optimum does not hold falls by the factor $g_i(\boldsymbol{b}^{\star})$ at each step. When that multiplier is near one, the default budget can stop first with converged = false. The retcode.res of the result holds converged, iterations and the certificate gap.
Mathematical definition
\[\begin{align} \boldsymbol{b}^{\star} &= \underset{\boldsymbol{b} \in \Delta_N}{\arg\max} \log S_T(\boldsymbol{b}) = \underset{\boldsymbol{b} \in \Delta_N}{\arg\max} \sum_{t=1}^{T} \log \langle \boldsymbol{b}, \boldsymbol{x}_t \rangle\,, \\ g_i(\boldsymbol{b}) &= \frac{1}{T} \sum_{t=1}^{T} \frac{x_{t,i}}{\langle \boldsymbol{b}, \boldsymbol{x}_t \rangle}\,, \\ b_i^{(k+1)} &= b_i^{(k)} \, g_i\left(\boldsymbol{b}^{(k)}\right)\,, \\ \log S_T(\boldsymbol{b}^{\star}) - \log S_T(\boldsymbol{b}) &\leq T \log \max_i g_i(\boldsymbol{b})\,. \end{align}\]
Where:
- $\boldsymbol{b}^{\star}$: Best constant rebalanced portfolio, the weights of the result when no bound binds.
- $\boldsymbol{b}$: Target of a constant rebalanced portfolio, the allocation that it rebalances to every period.
- $\Delta_N$: Probability simplex over the $N$ assets.
- $S_t(\boldsymbol{b}) = \prod_{s \leq t} \langle \boldsymbol{b}, \boldsymbol{x}_s \rangle$: Wealth of the constant rebalanced portfolio $\boldsymbol{b}$ after period $t$, from a wealth of one.
- $\boldsymbol{x}_t$: Price relative vector of period $t$, each asset's price over its price one period earlier. Its entry $x_{t,i}$ is one plus the return of asset $i$.
- $T$: Number of observations.
- $N$: Number of assets.
- $g_i(\boldsymbol{b})$: Multiplier of asset $i$ at $\boldsymbol{b}$, the mean over the periods of the price relative of asset $i$ divided by the gross return of $\boldsymbol{b}$.
- $\boldsymbol{b}^{(k)}$: Iterate $k$ of Cover's map.
The objective is concave on the simplex, so its maximum is global. The update is Equation 1.3 of [6], with the expectation over the periods taken as the mean over the $T$ rows. The multipliers satisfy $\sum_i b_i g_i(\boldsymbol{b}) = 1$, so the map keeps an iterate on the simplex. By Theorem 1 of [6], $\log S_T$ does not fall from one iterate to the next. An entry at zero stays at zero. At $\boldsymbol{b}^{\star}$ every held asset has $g_i = 1$ and every other asset has $g_i \leq 1$, which are Equations 3.1 and 3.2 of [6]. The last line is Theorem 4 of [6], scaled by $T$. It holds at every $\boldsymbol{b}$ in the simplex, by concavity and Jensen's inequality, and its right side is zero at $\boldsymbol{b}^{\star}$, a corner included.
Fields
wb: Weight bounds.
fees: Fees estimator or result.
sets: Sets used to map estimator values to assets.
wf: Weight finaliser.
fb: Fallback result or estimator.
iters: Maximum number of fixed-point iterations.
tol: Convergence tolerance on the certificate of the shortfall in log wealth from the optimum, relative to the log wealth.
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.
cache: OptionalReturnsBufferState, the fold context of the online step. It isnothinguntilpartial_fit!writes one, andoptimise(opt)with no returns reads it. This head holds no prior, so it is the bottom of the chain and its state carries the returns themselves, beside every other column of the returns data and the context pinned at the first step.factorycarries it unchanged andport_opt_viewslices it to the selected assets.
Constructors
BestConstantRebalancedPortfolio(; wb::TD_Option{<:WbE_Wb} = WeightBounds(), fees::TD_Option{<:FeesE_Fees} = nothing, sets::TD_Option{<:UniverseSets} = nothing, wf::TD{<:WeightFinaliser} = IterativeWeightFinaliser(), fb::TDO_Option{<:OptE_Opt} = nothing, iters::Integer = 20_000, tol::Number = 1e-12, strict::Bool = false, cache::Option{<:ReturnsBufferState} = nothing) -> BestConstantRebalancedPortfolioKeywords correspond to the struct's fields. A field typed TD, TD_Option or TDO_Option can hold a TimeDependent per-fold schedule in place of a static value. The weight bounds, the fees, the asset sets, the weight finaliser and the fallback define the problem, so a cross-validation fold loop resolves them for each fold. A fold-less optimise sets each of them to its static default. iters, tol and strict control the run and stay static. The result carries fees, and a walk-forward fold charges it. A turnover fee reads the previous weights that the loop writes through factory.
Validation
- If
wbis keyed by name (name_keyed):!isnothing(sets). AScoreWeightBoundswith a number or a vector of numbers invalnames no asset and needs no sets. - If
feesis aFeesEstimator:!isnothing(sets). fbschedules:bind !== :nearest.iters > 0.tol > 0.
Propagated parameters
factory passes its arguments on to these @fprop fields:
fees: Recursively updated throughfactory.fb: Recursively updated throughfactory.cache: Carried unchanged throughfactory.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
wb: Recursively viewed throughport_opt_view.fees: Recursively viewed throughport_opt_view.sets: Sliced to the selected indices throughport_opt_view.fb: Recursively viewed throughport_opt_view, except a precomputed result, which is kept (seeview_child).cache: Sliced to the selected assets throughport_opt_view.
Examples
julia> BestConstantRebalancedPortfolio()BestConstantRebalancedPortfolio wb ┼ WeightBounds │ lb ┼ Float64: 0.0 │ ub ┴ Float64: 1.0 fees ┼ nothing sets ┼ nothing wf ┼ IterativeWeightFinaliser │ iter ┴ Int64: 100 fb ┼ nothing iters ┼ Int64: 20000 tol ┼ Float64: 1.0e-12 strict ┴ Bool: falseRelated
optimiseNaiveOptimisationResultNaiveOptimisationEstimatorlog_wealth_regretcover_fixed_pointMeanRisk: Reaches the same portfolio with a solver underLogarithmicReturnandMaximumReturn, and takes bounds.LogarithmicReturnEqualWeightedfactoryport_opt_view
References
- [6] T. M. Cover. An algorithm for maximizing expected log investment return. IEEE Transactions on Information Theory 30(2), 369–373 (1984). Equation 1.3, Theorems 1 and 4, Equations 3.1 and 3.2.
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
AbstractResult, StatsBase.CovarianceEstimator}},
args...; kwargs...) -> AbstractArrayRebuild 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:
- Return
awith no change, and dropargs...andkwargs.... 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:
- For each element
aiofa, callfactoryonai, and forwardargs...andkwargs...with no change. - Collect the results into a new array of the shape of
a, in the order ofa, 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 ornothing, 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 ofa, 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 ┴ nothingRelated
factory(res::NonFiniteAllocationOptimisationResult, fb::Option{<:OptE_Opt_FbChain})Rebuilds a continuous optimisation result with a new fallback record fb.
A concrete result can add its own method when a rebuild needs more than a new fb. optimise is the one caller, and it gives the FbChain of the attempts that failed.
Algorithm
- Read every field of
res, in the order of the struct. - Call the constructor of the type of
reswith every field except the last, and withfbas the last field.
Validation
fbis the last field of the type ofres. Every concrete optimisation result obeys this rule, so the method checks nothing.
Related
factory(
opt::Union{NonFiniteAllocationOptimisationEstimator, NonFiniteAllocationOptimisationResult},
_
) -> RelaxedRiskBudgeting{JuMPOptimiser{__T_pe, __T_slv, __T_cbe, __T_bgt, __T_fees, __T_ret, __T_sca, __T_sc, __T_so, __T_strict, __T_cache}, _A, _B, <:RelaxedRiskBudgetingAlgorithm} where {__T_pe, __T_slv, __T_cbe, __T_bgt, __T_fees, __T_ret, __T_sca, __T_sc, __T_so, __T_strict, __T_cache, _A, _B}
Returns opt unchanged.
This is the fallback factory of an optimisation estimator or result. An estimator whose parameters change at each step of an optimisation adds its own method. A precomputed result in a field of an estimator, for example in fb, reaches this method when factory gives the estimator the weights of the previous fold. A precomputed result does not change.
Related
PortfolioOptimisers.factory — Method
factory(pw::PreviousWeights, w::VecNum) -> PreviousWeightsThread the previous fold's weights into the hold-only head, into its fee, and on into its fallback.
Arguments
pw: The head.w: The weights the fold loop threads.
Returns
PreviousWeights: The head holdingw, withfeesandfbpropagated throughfactory.
Examples
julia> PortfolioOptimisers.factory(PreviousWeights(), [0.25, 0.75])PreviousWeights w ┼ Vector{Float64}: [0.25, 0.75] fees ┼ nothing fb ┴ nothingRelated
PortfolioOptimisers._optimise — Method
_optimise(
iv::InverseVolatility;
...
) -> NaiveOptimisationResult{var"#s185", _A, _B, _C, _D, _E, Nothing} where {var"#s185"<:AbstractPriorResult, _A, _B, _C, _D, _E}
_optimise(
iv::InverseVolatility,
rd::ReturnsResult;
kwargs...
) -> NaiveOptimisationResult{var"#s185", _A, _B, _C, _D, _E, Nothing} where {var"#s185"<:AbstractPriorResult, _A, _B, _C, _D, _E}
Run the inverse volatility portfolio optimisation.
optimise calls this method. The weights follow the closed form of InverseVolatility on the assets of the Investable Mask, and every other asset holds a zero.
Algorithm
- Set every
TimeDependentfield ofivto its static default, withreset_time_dependent_estimator. - Fit the prior
prwithiv.peonrd. The prior reads the returns in the frame that its ownx_srcstates.rdkeeps its raw returns. - Resolve the fee on the full universe of
rd, and view it on the Investable Mask ofpr, givingfees. - Reduce
pr,ivandrdto the Investable Mask withinvestable_reduction, giving the maskimsk. - Read the variances off the diagonal of
pr.sigma, and take their inverse square roots, or their inverses wheniv.sqistrue, givingw. - Divide
wby its sum. - Resolve the weight bounds
wbover the reduced assets. - Impose
wbonwwith the weight finaliseriv.wf, givingretcodeandw. - Build the
NaiveOptimisationResult, which expandswonto the full universe.
Arguments
iv: The inverse volatility optimiser to use.rd: The returns result to use. Wheniv.peis a prior result, the fit reads no returns fromrd, and an emptyReturnsResult()is enough.kwargs: Ignored.
Related
PortfolioOptimisers._optimise — Method
_optimise(
ew::EqualWeighted,
rd::ReturnsResult;
kwargs...
) -> Union{NaiveOptimisationResult{ReturnsResult{__T_nx, __T_X, __T_nf, __T_F, __T_nb, __T_B, __T_ne, __T_E, __T_ts, __T_iv, __T_ivpa, __T_pnl}, _A, _B, _C, _D, _E, Nothing} where {__T_nx, __T_X, __T_nf, __T_F, __T_nb, __T_B, __T_ne, __T_E, __T_ts, __T_iv, __T_ivpa, __T_pnl, _A, _B, _C, _D, _E}, NaiveOptimisationResult{__T_pr, __T_wb, __T_fees, __T_retcode, _A, __T_imsk, Nothing} where {__T_pr<:ReturnsResult, __T_wb<:Union{Nothing, WeightBounds}, __T_fees<:Union{Nothing, Fees}, __T_retcode<:Union{OptimisationSuccess{Nothing}, OptimisationFailure{String}}, _A, __T_imsk<:Union{Nothing, BitVector}}}
Run the equal-weighted portfolio optimisation.
optimise calls this method. The head fits no prior, so no Prior Result gives it an Investable Mask. It takes the Coverage Universe of the window as its mask, and the result carries that mask as imsk, as the result of a prior-fitting head carries its Investable Mask.
Algorithm
- Refuse a missing
rd.Xwith anIsNothingError. - Set every
TimeDependentfield ofewto its static default, withreset_time_dependent_estimator. - Resolve the fee on the full universe of
rd, givingfees. - Reduce
ewandrdto the Coverage Universe withcoverage_reduction, giving the maskcmsk. A window in which no asset is covered throws anIsEmptyError. - View
feesoncmsk. - Fill
wwith $1/N$ over the $N$ assets thatrdkeeps. - Resolve the weight bounds
wbover the kept assets. - Impose
wbonwwith the weight finaliserew.wf, givingretcodeandw. - Build the
NaiveOptimisationResult, which expandswonto the full universe.
Arguments
ew: The equal-weighted optimiser to use.rd: The returns result to use. Its returns matrix and its Asset Panel give the Coverage Universe of the window, and the weights are spread over that universe.kwargs: Ignored.
Validation
rd.Xis notnothing. The method throws anIsNothingErrorotherwise.
Related
PortfolioOptimisers._optimise — Method
_optimise(
rw::RandomWeighted,
rd::ReturnsResult;
kwargs...
) -> Union{NaiveOptimisationResult{ReturnsResult{__T_nx, __T_X, __T_nf, __T_F, __T_nb, __T_B, __T_ne, __T_E, __T_ts, __T_iv, __T_ivpa, __T_pnl}, _A, _B, _C, _D, _E, Nothing} where {__T_nx, __T_X, __T_nf, __T_F, __T_nb, __T_B, __T_ne, __T_E, __T_ts, __T_iv, __T_ivpa, __T_pnl, _A, _B, _C, _D, _E}, NaiveOptimisationResult{__T_pr, __T_wb, __T_fees, __T_retcode, _A, __T_imsk, Nothing} where {__T_pr<:ReturnsResult, __T_wb<:Union{Nothing, WeightBounds}, __T_fees<:Union{Nothing, Fees}, __T_retcode<:Union{OptimisationSuccess{Nothing}, OptimisationFailure{String}}, _A, __T_imsk<:Union{Nothing, BitVector}}}
Run the random-weighted portfolio optimisation.
optimise calls this method. The head fits no prior, so no Prior Result gives it an Investable Mask. It takes the Coverage Universe of the window as its mask, and the result carries that mask as imsk, as the result of a prior-fitting head carries its Investable Mask. A vector alpha states one concentration per asset of the full universe, so the method checks its length against the full width, before the reduction slices it.
Algorithm
- Refuse a missing
rd.Xwith anIsNothingError. - Set every
TimeDependentfield ofrwto its static default, withreset_time_dependent_estimator. - Refuse a vector
rw.alphawhose length is not the widthNfofrd.X, with aDimensionMismatch. - Resolve the fee on the full universe of
rd, givingfees. - Reduce
rwandrdto the Coverage Universe withcoverage_reduction, giving the maskcmsk.port_opt_viewslices a vectorrw.alphawith the rest ofrw. A window in which no asset is covered throws anIsEmptyError. - View
feesoncmsk. - Build the Dirichlet distribution
distover the $N$ kept assets, symmetric for a scalarrw.alpha. - Draw
wfromdistwith the generator thatresolve_rnggives forrw.rngandrw.seed. - Resolve the weight bounds
wbover the kept assets. - Impose
wbonwwith the weight finaliserrw.wf, givingretcodeandw. - Build the
NaiveOptimisationResult, which expandswonto the full universe.
Arguments
rw: The random-weighted optimiser to use.rd: The returns result to use. Its returns matrix and its Asset Panel give the Coverage Universe of the window, and the draw is over that universe.kwargs: Ignored.
Validation
rd.Xis notnothing. The method throws anIsNothingErrorotherwise.- A vector
rw.alphahas one entry per column ofrd.X. The method throws aDimensionMismatchotherwise.
Related
PortfolioOptimisers._optimise — Function
_optimise(
pw::PreviousWeights;
...
) -> NaiveOptimisationResult{ReturnsResult{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}, Nothing, __T_fees, __T_retcode, __T_w, Nothing, Nothing} where {__T_fees, __T_retcode, __T_w}
_optimise(
pw::PreviousWeights,
rd::ReturnsResult;
kwargs...
) -> NaiveOptimisationResult{__T_pr, Nothing, __T_fees, __T_retcode, __T_w, Nothing, Nothing} where {__T_pr, __T_fees, __T_retcode, __T_w}
Return the held weights as a result, or a failure when there are none.
optimise calls this method. It reads only the width of rd. The weights of the result are w unchanged, on the universe that the loop wrote them on, with imsk = nothing and no weight bounds.
A head whose w is nothing gives an OptimisationFailure that names the missing weights, so a fallback chain that reaches it goes on to the next fallback. Its weights are then NaN at every column of rd.X, as the weights of every failed solve are, so a fold reads this failure as it reads any other. They are nothing when rd.X is nothing.
Algorithm
- Set every
TimeDependentfield ofpwto its static default, withreset_time_dependent_estimator. - With
wset, give aNaiveOptimisationResultthat carrieswand anOptimisationSuccess. - With
wunset, give one that carries anOptimisationFailureand the weights offailed_hold_weights.
Arguments
pw: The hold-only head.rd: The returns result to use. The result records it aspr. The head reads only the width ofrd.X, and only whenpw.wisnothing.kwargs: Ignored.
Related
PortfolioOptimisers._optimise — Method
_optimise(
bcrp::BestConstantRebalancedPortfolio,
rd::ReturnsResult;
kwargs...
) -> Union{NaiveOptimisationResult{ReturnsResult{__T_nx, __T_X, __T_nf, __T_F, __T_nb, __T_B, __T_ne, __T_E, __T_ts, __T_iv, __T_ivpa, __T_pnl}, _A, _B, _C, _D, _E, Nothing} where {__T_nx, __T_X, __T_nf, __T_F, __T_nb, __T_B, __T_ne, __T_E, __T_ts, __T_iv, __T_ivpa, __T_pnl, _A, _B, _C, _D, _E}, NaiveOptimisationResult{__T_pr, __T_wb, __T_fees, __T_retcode, _A, __T_imsk, Nothing} where {__T_pr<:ReturnsResult, __T_wb<:Union{Nothing, WeightBounds}, __T_fees<:Union{Nothing, Fees}, __T_retcode<:Union{OptimisationFailure{String}, OptimisationSuccess{__T_res} where __T_res<:(NamedTuple{(:converged, :iterations, :gap), <:Tuple{Any, Int64, Any}})}, _A, __T_imsk<:Union{Nothing, BitVector}}}
Run the best constant rebalanced portfolio optimisation.
optimise calls this method. The return code is the one of the weight finaliser. A successful return code holds the converged flag, the iteration count and the certificate gap of the fixed point in its res, so the caller reads a run that stopped at iters off the result, and the method throws nothing for it.
Algorithm
- Refuse a missing
rd.Xwith anIsNothingError. - Set every
TimeDependentfield ofbcrpto its static default, withreset_time_dependent_estimator. - Resolve the fee on the full universe of
rd, givingfees. - Reduce
bcrpandrdto the Coverage Universe withcoverage_reduction, giving the maskcmsk. A window in which no asset is covered throws anIsEmptyError. - View
feesoncmsk. - Form the price relatives
X, one plusrd.X. - Run
cover_fixed_pointonXwithbcrp.itersandbcrp.tol, givingfp. - Resolve the weight bounds
wbover the kept assets. - Impose
wbonfp.wwith the weight finaliserbcrp.wf, givingretcodeandw. - When
retcodeis anOptimisationSuccess, replace it with one whoseresholdsfp.converged,fp.iterationsandfp.gap. - Build the
NaiveOptimisationResult, which expandswonto the full universe.
A Hindsight Comparator is fit on the rows that it is scored on. So predict(optimise(bcrp, rd_test), rd_test) is the prediction result of the comparator over rd_test, and cross_val_predict(bcrp, rd, cv) is the causal constant portfolio over the same rows.
Arguments
bcrp: The best constant rebalanced portfolio optimiser to use.rd: The returns result to use. Its returns matrix and its Asset Panel give the Coverage Universe of the window, and the fixed point runs over that universe.kwargs: Ignored.
Validation
rd.Xis notnothing. The method throws anIsNothingErrorotherwise.
Related
PortfolioOptimisers.needs_previous_weights — Method
needs_previous_weights(
opt::NaiveOptimisationEstimator
) -> Bool
Return whether the naive optimiser needs the previous portfolio weights.
The answer is true when one of three parts needs them. The first is a TimeDependent schedule on any field. The second is the fees. A static Fees whose turnover or liquidation term is not fixed reads the previous weights through factory, as it does on a JuMPOptimiser. The third is the fallback fb. PreviousWeights overrides this method and always answers true.
Related
References
- [6]
- T. M. Cover. An algorithm for maximizing expected log investment return. IEEE Transactions on Information Theory 30, 369–373 (1984).
- [12]
- D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025).
- [112]
- M. López de Prado. Building diversified portfolios that outperform out of sample. The Journal of Portfolio Management 42, 59–69 (2016).
- [147]
- S. Maillard, T. Roncalli and J. Teiletche. On the Properties of Equally-Weighted Risk Contributions Portfolios. Available at SSRN 1271972 (2008).