API introduction
This section explains PortfolioOptimisers.jl API in detail. The pages are organised in exactly the same way as the src folder itself. This means there should be a 1 to 1 correspondence between documentation and source files[1].
Design philosophy
There are three overarching design choices in PortfolioOptimisers.jl:
1. Well-defined type hierarchies
- Easily and quickly add new features by sticking to defined interfaces.
2. Strongly typed immutable structs
All types are concrete and known at instantiation.
Constants can be propagated if necessary.
There is always a single immutable source of truth for every process.
If needed, modifying values must be done via interface functions, which simplifies finding and fixing bugs. If the interface for modification is not provided the code will throw a missing method exception.
3. Compositional design
PortfolioOptimisers.jlis a toolkit whose components can interact in complex, deeply nested ways.Separation of concerns lets us subdivide logical components into isolated, self-contained units. Leading to easier and fearless development and testing.
Extensive and judicious data validation checks are performed at the earliest possible moment–-mostly at variable instantiation–-to ensure correctness.
Turtles all the way down. Structures can be used, reused, and nested in many ways. This allows for efficient data reuse and arbitrary complexity.
Design goals
This philosophy has three primary goals:
1. Maintainability and expandability
The only way to break existing functionality should be by modifying APIs.
Adding functionality should be a case of subtyping existing abstract types and implementing the correct interfaces.
Avoid leaking side effects to other components unless completely necessary. An example of this is entropy pooling requiring the use of a vector of observation weights which must be taken into account in different, largely unrelated places.
2. Correctness and robustness
- Each subunit should perform its own data validation as early as possible unless it absolutely needs downstream data.
3. Performance
Types and constants are always fully known at inference time.
Immutability ensures smaller structs live in the stack.
Features
This section is under active development so any [<name>]-(@ref) lacks docstrings.
Preprocessing
Prices to returns
prices_to_returnsandReturnsResultFind complete indices
find_complete_indicesFind uncorrelated indices
find_uncorrelated_indices
Matrix processing
Denoising
Denoise,denoise!,denoiseSpectral
SpectralDenoiseFixed
FixedDenoiseShrunk
ShrunkDenoise
Matrix processing pipeline
DenoiseDetoneAlgMatrixProcessing,matrix_processing!,matrix_processing,DenoiseDetoneAlg,DenoiseAlgDetone,DetoneDenoiseAlg,DetoneAlgDenoise,AlgDenoiseDetone,AlgDetoneDenoise
Regression models
Factor prior models and implied volatility use regression in their estimation, which return a Regression object.
Regression targets
Linear model
LinearModelGeneralised linear model
GeneralisedLinearModel
Regression types
Stepwise
StepwiseRegressionDimensional reduction with custom mean and variance estimators
DimensionReductionRegression
Moment estimation
Expected returns
Overloads Statistics.mean.
Optionally weighted expected returns
SimpleExpectedReturnsEquilibrium expected returns with custom covariance
EquilibriumExpectedReturnsExcess expected returns with custom expected returns estimator
ExcessExpectedReturnsShrunk expected returns with custom expected returns and custom covariance estimators
ShrunkExpectedReturnsAlgorithms
James-Stein
JamesSteinBayes-Stein
BayesSteinBodnar-Okhrin-Parolya
BodnarOkhrinParolya
Targets: all algorithms can have any of the following targets
Grand Mean
GrandMeanVolatility Weighted
VolatilityWeightedMean Squared Error
MeanSquaredError
Standard deviation expected returns
StandardDeviationExpectedReturns
Variance and standard deviation
Overloads Statistics.var and Statistics.std.
- Optionally weighted variance with custom expected returns estimator
SimpleVariance
Covariance and correlation
Overloads Statistics.cov and Statistics.cor.
Optionally weighted covariance with custom covariance estimator
GeneralCovarianceCovariance with custom covariance estimator
CovarianceGerber covariances with custom variance and demeaning estimator
GerberCovarianceSmyth-Broby extension of Gerber covariances with custom expected returns and variance estimators
SmythBrobyCovarianceSmyth-Broby 0
SmythBroby0Smyth-Broby 1
SmythBroby1Smyth-Broby 2
SmythBroby2Smyth-Broby-Gerber 0
SmythBrobyGerber0Smyth-Broby-Gerber 1
SmythBrobyGerber1Smyth-Broby-Gerber 2
SmythBrobyGerber2Smyth-Broby-Count 0
SmythBrobyCount0Smyth-Broby-Count 1
SmythBrobyCount1Smyth-Broby-Count 2
SmythBrobyCount2
Gerber Information Quality
GerberIQCovariancewith custom variance, demeaning, temporal decay and numerator + denominator estimatorsBasic template
BasicGerberIQPartial template
PartialGerberIQFull template
FullGerberIQ
Distance covariance with custom distance estimator via
Distances.jlDistanceCovarianceLower Tail Dependence covariance
LowerTailDependenceCovarianceRank covariances
Kendall covariance
KendallCovarianceSpearman covariance
SpearmanCovariance
Mutual information covariance with custom variance estimator and various binning algorithms
MutualInfoCovarianceAstroPy-defined binsKnuth's optimal bin width
KnuthFreedman Diaconis bin width
FreedmanDiaconisScott's bin width
Scott
Hacine-Gharbi-Ravier bin width
HacineGharbiRavierPredefined number of bins
Denoised covariance with custom covariance estimator
DenoiseCovarianceDetoned covariance with custom covariance estimator
DetoneCovarianceCustom processed covariance with custom covariance estimator
ProcessedCovarianceImplied volatility with custom covariance and matrix processing estimators, and implied volatility algorithms
ImpliedVolatilityPremium
ImpliedVolatilityPremiumRegression
ImpliedVolatilityRegression
Covariance with custom covariance estimator and matrix processing pipeline
PortfolioOptimisersCovarianceCorrelation covariance
CorrelationCovariance
Coskewness
Implements coskewness.
Coskewness and spectral decomposition of the negative coskewness with custom expected returns estimator and matrix processing pipeline
Coskewness
Cokurtosis
Implements cokurtosis.
Cokurtosis with custom expected returns estimator and matrix processing pipeline
Cokurtosis
Distance matrices
Implements distance and cor_and_dist.
First order distance estimator with custom distance algorithm, and optional exponent
DistanceSecond order distance estimator with custom pairwise distance algorithm from
Distances.jl, custom distance algorithm, and optional exponentDistanceDistance
The distance estimators are used together with various distance matrix algorithms.
Simple distance
SimpleDistanceSimple absolute distance
SimpleAbsoluteDistanceLogarithmic distance
LogDistanceCorrelation distance
CorrelationDistanceVariation of Information distance with various binning algorithms
VariationInfoDistanceAstroPy-defined binsKnuth's optimal bin width
KnuthFreedman Diaconis bin width
FreedmanDiaconisScott's bin width
Scott
Hacine-Gharbi-Ravier bin width
HacineGharbiRavierPredefined number of bins
Canonical distance
CanonicalDistance
Phylogeny
PortfolioOptimisers.jl can make use of asset relationships to perform optimisations, define constraints, and compute relatedness characteristics of portfolios.
Clustering
Phylogeny constraints and clustering optimisations make use of clustering algorithms via ClustersEstimator, Clusters, and clusterise. Most clustering algorithms come from Clustering.jl.
Automatic choice of number of clusters via
OptimalNumberClustersandVectorToScalarMeasureSecond order difference
SecondOrderDifferenceSilhouette scores
SilhouetteScorePredefined number of clusters.
Hierarchical
Hierarchical clustering
HClustAlgorithmDirect Bubble Hierarchical Trees
DBHTand Local Global sparsification of the covariance matrixLoGo,logo!, andlogo
Non-hierarchical
Non-hierarchical clustering algorithms are incompatible with hierarchical clustering optimisations, but they can be used for phylogeny constraints and NestedClustered optimisations.
- K-means clustering
KMeansAlgorithm
Networks
Adjacency matrices
Adjacency matrices encode asset relationships either with clustering or graph theory via phylogeny_matrix and PhylogenyResult.
Network adjacency
NetworkEstimatorwith custom tree algorithms, covariance, and distance estimatorsMinimum spanning trees
KruskalTree,BoruvkaTree,PrimTreeTriangulated Maximally Filtered Graph with various similarity matrix estimators
Maximum distance similarity
MaximumDistanceSimilarityExponential similarity
ExponentialSimilarityGeneral exponential similarity
GeneralExponentialSimilarity
Clustering adjacency
ClustersEstimatorandClusters
Centrality and phylogeny measures
Centrality estimator
CentralityEstimatorwith custom adjacency matrix estimators (clustering and network) and centrality measuresBetweenness
BetweennessCentralityCloseness
ClosenessCentralityDegree
DegreeCentralityEigenvector
EigenvectorCentralityKatz
KatzCentralityPagerank
PagerankRadiality
RadialityCentralityStress
StressCentrality
Centrality vector
centrality_vectorAverage centrality
average_centralityThe asset phylogeny score
asset_phylogeny
Optimisation constraints
Non clustering optimisers support a wide range of constraints, while naive and clustering optimisers only support weight bounds. Furthermore, entropy pooling prior supports a variety of views constraints. It is therefore important to provide users with the ability to generate constraints manually and/or programmatically. We therefore provide a wide, robust, and extensible range of types such as AbstractEstimatorValueAlgorithm and UniformValues, and functions that make this easy, fast, and safe.
Constraints can be defined via their estimators or directly by their result types. Some using estimators need to map key-value pairs to the asset universe, this is done by defining the assets and asset groups in AssetSets. Internally, PortfolioOptimisers.jl uses all the information and calls group_to_val!, and replace_group_by_assets to produce the appropriate arrays.
Equation parsing
parse_equationandParsingResult.Linear constraints
linear_constraints,LinearConstraintEstimator,PartialLinearConstraint, andLinearConstraintRisk budgeting constraints
risk_budget_constraints,RiskBudgetEstimator, andRiskBudgetPhylogeny constraints
phylogeny_constraints,centrality_constraints,SemiDefinitePhylogenyEstimator,SemiDefinitePhylogeny,IntegerPhylogenyEstimator,IntegerPhylogeny,CentralityConstraintWeight bounds constraints
weight_bounds_constraints,WeightBoundsEstimator,WeightBoundsAsset set matrices
asset_sets_matrixandAssetSetsMatrixEstimatorThreshold constraints
threshold_constraints,ThresholdEstimator, andThreshold
Prior statistics
Many optimisations and constraints use prior statistics computed via prior.
Low order prior
LowOrderPriorEmpirical
EmpiricalPriorFactor model
FactorPriorBlack-Litterman
Vanilla
BlackLittermanPriorBayesian
BayesianBlackLittermanPriorFactor model
FactorBlackLittermanPriorAugmented
AugmentedBlackLittermanPrior
Entropy pooling
EntropyPoolingPriorOpinion pooling
OpinionPoolingPrior
High order prior
HighOrderPriorHigh order
HighOrderPriorEstimatorHigh order factor model
HighOrderFactorPriorEstimator
Uncertainty sets
In order to make optimisations more robust to noise and measurement error, it is possible to define uncertainty sets on the expected returns and covariance. These can be used in optimisations which use either of these two quantities. These are implemented via ucs, mu_ucs, and sigma_ucs.
PortfolioOptimisers.jl implements two types of uncertainty sets.
EllipsoidalUncertaintySetandEllipsoidalUncertaintySetAlgorithmwith various algorithms for computing the scaling parameter viak_ucsPredefined scaling parameter
It also implements various estimators for the uncertainty sets, the following two can generate box and ellipsoidal sets.
Normally distributed returns
NormalUncertaintySetBootstrapping via Autoregressive Conditional Heteroscedasticity
ARCHUncertaintySetviaarchCircular
CircularBootstrapMoving
MovingBootstrapStationary
StationaryBootstrap
The following estimator can only generate box sets.
Turnover
The turnover is defined as the element-wise absolute difference between the vector of current weights and a vector of benchmark weights. It can be used as a constraint, method for fee calculation, and risk measure. These are all implemented using turnover_constraints, TurnoverEstimator, and Turnover.
Fees
Fees are a non-negligible aspect of active investing. As such PortfolioOptimiser.jl has the ability to account for them in all optimisations but the naive ones. They can also be used to adjust expected returns calculations via calc_fees and calc_asset_fees.
Fees
FeesEstimatorandFeesProportional long
Proportional short
Fixed long
Fixed short
Turnover
Portfolio returns and drawdowns
Various risk measures and analyses require the computation of simple and cumulative portfolio returns and drawdowns both in aggregate and per-asset. These are computed by calc_net_returns, calc_net_asset_returns, cumulative_returns, drawdowns.
Tracking
It is often useful to create portfolios that track the performance of an index, indicator, or another portfolio.
Tracking error
tracking_benchmark,TrackingErrorReturns tracking
ReturnsTrackingWeights tracking
WeightsTracking
The error can be computed using different algorithms using norm_tracking.
Norm tracking algorithms
L1-norm
L1TrackingL2-norm
L2TrackingL2-norm squared
SquaredL2TrackingLp-norm
LpTrackingL-Inf-norm
LInfTracking
It is also possible to track the error in with risk measures RiskTrackingError using WeightsTracking, which allows for two approaches.
Dependent variable tracking
DependentVariableTrackingIndependent variable tracking
IndependentVariableTracking
Risk measures
PortfolioOptimisers.jl provides a wide range of risk measures. These are broadly categorised into two types based on the type of optimisations that support them.
Risk measures for traditional optimisation
These are all subtypes of RiskMeasure, and are supported by all optimisation estimators.
Variance [
Variance]Traditional optimisations also support:
Risk contribution
Formulations
Quadratic risk expression
QuadRiskExprSquared second order cone
SquaredSOCRiskExpr
Standard deviation
StandardDeviationUncertainty set variance
UncertaintySetVariance(same as variance when used in non-traditional optimisation)Low order moments
LowOrderMomentFirst lower moment
FirstLowerMomentMean absolute deviation
MeanAbsoluteDeviationSecond moment
SecondMomentSecond squared moments
Scenario variance
FullScenario semi-variance
SemiTraditional optimisation formulations
Quadratic risk expression
QuadRiskExprSquared second order cone
SquaredSOCRiskExprRotated second order cone
RSOCRiskExpr
Second moments
SOCRiskExpr
Kurtosis
KurtosisActual kurtosis
Traditional optimisation formulations
Quadratic risk expression
QuadRiskExprSquared second order cone
SquaredSOCRiskExprRotated second order cone
RSOCRiskExpr
Square root kurtosis
SOCRiskExpr
Negative skewness
NegativeSkewnessSquared negative skewness
Traditional optimisation formulations
Quadratic risk expression
QuadRiskExprSquared second order cone
SquaredSOCRiskExpr
Square root negative skewness
SOCRiskExpr
Value at Risk
ValueatRiskTraditional optimisation formulations
Exact MIP formulation
MIPValueatRiskApproximate distribution based
DistributionValueatRisk
Value at Risk Range
ValueatRiskRangeTraditional optimisation formulations
Exact MIP formulation
MIPValueatRiskApproximate distribution based
DistributionValueatRisk
Drawdown at Risk
DrawdownatRiskConditional Value at Risk
ConditionalValueatRiskDistributionally Robust Conditional Value at Risk
DistributionallyRobustConditionalValueatRisk(same as conditional value at risk when used in non-traditional optimisation)Conditional Value at Risk Range
ConditionalValueatRiskRangeDistributionally Robust Conditional Value at Risk Range
DistributionallyRobustConditionalValueatRiskRange(same as conditional value at risk range when used in non-traditional optimisation)Conditional Drawdown at Risk
ConditionalDrawdownatRiskDistributionally Robust Conditional Drawdown at Risk
DistributionallyRobustConditionalDrawdownatRisk(same as conditional drawdown at risk when used in non-traditional optimisation)Entropic Value at Risk
EntropicValueatRiskEntropic Value at Risk Range
EntropicValueatRiskRangeEntropic Drawdown at Risk
EntropicDrawdownatRiskRelativistic Value at Risk
RelativisticValueatRiskRelativistic Value at Risk Range
RelativisticValueatRiskRangeRelativistic Drawdown at Risk
RelativisticDrawdownatRiskOrdered Weights Array
Risk measures
Ordered Weights Array risk measure
OrderedWeightsArrayOrdered Weights Array range risk measure
OrderedWeightsArrayRange
Traditional optimisation formulations
Exact
ExactOrderedWeightsArrayApproximate
ApproxOrderedWeightsArray
Array functions
Gini Mean Difference
owa_gmdWorst Realisation
owa_wrRange
owa_rgConditional Value at Risk
owa_cvarWeighted Conditional Value at Risk
owa_wcvarConditional Value at Risk Range
owa_cvarrgWeighted Conditional Value at Risk Range
owa_wcvarrgTail Gini
owa_tgTail Gini Range
owa_tgrgLinear moments (L-moments)
Linear Moment
owa_l_momentLinear Moment Convex Risk Measure
owa_l_moment_crmL-moment combination formulations
Maximum Entropy
MaximumEntropyExponential Cone Entropy
ExponentialConeEntropyRelative Entropy
RelativeEntropy
Minimum Squared Distance
MinimumSquaredDistanceMinimum Sum Squares
MinimumSumSquares
Average Drawdown
AverageDrawdownUlcer Index
UlcerIndexMaximum Drawdown
MaximumDrawdownBrownian Distance Variance
BrownianDistanceVarianceTraditional optimisation formulations
Distance matrix constraint formulations
Norm one cone Brownian distance variance
NormOneConeBrownianDistanceVarianceInequality Brownian distance variance
IneqBrownianDistanceVariance
Risk formulation
Quadratic risk expression
QuadRiskExprRotated second order cone
RSOCRiskExpr
Worst Realisation
WorstRealisationRange
RangeTurnover Risk Measure
TurnoverRiskMeasureTracking Risk Measure
TrackingRiskMeasureL1-norm
L1TrackingL2-norm
L2TrackingL2-norm squared
SquaredL2TrackingLp-norm
LpTrackingL-Inf-norm
LInfTracking
Risk Tracking Risk Measure
Dependent variable tracking
DependentVariableTrackingIndependent variable tracking
IndependentVariableTracking
Power Norm Value at Risk
PowerNormValueatRiskPower Norm Value at Risk Range
PowerNormValueatRiskRangePower Norm Drawdown at Risk
PowerNormDrawdownatRisk
Risk measures for hierarchical optimisation
These are all subtypes of HierarchicalRiskMeasure, and are only supported by hierarchical optimisation estimators.
High order moment
HighOrderMomentUnstandardised third lower moment
ThirdLowerMomentStandardised third lower moment
StandardisedHighOrderMomentandThirdLowerMomentUnstandardised fourth moment
FourthMomentStandardised fourth moment
StandardisedHighOrderMomentandFourthMoment
Relative Drawdown at Risk
RelativeDrawdownatRiskRelative Conditional Drawdown at Risk
RelativeConditionalDrawdownatRiskRelative Entropic Drawdown at Risk
RelativeEntropicDrawdownatRiskRelative Relativistic Drawdown at Risk
RelativeRelativisticDrawdownatRiskRelative Average Drawdown
RelativeAverageDrawdownRelative Ulcer Index
RelativeUlcerIndexRelative Maximum Drawdown
RelativeMaximumDrawdownRelative Power Norm Drawdown at Risk
RelativePowerNormDrawdownatRiskRisk Ratio Risk Measure
RiskRatioRiskMeasureEqual Risk Measure
EqualRiskMeasureMedian Absolute Deviation
MedianAbsoluteDeviation
Non-optimisation risk measures
These risk measures are unsuitable for optimisation because they can return negative values. However, they can be used for performance metrics.
Mean Return
MeanReturnThird Central Moment [
ThirdCentralMoment]-@(ref)Skewness
SkewnessReturn Risk Measure
ExpectedReturnReturn Risk Ratio Risk Measure
ExpectedReturnRiskRatio
Performance metrics
Expected risk
expected_riskNumber of effective assets
number_effective_assetsRisk contribution
Asset risk contribution
risk_contributionFactor risk contribution
factor_risk_contribution
Expected return
expected_returnArithmetic
ArithmeticReturnLogarithmic
LogarithmicReturn
Expected risk-adjusted return ratio
expected_ratioandexpected_risk_ret_ratioExpected risk-adjusted ratio information criterion
expected_sricandexpected_risk_ret_sricBrinson performance attribution
brinson_attribution
Portfolio optimisation
Optimisations are implemented via optimise. Optimisations consume an estimator and return a result.
Naive
These return a NaiveOptimisationResult.
Inverse Volatility
InverseVolatilityEqual Weighted
EqualWeightedRandom (Dirichlet)
RandomWeighted
Naive optimisation features
Weight bounds
WeightBoundsEstimator,UniformValues, andWeightBoundsWeight finalisers
Iterative Weight Finaliser
IterativeWeightFinaliserJuMP Weight Finaliser
JuMPWeightFinaliserRelative Error Weight Finaliser
RelativeErrorWeightFinaliserSquared Relative Error Weight Finaliser
SquaredRelativeErrorWeightFinaliserAbsolute Error Weight Finaliser
AbsoluteErrorWeightFinaliserSquared Absolute Error Weight Finaliser
SquaredAbsoluteErrorWeightFinaliser
Traditional
These optimisations are implemented as JuMP problems and make use of JuMPOptimiser, which encodes all supported constraints.
Objective function optimisations
These optimisations support a variety of objective functions.
Objective functions
Minimum risk
MinimumRiskMaximum utility
MaximumUtilityMaximum return over risk ratio
MaximumRatioMaximum return
MaximumReturn
Exclusive to
MeanRiskandNearOptimalCenteringN-dimensional Pareto fronts
FrontierReturn based
Risk based
Optimisation estimators
Mean-Risk
MeanRiskreturns aMeanRiskResultNear Optimal Centering
NearOptimalCenteringreturns aNearOptimalCenteringResultFactor Risk Contribution
FactorRiskContributionreturns aFactorRiskContributionResult
Risk budgeting optimisations
These optimisations attempt to achieve weight values according to a risk budget vector. This vector can be provided on a per asset or per factor basis.
Budget targets
Asset risk budgeting
AssetRiskBudgetingFromulations
Log-barrier risk budgeting
LogRiskBudgetingMIP asset risk bugeting
MixedIntegerRiskBudgeting
Factor risk budgeting
FactorRiskBudgeting
Optimisation estimators
Risk Budgeting
RiskBudgetingreturns aRiskBudgetingResultRelaxed Risk Budgeting
RelaxedRiskBudgetingreturns aRiskBudgetingResultRegularised
RegularisedRelaxedRiskBudgetingRegularised and penalised
RegularisedPenalisedRelaxedRiskBudgeting
Traditional optimisation features
Custom objective penalty
CustomJuMPObjectiveWeight bounds
WeightBoundsEstimator,UniformValues, andWeightBoundsBudget
Directionality
Long
Short
Type
Exact
Range
BudgetRange
Threshold
ThresholdEstimatorandThresholdDirectionality
Long
Short
Type
Asset
Linear constraints
LinearConstraintEstimatorandLinearConstraintCentralit(y/ies)
CentralityEstimatorCardinality
Asset
Asset group(s)
LinearConstraintEstimatorandLinearConstraintSet(s)
Set group(s)
LinearConstraintEstimatorandLinearConstraint
Turnover(s)
TurnoverEstimatorandTurnoverFees
FeesEstimatorandFeesTracking error(s)
TrackingErrorPhylogen(y/ies)
IntegerPhylogenyEstimatorandSemiDefinitePhylogenyEstimatorPortfolio returns
Arithmetic returns
ArithmeticReturnUncertainty set
BoxUncertaintySet,BoxUncertaintySetAlgorithm,EllipsoidalUncertaintySet, andEllipsoidalUncertaintySetAlgorithmCustom expected returns vector
Logarithmic returns
LogarithmicReturn
Risk vector scalarisation
Weighted sum
SumScalariserMaximum value
MaxScalariserLog-sum-exp
LogSumExpScalariser
Custom constraint
Number of effective assets
Regularisation penalty
L1
L2
L-Inf
Clustering optimisation
Clustering optimisations make use of asset relationships to either minimise the risk exposure by breaking the asset universe into subsets which are hierarchically or individually optimised.
Hierarchical clustering optimisation
These optimisations minimise risk by hierarchically splitting the asset universe into subsets, computing the risk of each subset, and combining them according to their hierarchy.
Hierarchical Risk Parity
HierarchicalRiskParityreturns aHierarchicalResultHierarchical Equal Risk Contribution
HierarchicalEqualRiskContributionreturns aHierarchicalResult
Hierarchical clustering optimisation features
Weight bounds
WeightBoundsEstimator,UniformValues, andWeightBoundsFees
FeesEstimatorandFeesRisk vector scalarisation
Weighted sum
SumScalariserMaximum value
MaxScalariserLog-sum-exp
LogSumExpScalariser
Weight finalisers
Iterative Weight Finaliser
IterativeWeightFinaliserJuMP Weight Finaliser
JuMPWeightFinaliserRelative Error Weight Finaliser
RelativeErrorWeightFinaliserSquared Relative Error Weight Finaliser
SquaredRelativeErrorWeightFinaliserAbsolute Error Weight Finaliser
AbsoluteErrorWeightFinaliserSquared Absolute Error Weight Finaliser
SquaredAbsoluteErrorWeightFinaliser
Schur complementary optimisation
Schur complementary hierarchical risk parity provides a bridge between mean variance optimisation and hierarchical risk parity by using an interpolation parameter. It converges to hierarchical risk parity, and approximates mean variance by adjusting this parameter. It uses the Schur complement to adjust the weights of a portfolio according to how much more useful information is gained by assigning more weight to a group of assets.
- Schur Complementary Hierarchical Risk Parity
SchurComplementHierarchicalRiskParityreturns aSchurComplementHierarchicalRiskParityResult
Schur complementary optimisation features
Weight bounds
WeightBoundsEstimator,UniformValues, andWeightBoundsFees
FeesEstimatorandFeesWeight finalisers
Iterative Weight Finaliser
IterativeWeightFinaliserJuMP Weight Finaliser
JuMPWeightFinaliserRelative Error Weight Finaliser
RelativeErrorWeightFinaliserSquared Relative Error Weight Finaliser
SquaredRelativeErrorWeightFinaliserAbsolute Error Weight Finaliser
AbsoluteErrorWeightFinaliserSquared Absolute Error Weight Finaliser
SquaredAbsoluteErrorWeightFinaliser
Nested clusters optimisation
Nested clustered optimisation breaks the asset universe of size N into C smaller subsets and treats every subset as an individual portfolio. The weights assigned to each asset are placed in an N × C matrix. In each column, non-zero values correspond to assets assigned to that subset, this means that assets only contribute to the column (and therefore synthetic asset) corresponding to their assigned subset. In other words, each row of the matrix contains a single non-zero value and each row contains as many non-zero values as there are assets in that subset.
From here there are two options:
Compute the returns matrix of the synthetic assets directly by multiplying the original
T × Nmatrix by theN × Cmatrix of asset weights to produce aT × Cmatrix of predicted returns, whereTis the number of observations.For each subset perform a cross validation prediction, yielding a vector of returns for that subset. These vectors are then horizontally concatenated into a
Y × Cmatrix of cross-validation predicted returns, whereY ≤ Tbecause the cross validation may not use the full history.
This matrix of predicted returns is then used by the outer optimisation estimator to generate an optimisation of the synthetic assets. This produces a C × 1 vector, essentially optimising a portfolio of asset clusters. The final weights are the product of the original N × C matrix of asset weights per cluster by the C × 1 vector of optimal synthetic asset weights to produce the final N × 1 vector of asset weights.
- Nested Clustered
NestedClusteredreturns aNestedClusteredResult
Nested clusters optimisation features
Any features supported by the inner and outer estimators.
Weight bounds
WeightBoundsEstimator,UniformValues, andWeightBoundsFees
FeesEstimatorandFeesWeight finalisers
Iterative Weight Finaliser
IterativeWeightFinaliserJuMP Weight Finaliser
JuMPWeightFinaliserRelative Error Weight Finaliser
RelativeErrorWeightFinaliserSquared Relative Error Weight Finaliser
SquaredRelativeErrorWeightFinaliserAbsolute Error Weight Finaliser
AbsoluteErrorWeightFinaliserSquared Absolute Error Weight Finaliser
SquaredAbsoluteErrorWeightFinaliser
Cross validation predictor for the outer estimator
Ensemble optimisation
This works similarly to the Nested Clustered estimator, only instead of breaking the asset universe into subsets, a list of inner estimators is provided. The procedure is then exactly the same as the nested clusters optimisation, only instead of an N × C matrix of asset weights where each column corresponds to a subset of assets, each column corresponds to a completely independent and isolated inner estimator, which also means there is no enforced sparsity pattern on this matrix.
- Stacking
Stackingreturns aStackingResult
Ensemble optimisation features
Any features supported by the inner and outer estimators.
Fees
FeesEstimatorandFeesWeight bounds
WeightBoundsEstimator,UniformValues, andWeightBoundsWeight finalisers
Iterative Weight Finaliser
IterativeWeightFinaliserJuMP Weight Finaliser
JuMPWeightFinaliserRelative Error Weight Finaliser
RelativeErrorWeightFinaliserSquared Relative Error Weight Finaliser
SquaredRelativeErrorWeightFinaliserAbsolute Error Weight Finaliser
AbsoluteErrorWeightFinaliserSquared Absolute Error Weight Finaliser
SquaredAbsoluteErrorWeightFinaliser
Cross validation predictor for the outer estimator
Subset resampling optimisation
This optimiser takes ideas from MultipleRandomised cross validation to randomly sample the asset universe and optimise each sample individually using a given optimiser. The final asset weights are the average weight per asset across all samples, if an asset does not appear in a sample, it is taken to be zero.
SubsetResamplingreturns aSubsetResamplingResult
Subset resampling optimisation features
Any features supported by the inner estimator.
Fees
FeesEstimatorandFeesWeight bounds
WeightBoundsEstimator,UniformValues, andWeightBoundsWeight finalisers
Iterative Weight Finaliser
IterativeWeightFinaliserJuMP Weight Finaliser
JuMPWeightFinaliserRelative Error Weight Finaliser
RelativeErrorWeightFinaliserSquared Relative Error Weight Finaliser
SquaredRelativeErrorWeightFinaliserAbsolute Error Weight Finaliser
AbsoluteErrorWeightFinaliserSquared Absolute Error Weight Finaliser
SquaredAbsoluteErrorWeightFinaliser
Finite allocation optimisation
Unlike all other estimators, finite allocation does not yield an "optimal" value, but rather the optimal attainable solution based on a finite amount of capital. They use the result of other estimations, the latest prices, and a cash amount.
Discrete (MIP)
DiscreteAllocationWeight finalisers
Iterative Weight Finaliser
IterativeWeightFinaliserJuMP Weight Finaliser
JuMPWeightFinaliserRelative Error Weight Finaliser
RelativeErrorWeightFinaliserSquared Relative Error Weight Finaliser
SquaredRelativeErrorWeightFinaliserAbsolute Error Weight Finaliser
AbsoluteErrorWeightFinaliserSquared Absolute Error Weight Finaliser
SquaredAbsoluteErrorWeightFinaliser
Greedy [
GreedyAllocation]
Cross validation
Prediction on unseen data
PredictionReturnsResult,PredictionResult,MultiPeriodPredictionResult,PopulationPredictionResultviapredict(res::NonFiniteAllocationOptimisationResult, rd::ReturnsResult),fit_and_predictPrediction scoring via
PredictionCrossValScorer,NearestQuantilePrediction, andquantile_by_measureCross validation estimators used via
splitandfit_and_predictK-Fold
KFoldreturns aKFoldResultCombinatorial
CombinatorialCrossValidationreturns aCombinatorialCrossValidationResultWalk forward
WalkForwardEstimatorreturn aWalkForwardResult- Index-based
IndexWalkForward,DateWalkForward
- Index-based
Multiple randomised
MultipleRandomisedreturns aMultipleRandomisedResult
Hyperparameter tuning via
search_cross_validation.Grid search cross validation
GridSearchCrossValidationRandomised search cross validation
RandomisedSearchCrossValidation
Plotting
Visualising the results is quite a useful way of summarising the portfolio characteristics or evolution. To this extent we provide a few plotting functions with more to come.
Simple or compound cumulative returns.
Portfolio
plot_ptf_cumulative_returns.Assets
plot_asset_cumulative_returns.
Portfolio composition.
Single portfolio
plot_composition.Multi portfolio.
Stacked bar
plot_stacked_bar_composition.Stacked area
plot_stacked_area_composition.
Risk contribution.
Asset risk contribution
plot_risk_contribution.Factor risk contribution
plot_factor_risk_contribution.
Asset dendrogram
plot_dendrogram.Asset clusters + optional dendrogram
plot_clusters.Simple or compound drawdowns
plot_drawdowns.Portfolio returns histogram + density
plot_histogram.2/3D risk measure scatter plots
plot_measures.
Except for a few cases, most of which are convenience function overloads. This means some links do not go to the exact method definition. Other than hard-coding links to specific lines of code, which is fragile, I haven't found an easy solution. ↩︎