Naive optimisation

PortfolioOptimisers.NaiveOptimisationResult — Type
struct NaiveOptimisationResult{__T_pr, __T_wb, __T_fees, __T_retcode, __T_w, __T_imsk, __T_fb} <: NonJuMPOptimisationResult

Holds 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 resolved Fees the head was charged with, on the universe it solved on, or nothing. A walk-forward fold charges it through extract_fees.
  • retcode: Optimisation return code.
  • w: Portfolio weights vector assets × 1.
  • imsk: The Investable Mask the optimisation reduced on: true at every asset whose prior moments were finite. It is nothing when every asset was investable, and that sentinel is what skips both the reduction and the expansion. investable_mask derives 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 attempt optimise made before this one, in the order they ran, or nothing when the estimator it was asked of answered (see FbChain).

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}) -> NaiveOptimisationResult

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

Related

source
PortfolioOptimisers.InverseVolatility — Type
struct InverseVolatility{__T_pe, __T_wb, __T_fees, __T_sets, __T_wf, __T_fb, __T_sq, __T_strict, __T_cache} <: NaiveOptimisationEstimator

Allocates 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 that sets does not hold raises an error. When it is false, the constraint generator warns and skips the entry.
  • cache: Optional ReturnsBufferState, the fold context of the online step. It is nothing until partial_fit! writes one, and optimise(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. factory carries it unchanged and port_opt_view slices 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) -> InverseVolatility

Keywords 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 wb is keyed by name (name_keyed): !isnothing(sets). A ScoreWeightBounds with a number or a vector of numbers in val names no asset and needs no sets.
  • If fees is a FeesEstimator: !isnothing(sets).
  • fb schedules: 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, see warn_raw_readers. The head then builds as configured.

Propagated parameters

factory passes its arguments on to these @fprop fields:

  • fees: Recursively updated through factory.
  • fb: Recursively updated through factory.
  • cache: Carried unchanged through factory.

View parameters

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

Observation weight parameters

obs_weights_view indexes these fields to the selected observations:

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: false

Related

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.
source
PortfolioOptimisers.EqualWeighted — Type
struct EqualWeighted{__T_wb, __T_fees, __T_sets, __T_wf, __T_fb, __T_strict, __T_cache} <: NaiveOptimisationEstimator

Allocates 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 that sets does not hold raises an error. When it is false, the constraint generator warns and skips the entry.
  • cache: Optional ReturnsBufferState, the fold context of the online step. It is nothing until partial_fit! writes one, and optimise(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. factory carries it unchanged and port_opt_view slices 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) -> EqualWeighted

Keywords 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 wb is keyed by name (name_keyed): !isnothing(sets). A ScoreWeightBounds with a number or a vector of numbers in val names no asset and needs no sets.
  • If fees is a FeesEstimator: !isnothing(sets).
  • fb schedules: bind !== :nearest.

Propagated parameters

factory passes its arguments on to these @fprop fields:

  • fees: Recursively updated through factory.
  • fb: Recursively updated through factory.
  • cache: Carried unchanged through factory.

View parameters

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

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: false

Related

source
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} <: NaiveOptimisationEstimator

Draws 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 of rng seeded with it, so rng does not advance and every call draws the same values. If nothing, the draws come from rng itself.
  • 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 that sets does not hold raises an error. When it is false, the constraint generator warns and skips the entry.
  • cache: Optional ReturnsBufferState, the fold context of the online step. It is nothing until partial_fit! writes one, and optimise(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. factory carries it unchanged and port_opt_view slices 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) -> RandomWeighted

Keywords 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 wb is keyed by name (name_keyed): !isnothing(sets). A ScoreWeightBounds with a number or a vector of numbers in val names no asset and needs no sets.
  • If fees is a FeesEstimator: !isnothing(sets).
  • fb schedules: bind !== :nearest.

Propagated parameters

factory passes its arguments on to these @fprop fields:

  • fees: Recursively updated through factory.
  • fb: Recursively updated through factory.
  • cache: Carried unchanged through factory.

View parameters

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

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: false

Related

source
PortfolioOptimisers.PreviousWeights — Type
struct PreviousWeights{__T_w, __T_fees, __T_fb} <: NaiveOptimisationEstimator

Holds 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, or nothing before the fold loop threads any.
  • fees: The resolved Fees the head was charged with, on the universe it solved on, or nothing. A walk-forward fold charges it through extract_fees.
  • fb: Fallback result or estimator.

Constructors

PreviousWeights(; w::Option{<:VecNum} = nothing, fees::Option{<:Fees} = nothing, fb::TDO_Option{<:OptE_Opt} = nothing) -> PreviousWeights

Keywords 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) when w is not nothing. The constructor throws a DomainError otherwise.
  • fb schedules: bind !== :nearest.

Propagated parameters

factory passes its arguments on to these @fprop fields:

  • fees: Recursively updated through factory.
  • fb: Recursively updated through factory.

View parameters

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

Examples

julia> PreviousWeights()PreviousWeights     w ┼ nothing  fees ┼ nothing    fb ┴ nothing

Related

source
PortfolioOptimisers.BestConstantRebalancedPortfolio — Type
struct BestConstantRebalancedPortfolio{__T_wb, __T_fees, __T_sets, __T_wf, __T_fb, __T_iters, __T_tol, __T_strict, __T_cache} <: NaiveOptimisationEstimator

Allocates 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 that sets does not hold raises an error. When it is false, the constraint generator warns and skips the entry.
  • cache: Optional ReturnsBufferState, the fold context of the online step. It is nothing until partial_fit! writes one, and optimise(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. factory carries it unchanged and port_opt_view slices 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) -> BestConstantRebalancedPortfolio

Keywords 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 wb is keyed by name (name_keyed): !isnothing(sets). A ScoreWeightBounds with a number or a vector of numbers in val names no asset and needs no sets.
  • If fees is a FeesEstimator: !isnothing(sets).
  • fb schedules: bind !== :nearest.
  • iters > 0.
  • tol > 0.

Propagated parameters

factory passes its arguments on to these @fprop fields:

  • fees: Recursively updated through factory.
  • fb: Recursively updated through factory.
  • cache: Carried unchanged through factory.

View parameters

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

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: false

Related

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.
source
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
                                 AbstractResult, StatsBase.CovarianceEstimator}},
        args...; kwargs...) -> AbstractArray

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

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

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

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

Algorithm

The leaf method:

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

The array method:

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

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

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

Arguments

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

Returns

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

Examples

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

Related

source
factory(res::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

  1. Read every field of res, in the order of the struct.
  2. Call the constructor of the type of res with every field except the last, and with fb as the last field.

Validation

  • fb is the last field of the type of res. Every concrete optimisation result obeys this rule, so the method checks nothing.

Related

source
factory(
    opt::Union{NonFiniteAllocationOptimisationEstimator, NonFiniteAllocationOptimisationResult},
    _
) -> EqualWeighted{_A, _B, _C, _D, _E, Bool} where {_A, _B, _C, _D, _E}

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

source
PortfolioOptimisers.factory — Method
factory(pw::PreviousWeights, w::VecNum) -> PreviousWeights

Thread 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 holding w, with fees and fb propagated through factory.

Examples

julia> PortfolioOptimisers.factory(PreviousWeights(), [0.25, 0.75])PreviousWeights     w ┼ Vector{Float64}: [0.25, 0.75]  fees ┼ nothing    fb ┴ nothing

Related

source
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

  1. Set every TimeDependent field of iv to its static default, with reset_time_dependent_estimator.
  2. Fit the prior pr with iv.pe on rd. The prior reads the returns in the frame that its own x_src states. rd keeps its raw returns.
  3. Resolve the fee on the full universe of rd, and view it on the Investable Mask of pr, giving fees.
  4. Reduce pr, iv and rd to the Investable Mask with investable_reduction, giving the mask imsk.
  5. Read the variances off the diagonal of pr.sigma, and take their inverse square roots, or their inverses when iv.sq is true, giving w.
  6. Divide w by its sum.
  7. Resolve the weight bounds wb over the reduced assets.
  8. Impose wb on w with the weight finaliser iv.wf, giving retcode and w.
  9. Build the NaiveOptimisationResult, which expands w onto the full universe.

Arguments

  • iv: The inverse volatility optimiser to use.
  • rd: The returns result to use. When iv.pe is a prior result, the fit reads no returns from rd, and an empty ReturnsResult() is enough.
  • kwargs: Ignored.

Related

source
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

  1. Refuse a missing rd.X with an IsNothingError.
  2. Set every TimeDependent field of ew to its static default, with reset_time_dependent_estimator.
  3. Resolve the fee on the full universe of rd, giving fees.
  4. Reduce ew and rd to the Coverage Universe with coverage_reduction, giving the mask cmsk. A window in which no asset is covered throws an IsEmptyError.
  5. View fees on cmsk.
  6. Fill w with $1/N$ over the $N$ assets that rd keeps.
  7. Resolve the weight bounds wb over the kept assets.
  8. Impose wb on w with the weight finaliser ew.wf, giving retcode and w.
  9. Build the NaiveOptimisationResult, which expands w onto 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.X is not nothing. The method throws an IsNothingError otherwise.

Related

source
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

  1. Refuse a missing rd.X with an IsNothingError.
  2. Set every TimeDependent field of rw to its static default, with reset_time_dependent_estimator.
  3. Refuse a vector rw.alpha whose length is not the width Nf of rd.X, with a DimensionMismatch.
  4. Resolve the fee on the full universe of rd, giving fees.
  5. Reduce rw and rd to the Coverage Universe with coverage_reduction, giving the mask cmsk. port_opt_view slices a vector rw.alpha with the rest of rw. A window in which no asset is covered throws an IsEmptyError.
  6. View fees on cmsk.
  7. Build the Dirichlet distribution dist over the $N$ kept assets, symmetric for a scalar rw.alpha.
  8. Draw w from dist with the generator that resolve_rng gives for rw.rng and rw.seed.
  9. Resolve the weight bounds wb over the kept assets.
  10. Impose wb on w with the weight finaliser rw.wf, giving retcode and w.
  11. Build the NaiveOptimisationResult, which expands w onto 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.X is not nothing. The method throws an IsNothingError otherwise.
  • A vector rw.alpha has one entry per column of rd.X. The method throws a DimensionMismatch otherwise.

Related

source
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

  1. Set every TimeDependent field of pw to its static default, with reset_time_dependent_estimator.
  2. With w set, give a NaiveOptimisationResult that carries w and an OptimisationSuccess.
  3. With w unset, give one that carries an OptimisationFailure and the weights of failed_hold_weights.

Arguments

  • pw: The hold-only head.
  • rd: The returns result to use. The result records it as pr. The head reads only the width of rd.X, and only when pw.w is nothing.
  • kwargs: Ignored.

Related

source
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

  1. Refuse a missing rd.X with an IsNothingError.
  2. Set every TimeDependent field of bcrp to its static default, with reset_time_dependent_estimator.
  3. Resolve the fee on the full universe of rd, giving fees.
  4. Reduce bcrp and rd to the Coverage Universe with coverage_reduction, giving the mask cmsk. A window in which no asset is covered throws an IsEmptyError.
  5. View fees on cmsk.
  6. Form the price relatives X, one plus rd.X.
  7. Run cover_fixed_point on X with bcrp.iters and bcrp.tol, giving fp.
  8. Resolve the weight bounds wb over the kept assets.
  9. Impose wb on fp.w with the weight finaliser bcrp.wf, giving retcode and w.
  10. When retcode is an OptimisationSuccess, replace it with one whose res holds fp.converged, fp.iterations and fp.gap.
  11. Build the NaiveOptimisationResult, which expands w onto 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.X is not nothing. The method throws an IsNothingError otherwise.

Related

source
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

source

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).