Hierarchical Equal Risk Contribution

PortfolioOptimisers.HierarchicalEqualRiskContribution — Type
struct HierarchicalEqualRiskContribution{__T_opt, __T_ri, __T_ro, __T_scai, __T_scao, __T_ex, __T_fb} <: ClusteringOptimisationEstimator

Splits 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 ri and the outer measure ro, resolved by factory against 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.
  • 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) -> HierarchicalEqualRiskContribution

Keywords 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 ri is a vector: !isempty(ri). If ro is a vector: !isempty(ro). The constructor throws an IsEmptyError otherwise.
  • ri and ro hold no NoRisk, alone or in a vector. The constructor throws an ArgumentError otherwise, through assert_risk_measure_required, because a zero risk leaves the split factor undefined.
  • fb schedules: bind !== :nearest. The constructor throws an ArgumentError otherwise.
  • If ri holds a DataBenchmarkTracking: opt.pe must not state x_src = ExcessSource(), see assert_data_benchmark_prior.
  • If ro holds a DataBenchmarkTracking: opt.pe must not state x_src = ExcessSource(), see assert_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, see warn_raw_readers. The head then builds as configured.

Propagated parameters

factory passes its arguments on to these @fprop fields:

  • opt: Recursively updated through factory.
  • ri: Recursively updated through factory.
  • ro: Recursively updated through factory.
  • fb: Recursively updated through factory.

View parameters

HierarchicalEqualRiskContribution defines its own port_opt_view method rather than deriving one from field tags.

  • The method reads the returns matrix X as its third argument. When opt.pe holds a prior result, the method replaces X with opt.pe.X, so it views the children against the observations of that prior, not against the caller's matrix.
  • ri, ro and opt recurse through port_opt_view with that matrix.
  • When ri and ro are 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.
  • fb recurses through view_child with that matrix.
  • scai, scao and ex stay 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 ┴ nothing

Related

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

source
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

  1. Resolve every TimeDependent field of hec to its static default, with reset_time_dependent_estimator.
  2. Fit the prior pr with opt.pe on rd. The prior reads the returns in the frame that its own x_src states. rd keeps its raw returns, and the clustering reads the frame that its own x_src states.
  3. Find the Investable Mask imsk of pr. Resolve the fees fees on the full universe, and place them on the assets of imsk.
  4. Remove the two liquidation charges, lq and flq, from fees, giving cfees, the fees that the risks read.
  5. Reduce pr, hec and rd to the assets of imsk, with investable_reduction. X is the returns matrix of the reduced pr, and N its number of assets.
  6. Cluster the assets with opt.cle, giving clr, and cut its dendrogram into clr.k clusters, giving cls, the asset indices of each cluster.
  7. Compute the shares w and the cluster risks rkcl with herc_risk.
  8. Build the nodes nd of the dendrogram with to_tree. The cut does the first N - clr.k merges in the order of their heights, as Clustering.cutree does, so the other clr.k - 1 merges are the nodes above the cut.
  9. For each node above the cut, read the assets ln and rn of its two branches, and the clusters lc and rc inside them.
  10. Form the split factor alpha from the risks of lc and rc. Multiply w[ln] by alpha and w[rn] by 1 - alpha.
  11. Resolve the weight bounds wb from opt.wb and opt.sets. Divide w by its sum, and apply the weight finaliser opt.wf with finalise_weight_bounds, giving retcode and the final w.
  12. Return a HierarchicalEqualRiskContributionResult. Its HierarchicalResult expands w back onto the full asset universe through imsk.

Arguments

  • hec: The hierarchical equal risk contribution optimiser to use.
  • rd: The returns result to use. If isa(hec.opt.pe, AbstractPriorResult), a standalone optimisation does not need rd, 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. When opt.cle holds a clustering result, the order has no effect.
  • rmsk: The mask of a fit again after a refusal, or nothing on the first fit.
  • kwargs: Keyword arguments that the method accepts and does not read.

Related

source

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