Risk budgeting
PortfolioOptimisers.RiskBudgetingResult — Type
struct RiskBudgetingResult{__T_jr, __T_rbr, __T_fb} <: RiskJuMPOptimisationResultHolds the solution, the resolved risk measures, the budget and the fallback chain of a Risk Budgeting optimisation.
optimise returns it for a RiskBudgeting. A name that is not a field resolves through rbr first, so res.rkb is the budget of the model. Every other name, and the property w, then resolves through jr, the JuMPOptimisationResult that the result holds.
Fields
jr: TheJuMPOptimisationResultthat holds the resolved bundle of the optimiser, the return code, the solution and the model.
r: The risk measure the optimisation ran under, or a vector of them, stored resolved. Every Deferred Quantity in it is fitted, and every unstated slot holds the prior's field. A resolved measure is fitted state, not configuration, so it belongs on the Result. Pass it back asexpected_risk(res.r, res.w, res.pr; sca = res.sca). The type ofris not a type parameter of the Result, so the Results of two risk measures have one type, and a verb that reads them compiles one time.
rbr: The resolved risk budget of the model, anAbstractResolvedRiskBudgeting.
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
RiskBudgetingResult(; jr::JuMPOptimisationResult, r::BaseRM_VecBaseRM, rbr::AbstractResolvedRiskBudgeting, fb::Option{<:OptE_Opt_FbChain}) -> RiskBudgetingResultKeywords correspond to the struct's fields.
Related
PortfolioOptimisers.LogRiskBudgeting — Type
struct LogRiskBudgeting{T} <: RiskBudgetingFormulationSelects the log-barrier formulation of the risk budgeting condition, in one orthant of the weights.
Equation 9 of [146] states it in the positive orthant, and problem 2.13 of [243] states it in any orthant. The logarithm needs a positive argument, so the solution lies in the orthant that z states, asset by asset. A stated orthant costs no binary variable, but the signs must be known in advance. MixedIntegerRiskBudgeting searches every orthant.
The solution in the orthant of z must have a positive sum. Otherwise the budget row needs a negative $k$, and $k \geq 0$. The solve then returns a portfolio of that orthant that misses the budget, or it fails. When no weight bound and no short budget bounds the scale, $k$ falls to the floor of risk_budgeting_scale_floor, and the weights grow as $1/k$. A $k$ on the floor is the signal of this case. Lemma 2.2 of [243] states, for the variance, that the portfolio of that orthant, normalised to a positive budget, lies in the complementary orthant, so -z gives it. The lemma needs $R(-\boldsymbol{y}) = R(\boldsymbol{y})$. A risk measure that is not even, such as ConditionalValueatRisk, has a different solution in the orthant -z, so solve in that orthant.
Fields
z: Orthant vector, one entry of1or-1for each asset. Entry $i$ is the sign of weight $i$.nothingputs every weight in the positive orthant.
Constructors
LogRiskBudgeting(; z::Option{<:VecInt} = nothing) -> LogRiskBudgetingKeywords correspond to the struct's fields.
Validation
- If
zis provided:!isempty(z)andall(x -> abs(x) == 1, z).
Related
References
- [146] B. Bruder and T. Roncalli. Managing risk exposures using the risk budgeting approach. Available at SSRN 2009778 (2012). Equation 9, and Section 2.4 for a general convex risk measure.
- [147] S. Maillard, T. Roncalli and J. Teiletche. On the properties of equally-weighted risk contributions portfolios. Available at SSRN 1271972 (2008). Equation 7 and Appendix A.2, for equal budgets.
- [243] X. Bai, K. Scheinberg and R. Tutuncu. Least-squares approach to risk parity in portfolio selection. Quantitative Finance 16, 357–376 (2016). Problem 2.13 and Lemma 2.2, for equal budgets in any orthant.
- [238] MOSEK ApS. MOSEK Portfolio Optimization Cookbook (2023). Section 9.3.2, Problem 9.7, for a general budget in any orthant.
- [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Section 10.1.3, Equations 10.8 to 10.10, for the variable $k$ that scales the weights.
PortfolioOptimisers.MixedIntegerRiskBudgeting — Type
struct MixedIntegerRiskBudgeting <: RiskBudgetingFormulationSelects the mixed-integer formulation of the risk budgeting condition, which searches every orthant of the weights.
Problem 9.9 of [238] states it. The weights are the difference of a long part and a short part, the logarithm reads their sum, and one binary variable for each asset holds one of the two parts at zero. The cost is one binary variable for each asset, and a mixed-integer conic solver.
The solve gives the orthant whose solution has the least risk at the scale $\boldsymbol{b}^\intercal \ln \lvert \boldsymbol{y} \rvert = 0$. Problem 9.9 writes the logarithm as a penalty in the objective, and this formulation writes it as a row, as LogRiskBudgeting does. In each orthant the two forms have the same solution up to a positive factor, and the risk measure is positively homogeneous, so both choose the same orthant. That orthant need not have the least risk after the normalisation to the budget, as Section 9.3.3 of [238] states.
The parts are the weights, so the budget rows bound them exactly. With a long budget and no short budget, the long parts sum to the budget, and the book stays long. A long-short solution needs bgt = nothing, or a short budget that leaves the short exposure free.
The search stops when the bound of the solver is near the objective, so a small objective can stop it in the wrong orthant. Measured on five assets with Variance, Pajarito with HiGHS and Clarabel at their default tolerances, and so = 1: the solve stopped in an orthant with 5.8 % more variance than the best one, and with a largest gap of 0.17 between a share of the risk and its budget. At so = 10_000, or with StandardDeviation, it found the best orthant, and the largest gap was below 2e-5. Scale the objective through the so field of JuMPOptimiser.
Related
References
- [238] MOSEK ApS. MOSEK Portfolio Optimization Cookbook (2023). Section 9.3.3, Problem 9.9.
- [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Section 10.1.4, Equation 10.11, for the logarithm as a row and one binary variable for each asset.
PortfolioOptimisers.AssetRiskBudgeting — Type
struct AssetRiskBudgeting{__T_rkb, __T_sets, __T_alg} <: RiskBudgetingAlgorithmSelects a risk budget over the assets, and the formulation that solves for it.
Each asset takes the share of the risk that its entry of rkb states. rkb = nothing gives every asset the share $1/N$. A RiskBudgetEstimator states the shares by asset or group names, and sets resolves the names. alg selects the formulation, see RiskBudgetingFormulation.
Fields
rkb: Risk budget estimator or result.
sets: Sets used to map estimator values to assets.
alg: Risk budget algorithm.
Constructors
AssetRiskBudgeting(; rkb::Option{<:RkbE_Rkb} = nothing, sets::Option{<:UniverseSets} = nothing, alg::RiskBudgetingFormulation = LogRiskBudgeting()) -> AssetRiskBudgetingKeywords correspond to the struct's fields.
Validation
- If
rkbis aRiskBudgetEstimator:!isnothing(sets).
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
rkb: Recursively viewed throughport_opt_view.sets: Sliced to the selected indices throughport_opt_view.alg: Recursively viewed throughport_opt_view.
Related
PortfolioOptimisers.FactorRiskBudgeting — Type
struct FactorRiskBudgeting{__T_re, __T_rkb, __T_sets, __T_flag, __T_hedge} <: RiskBudgetingAlgorithmSelects a risk budget over the factors of a loadings regression.
Each factor takes the share of the risk that its entry of rkb states, and rkb = nothing gives every factor the same share. Problem 8 of [223] states the formulation, and the # Mathematical definition of RiskBudgeting states it in the notation of the library. flag = false keeps the weights in the span of the loadings. flag = true adds the off-factor weights, which the solve sets freely, and hedge = true holds their marginal variance at zero.
A RiskBudgetEstimator states the budget by factor names. The names resolve against the factor axis that re names: factor_axis_key reads sets.tfkey for a time-series regression and sets.cfkey for a cross-sectional one. That axis must name the columns of rr.L in order, see risk_budget_universe_key.
Fields
re: Regression estimator.
rkb: Risk budget estimator or result.
sets: Universe sets. A factor axis is what this algorithm reads —factor_axis_keypickssets.tfkeyorsets.cfkeyoffre, so the axis follows the loadings family rather than the caller. It is the universe the risk budget is written in, and it must name the columns ofrr.Lin order — the budget is over the factor weightsw1, one per column of the loadings the risk decomposition uses. It is only read whenrkbis aRiskBudgetEstimator; aRiskBudgetresult carries its own vector and resolves no names. The asset axis is required byUniverseSetsand is what a view slices — the factor entries come back fromport_opt_viewuntouched.
flag: Algorithm selection flag.
hedge: Whether the off-factor weights hedge the factor exposures at minimum variance. Whentrueandflag = true, the model adds the rows $\mathbf{B}_2^\intercal \mathbf{\Sigma} \boldsymbol{w} = \boldsymbol{0}$, so the off-factor weights take no risk contribution. Ignored whenflag = false.
Constructors
FactorRiskBudgeting(; re::RegE_Reg = StepwiseRegression(), rkb::Option{<:RkbE_Rkb} = nothing, sets::Option{<:UniverseSets} = nothing, flag::Bool = true, hedge::Bool = false) -> FactorRiskBudgetingKeywords correspond to the struct's fields.
Validation
- If
rkbis aRiskBudgetEstimator:!isnothing(sets).
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
re: Loadings sliced to the selected assets throughport_opt_view.sets: Sliced throughport_opt_view, which keeps the selected entries of the asset axis and leaves the factor entries unchanged. The field takes a view because it can hold both axes.rkbtakes no view, because a factor budget has no asset index.
Observation weight parameters
obs_weights_view indexes these fields to the selected observations:
re: Recursively indexed throughobs_weights_view.
Related
RiskBudgetingAlgorithmAssetRiskBudgetingRiskBudgetingset_factor_risk_contribution_constraints!risk_budget_universe_keyport_opt_viewobs_weights_view
References
- [223] T. Roncalli and G. Weisang. Risk parity portfolios with risk factors. Available at SSRN 2155159 (2012). Equation 2, Theorem 1, Problem 8, and Section 4.1.1 for the separation principle.
- [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Section 10.2.2, Equation 10.21, for the variable $k$ that scales the weights.
PortfolioOptimisers.RiskBudgeting — Type
struct RiskBudgeting{__T_opt, __T_r, __T_rba, __T_wi, __T_kmin, __T_fb} <: RiskJuMPOptimisationEstimatorOptimises the portfolio whose assets, or whose factors, take stated shares of the risk.
rba selects the budget and its formulation, r gives the risk measures, and opt gives the prior, the solver and every other constraint. A row of opt that binds at the solution changes the optimality conditions, so the shares then miss the budget. With bgt = nothing no row fixes $k$, and the scale of the weights is the scale that the solver returns. $k \geq 0$, so the sign of each weight is the sign of its unscaled weight. kmin sets the floor of $k$, see risk_budgeting_scale_floor.
A small objective stops the solve short of the budget. Clarabel divides its duality gap by the larger of one and the cost, so on a cost far below one it reads an absolute gap. Measured on five assets with Variance, a variance of 2.4e-4 at the optimum, and Clarabel at tol_gap_abs = tol_gap_rel = tol_feas = 1e-11: under FactorRiskBudgeting with flag = false, the largest gap between a share of the risk and its budget was 1.3e-5 at so = 1, 1.6e-6 at so = 10, 1.8e-7 at so = 100 and 6.1e-10 at so = 1000. Under AssetRiskBudgeting it was 2.9e-6 at so = 1 and 3.9e-8 at so = 1000. Tighter tolerances at so = 1 stopped the solve at ALMOST_OPTIMAL, with a gap of 8.8e-6. Scale the objective through the so field of JuMPOptimiser.
Mathematical definition
The risk of a positively homogeneous risk measure splits into the contributions of the assets, which is the Euler decomposition. The risk budgeting condition states the share of each contribution:
\[\begin{align} RC_{i}(\boldsymbol{w}) &= w_{i} \frac{\partial R(\boldsymbol{w})}{\partial w_{i}}\,, \quad \frac{RC_{i}(\boldsymbol{w})}{\sum_{j=1}^{N} RC_{j}(\boldsymbol{w})} = b_{i}\,, \quad \sum_{i=1}^{N} b_{i} = 1\,, \quad b_{i} \geq 0\,. \end{align}\]
The condition is a system of equations that is not convex. LogRiskBudgeting solves a convex programme in its place, equation 9 of [146] in the orthant of $\boldsymbol{z}$:
\[\begin{align} \underset{\boldsymbol{y},\, k}{\min} \; &R(\boldsymbol{y}) \\ \text{s.t.} \quad &\boldsymbol{b}^\intercal \ln(\boldsymbol{z} \odot \boldsymbol{y}) \geq 0\,, \\ &\boldsymbol{z} \odot \boldsymbol{y} \geq \boldsymbol{0}\,, \\ &\boldsymbol{y} \in k\, \mathcal{W}\,, \quad \boldsymbol{w} = \boldsymbol{y} / k\,. \end{align}\]
When no row of $\mathcal{W}$ binds, the optimality conditions give $y_{i}\, \partial R(\boldsymbol{y}) / \partial y_{i} = \lambda b_{i}$, which is the risk budgeting condition. The solution cannot be zero, so the row of the logarithm binds, and it fixes the scale of $\boldsymbol{y}$. The right-hand side sets that scale alone, so the library uses 0 where the source writes a free constant. The budget row of $\mathcal{W}$, $\boldsymbol{1}^\intercal \boldsymbol{y} = b_{g} k$, then sets $k$.
MixedIntegerRiskBudgeting searches every orthant, after problem 9.9 of [238]:
\[\begin{align} \underset{\boldsymbol{y}^{+},\, \boldsymbol{y}^{-},\, \boldsymbol{g},\, k}{\min} \; &R(\boldsymbol{y}) \\ \text{s.t.} \quad &\boldsymbol{b}^\intercal \ln(\boldsymbol{y}^{+} + \boldsymbol{y}^{-}) \geq 0\,, \quad \boldsymbol{y} = \boldsymbol{y}^{+} - \boldsymbol{y}^{-}\,, \\ &\boldsymbol{y}^{+} \leq M \boldsymbol{g}\,, \quad \boldsymbol{y}^{-} \leq M (\boldsymbol{1} - \boldsymbol{g})\,, \\ &\boldsymbol{y}^{+},\, \boldsymbol{y}^{-} \geq \boldsymbol{0}\,, \quad \boldsymbol{g} \in \{0, 1\}^{N}\,, \\ &\boldsymbol{y} \in k\, \mathcal{W}\,, \quad \boldsymbol{w} = \boldsymbol{y} / k\,. \end{align}\]
FactorRiskBudgeting states the budget over the factor exposures $\boldsymbol{y}_{f} = \mathbf{B}^\intercal \boldsymbol{y}$, after problem 8 of [223]. The weights are written on the factor axis, and the row of the logarithm reads the factor exposures:
\[\begin{align} \boldsymbol{y} &= (\mathbf{B}^\intercal)^{+} \boldsymbol{y}_{f} + (\tilde{\mathbf{B}}^\intercal)^{+} \tilde{\boldsymbol{y}}_{af}\,, \quad \boldsymbol{b}_{f}^\intercal \ln(\boldsymbol{y}_{f}) \geq 0\,, \\ RC_{j}^{f}(\boldsymbol{w}) &= \left[ \mathbf{B}^\intercal \boldsymbol{w} \right]_{j} \left[ \frac{\partial R(\boldsymbol{w})}{\partial \boldsymbol{w}} (\mathbf{B}^\intercal)^{+} \right]_{j}\,. \end{align}\]
The off-factor term is present when flag = true. The solve sets $\tilde{\boldsymbol{y}}_{af}$ freely, so at the optimum the marginal risk of each off-factor direction is zero, and the factor contributions $RC_{j}^{f}$ take the shares $\boldsymbol{b}_{f}$. That is the separation principle of Section 4.1.1 of [223]. With hedge = true the rows $((\tilde{\mathbf{B}}^\intercal)^{+})^\intercal \mathbf{\Sigma} \boldsymbol{y} = \boldsymbol{0}$ hold that condition for the variance, also when a row of $\mathcal{W}$ binds.
Where:
- $\boldsymbol{w}$: Portfolio weights vector $N \times 1$.
- $\boldsymbol{y}$: Unscaled weights, the weight variable of the model.
- $k$: Variable that scales the budget in the homogenised problem. The model bounds it below by $k_{\min}$.
- $k_{\min}$: Lower bound on the homogenisation variable $k$, the field
kminof the optimiser or a size that the model derives. It is not negative, and zero turns the floor off.risk_budgeting_scale_floorsizes it, and a statedkminreplaces it. - $R(\boldsymbol{w})$: Portfolio risk. With many measures it is the scalarised risk of the model.
- $RC_{i}(\boldsymbol{w})$: Risk contribution of asset $i$.
- $\boldsymbol{b}$: Budget of the assets,
rba.rkb. - $\boldsymbol{z}$: Orthant vector of
LogRiskBudgeting, a vector of ones whenz = nothing. - $\mathcal{W}$: Feasible weight set, the portfolios that the constraints of the optimiser admit. It holds the weight bounds, the budgets and every other row of
opt. - $b_{g}$: The budget
opt.bgt. - $\lambda$: Multiplier of the row of the logarithm.
- $\boldsymbol{y}^{+}$, $\boldsymbol{y}^{-}$: Long and short parts of the unscaled weights.
- $\boldsymbol{g}$: Binary vector. $g_{i} = 1$ lets asset $i$ be long, and $g_{i} = 0$ lets it be short.
- $M$: Big-M constant,
opt.ss. - $\mathbf{B}$: Loading matrix, of size $N \times N_{f}$.
- $\tilde{\mathbf{B}}$: Basis of the kernel of $\mathbf{B}^\intercal$, the $N - N_{f}$ directions that the loadings do not span.
- $\boldsymbol{y}_{f}$, $\tilde{\boldsymbol{y}}_{af}$: Factor exposures and off-factor weights, both unscaled.
- $RC_{j}^{f}(\boldsymbol{w})$: Risk contribution of factor $j$.
- $\boldsymbol{b}_{f}$: Budget of the factors,
rba.rkb. - $\mathbf{\Sigma}$: Covariance matrix of the prior.
- $N$: Number of assets.
Fields
opt:JuMPoptimiser configuration.
r: Risk measure or vector of risk measures.
rba: Risk budget algorithm.
wi: Initial portfolio weights for warm-starting the solver.
kmin: Floor on the variablekthat scales the risk budgeting weights, ornothingto size it from the budget ofopt.0turns the floor off. It keeps the solver offk = 0, where the weightsw = y / khave no finite value. Akon the floor is the signal that no portfolio meets the budget in the orthant of the solve.
fb: Fallback result or estimator.
Constructors
RiskBudgeting(; opt::JuMPOptimiser, r::TD{<:RM_VecRM} = Variance(), rba::TD{<:RiskBudgetingAlgorithm} = AssetRiskBudgeting(), wi::TD_Option{<:VecNum} = nothing, kmin::Option{<:Number} = nothing, fb::TDO_Option{<:OptE_Opt} = nothing) -> RiskBudgetingKeywords correspond to the struct's fields. A field of the type TD, TD_Option or TDO_Option can hold a TimeDependent schedule in place of a static value. The risk measures, the budgeting algorithm with its budget, the initial weights and the fallback define the problem, so a cross-validation fold loop resolves them for each fold. An optimise outside a fold loop uses the static default of each field. The default of wi, of kmin and of fb is nothing.
Validation
- If
ris a vector:!isempty(r). - If
wiis provided:!isempty(wi). - If
kminis provided:kmin >= 0. - A schedule in
fb:bind !== :nearest. - The constructor refuses a risk expression that is identically zero, because every portfolio that meets the row of the logarithm is then optimal. A
NoRiskmeasure gives such an expression, and so doessettings.rke = falseon every measure. - If
rholds aDataBenchmarkTracking:opt.pemust not statex_src = ExcessSource(), seeassert_data_benchmark_prior. - A part that states no source and reads the raw returns, beside a part that states
x_src = ExcessSource(), logs one warning that names its path, seewarn_raw_readers. The constructor then builds the estimator as configured.
Propagated parameters
factory passes its arguments on to these @fprop fields:
opt: Recursively updated throughfactory.r: Recursively updated throughfactory.fb: Recursively updated throughfactory.
View parameters
RiskBudgeting defines its own port_opt_view method rather than deriving one from field tags.
- The method reads the returns matrix
Xas its third argument. Whenopt.peholds a prior result, the method usesopt.pe.Xin place ofX. So the views of the children read the observations of the prior, and not the matrix of the caller. optandrrecurse throughport_opt_viewwith that matrix.rbarecurses with the indices alone.fbrecurses throughview_childwith that matrix.wiis sliced to the selected assets.
Observation weight parameters
obs_weights_view indexes these fields to the selected observations:
opt: Recursively indexed throughobs_weights_view.r: Recursively indexed throughobs_weights_view.rba: Recursively indexed throughobs_weights_view.fb: Recursively indexed throughobs_weights_view.
Related
optimiseRiskBudgetingResultscalarise_risk_expression!set_risk_constraints!RiskJuMPOptimisationEstimatorMeanRiskRelaxedRiskBudgetingAssetRiskBudgetingFactorRiskBudgetingfactoryport_opt_viewobs_weights_view
References
- [146] B. Bruder and T. Roncalli. Managing risk exposures using the risk budgeting approach. Available at SSRN 2009778 (2012). Equation 9, and Section 2.4 for a general convex risk measure.
- [147] S. Maillard, T. Roncalli and J. Teiletche. On the properties of equally-weighted risk contributions portfolios. Available at SSRN 1271972 (2008). Equation 7 and Appendix A.2, for equal budgets.
- [243] X. Bai, K. Scheinberg and R. Tutuncu. Least-squares approach to risk parity in portfolio selection. Quantitative Finance 16, 357–376 (2016). Problem 2.13, for equal budgets in any orthant.
- [238] MOSEK ApS. MOSEK Portfolio Optimization Cookbook (2023). Section 9.3.2, Problem 9.7, and Section 9.3.3, Problem 9.9.
- [223] T. Roncalli and G. Weisang. Risk parity portfolios with risk factors. Available at SSRN 2155159 (2012). Equation 2, Theorem 1, Problem 8, and Section 4.1.1.
- [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Sections 10.1.3, 10.1.4 and 10.2.2, for the variable $k$ that scales the weights.
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.port_opt_view — Method
port_opt_view(alg::LogRiskBudgeting{<:VecInt}, i, args...) -> LogRiskBudgetingReturn a LogRiskBudgeting whose orthant vector is the view of alg.z at the assets i.
A LogRiskBudgeting with no orthant vector holds no data, and the universal method of port_opt_view returns it unchanged.
Arguments
alg: The formulation.i: Indices of the assets that the view keeps.args...: Not read.
Related
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(
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.port_opt_view — Method
port_opt_view(
rb::RiskBudgeting,
i,
X::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
args...
) -> RiskBudgeting{JuMPOptimiser{__T_pe, __T_slv, __T_cbe, __T_bgt, __T_fees, __T_ret, __T_sca, __T_sc, __T_so, __T_strict, __T_cache}} where {__T_pe, __T_slv, __T_cbe, __T_bgt, __T_fees, __T_ret, __T_sca, __T_sc, __T_so, __T_strict, __T_cache}
Return the view of a RiskBudgeting at the assets i.
The ## View parameters subsection of RiskBudgeting states how the method takes the view of each field.
Arguments
rb: The optimiser.i: Indices of the assets that the view keeps.X::MatNum: Returns matrix of the caller. The method uses the matrix of the prior in its place whenrb.opt.peholds a prior result.args...: Not read.
Returns
RiskBudgeting: A new optimiser, built through the keyword constructor.
Related
PortfolioOptimisers._optimise — Function
_optimise(rb::RiskBudgeting, rd::ReturnsResult = ReturnsResult(); str_names::Bool = false,
save::Bool = true, blocks::Tuple = (), kwargs...) -> RiskBudgetingResultBuild the model of a RiskBudgeting, solve it, and return its result.
optimise reaches this method through shared_series_solve, which drops the observations of a Shared Series gap before the solve.
Algorithm
- Replace each schedule of
rbwith its static default throughreset_time_dependent_estimator. - Resolve
rb.optagainstrdwithresolve_jump_optimiser, with the blocks ofblocks, givingattrs. It holds the prior, the block Results, the fees, the return terms and the Investable Mask. - Take the view of
rband ofrdat the investable assets withinvestable_view. Both are unchanged when every asset is investable. - Bind the benchmark of each
DataBenchmarkTrackingmeasure tordwithbind_data_benchmark. - Build a new model. Register the scales with
set_model_scales!and the number of observations withset_model_observations!. - Add the weights, the row of the logarithm and the weight constraints with
set_risk_budgeting_constraints!, givingrbr. - Add the constraints of every block, the return terms and the risk measures with
assemble_jump_model!, underMinimumRisk. - Set the objective
MinimumRisk, and solve withoptimise_JuMP_model!, givingretcodeandsol.process_modeldivides the unscaled weights by $k$. - Build the result. It holds
attrs,retcode,sol, the model whensaveistrue, the risk measures resolved against the prior, andrbr.
Arguments
rb::RiskBudgeting: The optimiser.rd: The returns result to use. Whenrb.opt.peis a prior result, the solve does not readrd, except to fit the loadings ofFactorRiskBudgetingwhen no other source holds them. A fallback or a clustering step can still read it.str_names::Bool:truegives each variable and each row of the model its string name.save::Bool:truekeeps the model in the result.blocks::Tuple = (): The blocks after the block of the optimiser of the head, the keywordblocksofresolve_jump_optimiser. The head adds the rows of every block to its model withassemble_jump_model!. The fallback chain ofoptimisepasses the keyword to each member, so a fallback solves on the same blocks.kwargs...: Passed on toresolve_jump_optimiser.
Returns
RiskBudgetingResult: The result, withfb = nothing.optimiseruns the fallback chain when the solve fails.
Related
PortfolioOptimisers.needs_previous_weights — Method
needs_previous_weights(opt::RiskBudgeting) -> Any
Return true when a part of opt needs the previous portfolio weights.
The parts are the schedules of the time-dependent fields, the JuMPOptimiser opt.opt, the risk measures opt.r and the fallback opt.fb. A turnover measure or a fee on the turnover is a part that needs them.
Returns
Bool:truewhen any part answerstrue.
Related
References
- [12]
- D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025).
- [146]
- B. Bruder and T. Roncalli. Managing Risk Exposures Using the Risk Budgeting Approach. Available at SSRN 2009778 (2012).
- [147]
- S. Maillard, T. Roncalli and J. Teiletche. On the Properties of Equally-Weighted Risk Contributions Portfolios. Available at SSRN 1271972 (2008).
- [223]
- T. Roncalli and G. Weisang. Risk Parity Portfolios with Risk Factors. Available at SSRN 2155159 (2012).
- [238]
- MOSEK ApS. MOSEK Portfolio Optimization Cookbook,
https://docs.mosek.com/portfolio-cookbook/index.html(2023). - [243]
- X. Bai, K. Scheinberg and R. Tutuncu. Least-Squares Approach to Risk Parity in Portfolio Selection. Quantitative Finance 16, 357–376 (2016).