Hierarchical Equal Risk Contribution
PortfolioOptimisers.HierarchicalEqualRiskContribution — Type
struct HierarchicalEqualRiskContribution{__T_opt, __T_ri, __T_ro, __T_scai, __T_scao, __T_ex, __T_fb} <: ClusteringOptimisationEstimatorSplits weight down the dendrogram between clusters by their outer risk ro, then splits each cluster's share between its assets by their inner risk ri.
This is the Hierarchical Equal Risk Contribution algorithm of Section 1 of [231]. It differs from HierarchicalRiskParity in two ways. It stops at the optimal number of clusters, not at the individual assets, and it splits at the branches of the dendrogram, not at the halves of a leaf order. The dendrogram split follows the hierarchical clustering based allocation of [232], which [231] reviews in the same section. The name is the source's. The portfolio is not a risk parity portfolio, and the clusters do not contribute equally to risk. It solves no optimisation problem, so it accepts a risk measure that is not convex. The weight finaliser of opt acts on the result, and _optimise states the steps.
Mathematical definition
Cut the dendrogram into $K$ clusters. The $K - 1$ nodes of the dendrogram above the cut each split their weight between their two branches, and every cluster lies wholly in one branch of each node above it:
\[\begin{align} \tilde{w}_i(C_k) &= \frac{\rho_o(\{i\})^{-1}}{\sum_{l \in C_k} \rho_o(\{l\})^{-1}} \quad \forall\, i \in C_k\,,\\ \tilde{\rho}_o(C_k) &= \rho_o\left(\tilde{\boldsymbol{w}}(C_k)\right)\,,\\ \alpha_n &= \frac{\sum_{C_k \subseteq B_2(n)} \tilde{\rho}_o(C_k)}{\sum_{C_k \subseteq B_1(n)} \tilde{\rho}_o(C_k) + \sum_{C_k \subseteq B_2(n)} \tilde{\rho}_o(C_k)}\,,\\ W(C_k) &= \prod_{n \in \mathcal{N},\, C_k \subseteq B_1(n)} \alpha_n \prod_{n \in \mathcal{N},\, C_k \subseteq B_2(n)} \left(1 - \alpha_n\right)\,,\\ v_i &= \frac{\rho_i(\{i\})^{-1}}{\sum_{l \in C_k} \rho_i(\{l\})^{-1}} \quad \forall\, i \in C_k\,,\\ w_i &= W(C_k) \, v_i \quad \forall\, i \in C_k\,. \end{align}\]
Where:
- $\rho_i$, $\rho_o$: The inner measure
riand the outer measurero, resolved byfactoryagainst the prior. - $\rho(\{i\})$: Risk of asset $i$ held alone under the measure $\rho$, from
unitary_expected_risks. - $C_k$: The $k$-th cluster. The $K$ clusters partition the universe.
- $\mathcal{N}$: The $K - 1$ nodes of the dendrogram above the cut.
- $B_1(n)$, $B_2(n)$: The left and right branches of node $n$. Each is a union of whole clusters.
- $\tilde{\boldsymbol{w}}(C_k)$: Naive risk parity weights inside cluster $C_k$ under $\rho_o$, zero outside it.
- $\tilde{\rho}_o(C_k)$: Risk of that naive risk parity sub-portfolio.
- $\alpha_n$: Split factor of node $n$, the fraction of its weight that goes to $B_1(n)$.
- $W(C_k)$: Weight of cluster $C_k$, the product of the split factors on the path from the root to $C_k$.
- $v_i$: Share of asset $i$ in the weight of its cluster.
- $w_i$: Weight of asset $i$.
The split factor $\alpha_n$ is Step 2.4 of Section 12.2.2 of [12], where the risk of a branch is the sum of the risks of its clusters. The branch with the lower risk receives more weight. Step 3 of [231] prints the factor of the first branch as $\mathcal{RC}_1 / (\mathcal{RC}_1 + \mathcal{RC}_2)$, which gives the first branch more weight when its risk is higher. This type does not follow that print. The shares $v_i$ are the naive risk parity weights of Step 4 of [231].
When ri is a vector, herc_intra_cluster_weights states the shares $v_i$ that the scalariser scai makes. When ro is a vector, herc_cluster_risk states the risk $\tilde{\rho}_o(C_k)$ that the scalariser scao makes.
The weights of the two branches of a node sum to the weight of the node, and the shares inside a cluster sum to one, so $\sum_k W(C_k) = 1$ and $\sum_i w_i = 1$. When $K = 2$ the one split gives each cluster a weight in inverse proportion to its risk. When $K > 2$ a cluster's weight is a product of split factors, and it is in general not the weight of a flat inverse-risk allocation over the $K$ clusters. The weights depend on the merge tree and on the cut. They do not depend on the order of the leaves.
Fields
opt: Base hierarchical optimiser configuration.
ri: Inner risk measure.
ro: Outer risk measure.
scai: Inner scalariser.nothinggives the sum ofSumScalariser.
scao: Outer scalariser.nothinggives the sum ofSumScalariser.
ex: Parallel execution strategy.
fb: Fallback result or estimator.
Constructors
HierarchicalEqualRiskContribution(; opt::HierarchicalOptimiser = HierarchicalOptimiser(), ri::TD{<:OptRM_VecOptRM} = Variance(), ro::TD{<:OptRM_VecOptRM} = ri, scai::TD_Option{<:Scalariser} = nothing, scao::TD_Option{<:Scalariser} = scai, ex::FLoops.Transducers.Executor = FLoops.ThreadedEx(), fb::TDO_Option{<:OptE_Opt} = nothing) -> HierarchicalEqualRiskContributionKeywords correspond to the struct's fields. Fields typed TD or TDO_Option may hold a TimeDependent per-fold schedule instead of a static value. The inner and outer risk measures, their scalarisers and the fallback are problem definition, so a cross-validation fold loop resolves them per fold. A fold-less optimise runs with each at its static default, which is nothing for fb. The executor ex is execution control and stays static.
Validation
- If
riis a vector:!isempty(ri). Ifrois a vector:!isempty(ro). The constructor throws anIsEmptyErrorotherwise. riandrohold noNoRisk, alone or in a vector. The constructor throws anArgumentErrorotherwise, throughassert_risk_measure_required, because a zero risk leaves the split factor undefined.fbschedules:bind !== :nearest. The constructor throws anArgumentErrorotherwise.- If
riholds aDataBenchmarkTracking:opt.pemust not statex_src = ExcessSource(), seeassert_data_benchmark_prior. - If
roholds aDataBenchmarkTracking:opt.pemust not statex_src = ExcessSource(), seeassert_data_benchmark_prior. - 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:
opt: Recursively updated throughfactory.ri: Recursively updated throughfactory.ro: Recursively updated throughfactory.fb: Recursively updated throughfactory.
View parameters
HierarchicalEqualRiskContribution 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 replacesXwithopt.pe.X, so it views the children against the observations of that prior, not against the caller's matrix. ri,roandoptrecurse throughport_opt_viewwith that matrix.- When
riandroare the same object, the method views it once and gives the view to both fields, so the two fields stay one object on the subset. fbrecurses throughview_childwith that matrix.scai,scaoandexstay unchanged.
Examples
julia> HierarchicalEqualRiskContribution()HierarchicalEqualRiskContribution opt ┼ HierarchicalOptimiser │ 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 │ cle ┼ ClustersEstimator │ │ 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) │ │ de ┼ Distance │ │ │ power ┼ nothing │ │ │ alg ┴ CanonicalDistance() │ │ alg ┼ HClustAlgorithm │ │ │ linkage ┴ Symbol: :ward │ │ onc ┼ OptimalNumberClusters │ │ │ max_k ┼ nothing │ │ │ alg ┼ SecondOrderDifference │ │ │ │ alg ┼ StandardisedValue │ │ │ │ │ mv ┼ MeanValue │ │ │ │ │ │ w ┴ nothing │ │ │ │ │ sv ┼ StdValue │ │ │ │ │ │ w ┼ nothing │ │ │ │ │ │ corrected ┴ Bool: true │ │ x_src ┴ nothing │ slv ┼ nothing │ wb ┼ WeightBounds │ │ lb ┼ Float64: 0.0 │ │ ub ┴ Float64: 1.0 │ fees ┼ nothing │ sets ┼ nothing │ wf ┼ IterativeWeightFinaliser │ │ iter ┴ Int64: 100 │ strict ┴ Bool: false ri ┼ Variance │ settings ┼ RiskMeasureSettings │ │ scale ┼ Float64: 1.0 │ │ ub ┼ nothing │ │ rke ┴ Bool: true │ sigma ┼ nothing │ chol ┼ nothing │ rc ┼ nothing │ alg ┼ SquaredSOCRiskExpr() │ mtx_sqrt ┼ EigenFallbackSquareRoot() │ ratio_alg ┼ SquareRootRatio() │ corner ┴ nothing ro ┼ Variance │ settings ┼ RiskMeasureSettings │ │ scale ┼ Float64: 1.0 │ │ ub ┼ nothing │ │ rke ┴ Bool: true │ sigma ┼ nothing │ chol ┼ nothing │ rc ┼ nothing │ alg ┼ SquaredSOCRiskExpr() │ mtx_sqrt ┼ EigenFallbackSquareRoot() │ ratio_alg ┼ SquareRootRatio() │ corner ┴ nothing scai ┼ nothing scao ┼ nothing ex ┼ Transducers.ThreadedEx{@NamedTuple{}}: Transducers.ThreadedEx() fb ┴ nothingRelated
optimiseHierarchicalEqualRiskContributionResultClusteringOptimisationEstimatorHierarchicalRiskParitySchurComplementHierarchicalRiskParityHierarchicalOptimiserunitary_expected_risksherc_riskfactoryport_opt_view
References
- [232] T. Raffinot. Hierarchical clustering-based asset allocation. The Journal of Portfolio Management 44, 89–99 (2017).
- [231] T. Raffinot. The hierarchical equal risk contribution portfolio. SSRN Electronic Journal (2018). Section 1, Steps 1 to 4.
- [12] D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025). Section 12.2.2, Steps 2.1 to 3.
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},
_
) -> 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
PortfolioOptimisers.port_opt_view — Method
port_opt_view(
hec::HierarchicalEqualRiskContribution,
i,
X::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
args...
) -> HierarchicalEqualRiskContribution{HierarchicalOptimiser{__T_pe, __T_cle, __T_slv, __T_wb, __T_fees, __T_sets, __T_wf, __T_strict, __T_cache}, _A, _B, _C, _D, <:Transducers.Executor} where {__T_pe, __T_cle, __T_slv, __T_wb, __T_fees, __T_sets, __T_wf, __T_strict, __T_cache, _A, _B, _C, _D}
Return a view of HierarchicalEqualRiskContribution hec sliced to asset indices i.
When hec.opt.pe holds a prior result, the view reads that prior's X in place of the X it receives. The struct's ## View parameters states what each field does.
Related
PortfolioOptimisers._optimise — Function
_optimise(
hec::HierarchicalEqualRiskContribution;
...
) -> HierarchicalEqualRiskContributionResult{HierarchicalResult{__T_pr, __T_clr, __T_wb, __T_fees, __T_retcode, __T_w, __T_imsk}, Nothing} where {__T_pr, __T_clr, __T_wb, __T_fees, __T_retcode, __T_w, __T_imsk}
_optimise(
hec::HierarchicalEqualRiskContribution,
rd::ReturnsResult;
branchorder,
rmsk,
kwargs...
) -> HierarchicalEqualRiskContributionResult{HierarchicalResult{__T_pr, __T_clr, __T_wb, __T_fees, __T_retcode, __T_w, __T_imsk}, Nothing} where {__T_pr, __T_clr, __T_wb, __T_fees, __T_retcode, __T_w, __T_imsk}
Run the Hierarchical Equal Risk Contribution optimisation.
optimise calls this method. The struct HierarchicalEqualRiskContribution states the mathematics.
Algorithm
- Resolve every
TimeDependentfield ofhecto its static default, withreset_time_dependent_estimator. - Fit the prior
prwithopt.peonrd. The prior reads the returns in the frame that its ownx_srcstates.rdkeeps its raw returns, and the clustering reads the frame that its ownx_srcstates. - Find the Investable Mask
imskofpr. Resolve the feesfeeson the full universe, and place them on the assets ofimsk. - Remove the two liquidation charges,
lqandflq, fromfees, givingcfees, the fees that the risks read. - Reduce
pr,hecandrdto the assets ofimsk, withinvestable_reduction.Xis the returns matrix of the reducedpr, andNits number of assets. - Cluster the assets with
opt.cle, givingclr, and cut its dendrogram intoclr.kclusters, givingcls, the asset indices of each cluster. - Compute the shares
wand the cluster risksrkclwithherc_risk. - Build the nodes
ndof the dendrogram withto_tree. The cut does the firstN - clr.kmerges in the order of their heights, asClustering.cutreedoes, so the otherclr.k - 1merges are the nodes above the cut. - For each node above the cut, read the assets
lnandrnof its two branches, and the clusterslcandrcinside them. - Form the split factor
alphafrom the risks oflcandrc. Multiplyw[ln]byalphaandw[rn]by1 - alpha. - Resolve the weight bounds
wbfromopt.wbandopt.sets. Dividewby its sum, and apply the weight finaliseropt.wfwithfinalise_weight_bounds, givingretcodeand the finalw. - Return a
HierarchicalEqualRiskContributionResult. ItsHierarchicalResultexpandswback onto the full asset universe throughimsk.
Arguments
hec: The hierarchical equal risk contribution optimiser to use.rd: The returns result to use. Ifisa(hec.opt.pe, AbstractPriorResult), a standalone optimisation does not needrd, but a fallback or the clustering can need it.branchorder: The branch order of the clustering. The weights do not depend on the order of the leaves, so a faster order that is not optimal gives the same weights. Whenopt.cleholds a clustering result, the order has no effect.rmsk: The mask of a fit again after a refusal, ornothingon the first fit.kwargs: Keyword arguments that the method accepts and does not read.
Related
PortfolioOptimisers.needs_previous_weights — Method
needs_previous_weights(
opt::HierarchicalEqualRiskContribution
) -> Any
Return whether the HierarchicalEqualRiskContribution needs previous portfolio weights.
Returns true when opt.opt, opt.ri, opt.ro or opt.fb needs previous weights, or when a TimeDependent schedule in a field holds a value that does. A TurnoverRiskMeasure and a turnover fee both need them.
Related
References
- [12]
- D. Cajas. Advanced Portfolio Optimization: A Cutting-edge Quantitative Approach (Springer Nature Switzerland, 2025).
- [231]
- T. Raffinot. The hierarchical equal risk contribution portfolio. SSRN Electronic Journal (2018).
- [232]
- T. Raffinot. Hierarchical clustering-based asset allocation. The Journal of Portfolio Management 44, 89–99 (2017).