Capability catalogue
Everything PortfolioOptimisers.jl can do, grouped by the job it does rather than by the file it lives in. Each entry links to its docstring. Every entry here is public API: test_26_docs.jl's "every exported function is accounted for" testset makes that true by construction (ADR 0040), so the page needs no per-entry marker.
This page is generated (see docs/generatecapabilitycatalogue.jl): the grouping is curated in docs/capability_catalogue.jl, and every description is the first sentence of the corresponding docstring, so the two can never disagree. A test asserts that every estimator and algorithm in the package appears here, so the page cannot fall behind the code.
For the same types arranged by subtyping rather than by capability, see the type hierarchy.
Core abstractions
Every component is an Estimator (a configuration encoding a method and its hyperparameters), an Algorithm (a behaviour selector consumed through an Estimator), or a Result (computed output). Estimators and Algorithms are what you choose; Results are what you get back.
Because every struct is immutable, runtime values are propagated down a composed estimator tree by rebuilding it.
- No-op factory function for constructing objects with a uniform interface.
factory
Preprocessing
- Compute returns from the price carrier, and nothing else.
prices_to_returnsandReturnsResult - A container for aligned, time-indexed price-level data.
PricesResult
Preprocessing estimator converting price-level data into returns-level data. PricesToReturns, fit_preprocessing, and apply_preprocessing
PricesToReturns, fit_preprocessing, and apply_preprocessing- Preprocessing estimator dropping assets and observations with excessive missing data from price-level data.
MissingDataFilterandMissingDataFilterResult
Price gap conventions
- Fills the price gaps inside an asset's listing with a stated convention, and touches nothing outside it.
PriceGapFillandPriceGapFillResult - States that a price did not move across a gap, so the last priced observation is held forward.
CarriedPrice
Gap Return conventions
- Books a Held Gap's whole move on the observation that ends it, shortening the gap to
k.CatchUpGapReturn
Asset selection
- Asset selector that scores every asset with a risk measure and keeps the assets a rule admits.
ScoreSelector,ZeroVarianceFilter, andCompleteAssetSelector - Asset selector that discards assets which duplicate information already carried by others.
RedundancySelector - Fitted result of any
AbstractAssetSelector.AssetSelectorResult
Selection rules
RankRulewith the tail sizes given as fractions of the asset universe.QuantileRule- Take
bestand/orworstassets from the tails of the score ordering, then keep or drop them.RankRule - Keep assets whose score falls strictly inside the band
(lo, hi).ThresholdRule
The universe a price panel states
A gap's position in a price column says which universe it implies: a leading run is an asset not yet listed, a trailing run is a delisting, and an interior gap is a suspension on an asset that is still listed. listing_span reads that rule off bare prices and universe_masks projects it onto the returns clock, giving the two masks an AssetPanel carries; a caller's own listing calendar enters at the same point and replaces the derived answer outright.
- Derive the Listing Span of every asset column of a price panel by the Span Rule.
listing_spananduniverse_masks
The ingestion layer
PriceIngestion assembles raw price series into the carrier the conversion reads, running once on the whole panel rather than as a Pipeline step, because unification, the join and the collapse each move the observation clock — and because the Span Rule needs the whole panel, which a step, seeing only a window, cannot give it. The carrier it emits holds the Listing Span, and PricesToReturns projects that onto the returns clock and hands the ReturnsResult an AssetPanel stating the universe: always, a gapless table included, so a returns carrier holding no panel is one built outside the layer.
- Estimator assembling raw price series into the span-carrying price carrier the ingestion layer converts.
PriceIngestionandprice_ingestion
- Cut price- or returns-level data into a training window (the head) and a held-out test window (the tail).
train_test_split,TrainTestSplit, andTrainTestSplitResult - Return a
ReturnsResultappropriate for benchmark-tracking optimisations.returns_result_picker
Build the AssetPanel a carrier holds, from the raw, blank-carrying form of each Panel Field. asset_panel, AssetPanel, panel_field, panel_feature_matrix, panel_dataframe, feature_matrix, feature_labels, and panel_input
AssetPanel a carrier holds, from the raw, blank-carrying form of each Panel Field. asset_panel, AssetPanel, panel_field, panel_feature_matrix, panel_dataframe, feature_matrix, feature_labels, and panel_inputPanel Field kinds
- A Panel Field holding one number per asset, and per observation when it is time-varying.
NumericPanelField - A Panel Field holding one category label per asset, and per observation when it is time-varying.
CategoricalPanelField - A Panel Field whose trailing axis carries its own labels, and optionally its own groups.
TensorPanelField
Panel Field inputs
- Raw form of a Panel Field holding one numeric quantity per observation and asset.
NumericPanelInput - Raw form of a Panel Field holding one category label per observation and asset.
CategoricalPanelInput - Raw form of a Panel Field whose third axis carries its own labels, and optionally its own groups.
TensorPanelInput
Blank-cell policies
- Refuses a blank cell instead of resolving one.
NoPanelFill - Resolves every blank cell to one constant.
ConstantPanelFill - Resolves a blank cell to the nearest earlier observed value of the same asset.
ForwardPanelFill - Resolves a blank cell to the nearest later observed value of the same asset.
BackwardPanelFill
Cross-sectional transforms
A cross-sectional transform rescales one observation against the other assets of that same observation, through cross_sectional_transform. The benchmark weights and the group labels are arguments of the call, and cross_sectional_groups derives the labels from a one-hot Panel Field.
Outlier treatments
- Clips every value of an observation into the band between two percentiles of that observation's cross-section.
CrossSectionalWinsoriser,cross_sectional_transform, andcross_sectional_groups - Compresses every value of an observation towards the centre of that observation's cross-section, through a hyperbolic tangent.
CrossSectionalTanhShrinker
Scoring transforms
- Scores every value of an observation as a cross-sectional z-score, optionally inside its own group first.
CrossSectionalStandardiser - Scores every value of an observation by the inverse normal of its cross-sectional percentile rank.
CrossSectionalGaussianRank - Scores every value of an observation by its percentile rank inside that observation's cross-section.
CrossSectionalPercentileRank
Matrix processing
- Projects a matrix to the nearest positive definite matrix, typically used for co-moment matrices.
Posdef,posdef!, andposdef
Configures and applies denoising algorithms to covariance or correlation matrices. Denoise, denoise!, and denoise
Denoise, denoise!, and denoise- Denoises by setting the noise eigenvalues to zero.
SpectralDenoise - Denoises by replacing the noise eigenvalues with their own mean.
FixedDenoise - Denoises by shrinking the off-diagonal part of the noise block towards zero, keeping its diagonal whole.
ShrunkDenoise
- Removes the largest
nprincipal components (market modes) from a covariance or correlation matrix.Detone,detone!, anddetone - Configures and applies matrix processing routines.
MatrixProcessing,matrix_processing!,matrix_processing_step!, andmatrix_processing
Regression models
Factor prior models and implied volatility use regression in their estimation, which return a Regression object.
Regression targets
- Fits each response by ordinary least squares through
GLM.LinearModel.LinearModel - Fits each response by a generalised linear model through
GLM.GeneralizedLinearModel.GeneralisedLinearModel
Regression types
Estimates a loadings matrix by selecting a factor subset per asset, one factor at a time. StepwiseRegression
StepwiseRegressionAlgorithms
- Grows the factor set from empty, adding the factor that most improves the criterion.
ForwardSelection - Shrinks the factor set from full, removing the factor whose removal most improves the criterion.
BackwardElimination
Selection criteria
- Selects factors by the statistical significance of their coefficients.
PValue :aic:aicc:bic:r2:adjr2
Estimates a loadings matrix by regressing each asset on the leading components of the factors. DimensionReductionRegression
DimensionReductionRegressionCross-sectional regression types
A cross-sectional regression fits one model per observation across the assets, and implements cross_sectional_regression, which returns a CrossSectionalRegression object. cross_sectional_r2 and mean_cross_sectional_r2 score a fit.
Fits one weighted least squares per observation across the assets, in closed form. CrossSectionalLinearRegression, cross_sectional_regression, cross_sectional_r2, and mean_cross_sectional_r2
CrossSectionalLinearRegression, cross_sectional_regression, cross_sectional_r2, and mean_cross_sectional_r2Rank deficiency policies
- Solves the full-rank design directly and pseudo-inverts a rank-deficient one.
PseudoInverseFallback - Solves the full-rank design directly and refuses a rank-deficient one.
RankDeficiencyRefusal - Runs no rank test and takes whatever
\returns.UncheckedSolve - Always pseudo-inverts, so it runs no rank test and takes no threshold.
MinimumNormSolve
- Fits one external regression model per observation across the assets.
CrossSectionalTargetRegression
Cross-sectional regression weight policies
A weight policy says what weight an asset carries in the cross-sectional fit of an observation. A one-pass policy reads the cross-section alone, and a two-pass policy reads the residuals of a first fit.
- Weights an asset by a power of its market capitalisation, in one pass.
MarketCapWeights - Blends market capitalisation weights with inverse idiosyncratic variance weights, in two passes.
BlendedInverseVarianceWeights
Cross-sectional regression diagnostics
A diagnostic of the cross-sectional fit reads the exposure history, the factor returns and the residuals, and answers a series over the observations or one value per factor. Every verb takes the lag-aligned histories as bare arrays, and takes a CrossSectionalFactorModel as well, which lags the exposures and maps them through a Factor Family Basis before it answers.
Return the weighted Gram history of a cross-sectional regression, one slice per observation. cs_gram
cs_gram- Return the variance inflation factor of every factor, one row per observation.
exposure_vif - Return the two-norm condition number of the cross-sectional design, one entry per observation.
exposure_condition_number
Fit quality.
- Return the weighted cross-sectional coefficient of determination, one entry per observation.
cs_regression_r2 - Return the cross-sectional coefficient of determination adjusted for the regressor count, one entry per observation.
cs_regression_adjusted_r2 - Return the Akaike information criterion of every cross-sectional fit, one entry per observation.
cs_regression_aic - Return the Bayesian information criterion of every cross-sectional fit, one entry per observation.
cs_regression_bic
Significance of a factor return.
- Return the t-statistic of every factor return, one row per observation.
cs_regression_t_stats - Return the fraction of observations at which a factor's t-statistic exceeds a threshold.
cs_regression_t_stat_exceedance_rate
Cross-sectional exposure diagnostics
A diagnostic of the exposure history reads the history as the Asset Panel wrote it, unlagged and on the raw factor axis, and answers a matrix over the factors, a series over the observations, or one value per factor. Every verb takes the history as bare arrays, and takes a CrossSectionalFactorModel as well, which resolves the cross-sectional weights from an AbstractOrthogonalityMetric.
Redundancy and turnover of an exposure.
- Return the time-averaged correlation between every pair of factor exposures.
exposure_correlation - Return the stability of every factor exposure, one row per pair of observations.
exposure_stability
Reach and spread of an exposure.
- Return the weighted cross-sectional standard deviation of every factor exposure, one row per observation.
exposure_dispersion - Return the coverage of every factor exposure, one entry per factor.
exposure_coverage
Forecasting power of an exposure.
- Return the information coefficient of every factor exposure, one row per pair of observations.
exposure_ic - Return the summary of an information coefficient series, one entry per factor.
exposure_ic_summary
Cross-sectional idiosyncratic diagnostics
A diagnostic of the idiosyncratic returns divides each residual of the fit by the volatility the fit predicted for it, and reads the cross-section of the answer one observation at a time. Every verb takes the two histories as bare arrays, and takes a CrossSectionalFactorModel as well, which reads them off the block. Neither history carries a factor axis, so the group takes no lag and no family re-basis.
The kernel every series of the group reads.
- Return the standardised idiosyncratic returns of a cross-sectional fit.
standardised_idio_returns
Shape of the standardised cross-section.
- Return the cross-sectional standard deviation of the standardised idiosyncratic returns, one entry per observation.
idio_calibration - Return the share of assets whose standardised idiosyncratic return exceeds a threshold, one entry per observation.
idio_tail_rate - Return the cross-sectional excess kurtosis of the standardised idiosyncratic returns, one entry per observation.
idio_kurtosis - Return the cross-sectional skewness of the standardised idiosyncratic returns, one entry per observation.
idio_skewness - Return the five time-aggregated numbers of the calibration of a cross-sectional fit.
idio_calibration_summary
Ranking power of the predicted volatility.
- Return the information coefficient of the predicted idiosyncratic volatility, one entry per pair of observations.
idio_vol_ic - Return the rank correlation of the predicted idiosyncratic volatility against the next observation's standardised absolute idiosyncratic return, one entry per pair of observations.
idio_vol_residual_dependence
Factor model summary
The summary is the top of the diagnostic hierarchy. It calls one level-2 verb of the regression group and one of the exposure group per column, aggregates each series over the observations, and answers on the raw factor axis. A column that reads the exposure history is absent as a whole when the block carries none.
Summarise every factor of a cross-sectional factor model as a FactorSummaryResult. factor_model_summary
FactorSummaryResult. factor_model_summary- The headline statistics of every factor of a cross-sectional factor model.
FactorSummaryResult
Descriptors
A Descriptor Estimator maps the Panel Fields of an Asset Panel to one value per observation and asset through descriptor. Every named Descriptor is a constructor function that fixes the Panel Fields, the window, or the half-life of one archetype, and each accepts a keyword that overrides what it fixes.
Divides one Panel Field, or a combination of Panel Fields, by another at every observation. PanelFieldRatio
PanelFieldRatio- Book equity over market capitalisation, the value Descriptor.
BookToPrice - Trailing operating cash flow over market capitalisation, a value Descriptor.
CashFlowToPrice - Trailing sales over market capitalisation, a value Descriptor.
SalesToPrice - Trailing net income over market capitalisation, the earnings yield Descriptor.
EarningsToPrice - Forward earnings per share over the adjusted close, the forward earnings yield Descriptor.
ForwardEarningsToPrice - Trailing EBITDA over enterprise value, an earnings yield Descriptor that is neutral to the capital structure.
EbitdaToEnterpriseValue - Trailing common dividends over market capitalisation, the dividend yield Descriptor.
DividendToPrice - Forward dividends per share over the adjusted close, the forward dividend yield Descriptor.
ForwardDividendToPrice - Trailing dividends plus net buybacks over market capitalisation, the total payout Descriptor.
ShareholderYield - Total debt over total book capital, the book leverage Descriptor.
BookLeverage - Total debt over total market capital, the market leverage Descriptor.
MarketLeverage - Total debt over total assets, a leverage Descriptor.
DebtToAssets - Gross profit over total assets, the gross profitability Descriptor.
GrossProfitability - Gross profit over sales, the gross margin Descriptor.
GrossMargin - Trailing net income over total assets, the return on assets Descriptor.
ReturnOnAssets - Trailing net income over book equity, the return on equity Descriptor.
ReturnOnEquity - Trailing sales over total assets, the asset turnover Descriptor.
AssetTurnover - Trailing operating cash flow over total assets, a profitability Descriptor.
CashFlowToAssets - Trailing sales over enterprise value, a profitability Descriptor that is neutral to the capital structure.
SalesToEnterpriseValue - Accruals over total assets, the earnings quality Descriptor.
AccrualsCashFlow - Dispersion of the forward earnings estimates over the adjusted close, an earnings quality Descriptor.
AnalystDispersionToPrice - Shares sold short over shares outstanding, the short interest Descriptor.
ShortInterest
Takes the natural logarithm of one Panel Field at every observation. PanelFieldLog
PanelFieldLog- Natural logarithm of the market capitalisation, the size Descriptor.
LogMarketCap
- Returns one numeric Panel Field unchanged, as a Descriptor.
Passthrough
Growth of a non-negative Panel Field over a fixed lag, at every observation. GrowthRate
GrowthRate- Growth of total assets over one year, the investment Descriptor.
AssetsGrowthRate - Growth of trailing sales over one year, the growth Descriptor.
SalesGrowthRate - Growth of the split-adjusted share count over one year, the net issuance Descriptor.
IssuanceGrowthRate
Change of a Panel Field over a fixed lag, scaled by the current value of a second Panel Field. ChangeToScale
ChangeToScale- Change of trailing net income over one year, divided by the current market capitalisation.
EarningsChangeToPrice
Change of the ratio of two Panel Fields over a fixed lag. ChangeInIntensity
ChangeInIntensity- Change of the capital expenditure to total assets ratio over one year.
CapexToAssetsChangeInIntensity
Exponentially weighted mean of the log returns, at every observation, with an optional skip. EWMean
EWMean- Exponentially weighted mean of the log returns of the past year, less the past month.
EWMomentum
Exponentially weighted mean of a ratio of Panel Fields, at every observation. EWVolumeRatio
EWVolumeRatio- Exponentially weighted share turnover, the fraction of the shares outstanding that changes hands.
EWShareTurnover - Exponentially weighted price impact, the absolute return earned per unit of traded amount.
EWAmihudIlliquidity
- Ratio of a Panel Field to the exponentially weighted mean of a second one, at every observation.
DaysToCover
Exponentially weighted volatility of the returns, at every observation. EWVolatility
EWVolatility- Exponentially weighted volatility of the returns that fall short of a minimum acceptable return.
EWDownsideVolatility
Exponentially weighted volatility of the market-model residual, at every observation. EWResidualVolatility
EWResidualVolatility- Exponentially weighted volatility of the market-model residuals that fall short of a minimum acceptable return.
EWResidualDownsideVolatility
Exponentially weighted beta of the returns against the market return, at every observation. EWBeta
EWBeta- Exponentially weighted sensitivity of an asset to the market portfolio.
EWMarketBeta
- Exponentially weighted sensitivity of the returns to a reference series, after the market is removed.
EWMacroSensitivity - Exponentially weighted sensitivity of the returns to the falls of the market, at every observation.
EWDownsideBeta
Sum of log returns over a fixed window that ends a fixed number of observations back, at every observation. RollingLogReturn
RollingLogReturn- Sum of log returns over one year, ending one month back.
RollingMomentum - Negated sum of log returns over one month, ending at the current observation.
Reversal
Maximum return over a fixed trailing window, at every observation. RollingMax
RollingMax- Maximum return over one month.
MaxReturn
Factor exposures
An Exposure Estimator maps Descriptors, one categorical Panel Field, or nothing at all, to one asset loading per observation through factor_exposure. A member producing one factor returns an observations by assets matrix, and the one-hot member returns one factor per level of its Panel Field.
- A Factor Exposure that is a fixed weighted combination of Descriptors.
CompositeExposure - A Factor Exposure derived from the Factor Exposure of another factor.
DerivedExposure - A Factor Exposure that expands one categorical Panel Field into one factor per level.
OneHotExposure - A Factor Exposure equal to one for every asset at every observation.
ConstantExposure
Factor family basis
A Factor Family whose one-hot exposures are collinear with a global factor is re-based before the fit. factor_family_basis drops one member per family and returns the compact, time-varying change of basis the fit runs in, and the reduced factor returns expand back to the named raw ones.
- Compact change of basis between the raw factor axis and the reduced axis a re-based Factor Family is fitted in.
FactorFamilyBasisandfactor_family_basis
Return forecasts
A Return Forecast Estimator maps Descriptor Scores and a fitted factor-model block, or a stated vector, to one forecast per asset through return_forecast. descriptor_scores is the recipe every fitted member starts from: each Descriptor is winsorised, standardised, optionally neutralised against named Factor Exposures, and standardised again. The Forecast Unit says what the Descriptors forecast, and the member converts the answer to return units.
- The shared recipe that turns Descriptors into cross-sectional scores.
DescriptorScoresanddescriptor_scores - A Return Forecast the caller states outright.
CustomValueReturnForecast - A Return Forecast that is a fixed signed combination of Descriptor scores.
FixedWeightedReturnForecast - A Return Forecast whose Descriptor weights are fitted by exponentially weighted least squares.
ExpWeightedReturnForecast - A Return Forecast fitted by a regression target over every observation and asset at once.
TargetReturnForecast - The Descriptors forecast the idiosyncratic return itself.
IdiosyncraticReturnUnit - The Descriptors forecast the idiosyncratic return divided by the idiosyncratic volatility.
IdiosyncraticSharpeUnit
Forecast evaluation
forecast_evaluation pairs a Return Forecast with the forward target it is answerable for, out of sample, and answers a Result every statistic of the evaluation is then a verb over. The pairing takes bare matrices as readily as a fitted Return Forecast Result, so a forecast the library did not produce is scored on the same terms as one it did.
Pair a Return Forecast with the forward target it is answerable for, out of sample. forecast_evaluation
forecast_evaluation- The out-of-sample pairing of a Return Forecast with what happened next.
ForecastEvaluationResult - Return the history of a Return Forecast Estimator, refitting the member if it computes none.
forecast_history
The statistics of an evaluation, each a verb over its Result.
- Return the information coefficients of a Return Forecast, one row per evaluation date.
forecast_ic - Return the summary of the two information coefficient series of an evaluation, named.
forecast_ic_summary - Return the share of the universe an evaluation scored, one entry per evaluation date.
forecast_coverage - Score the long-short portfolio a Return Forecast states on its own.
forecast_portfolio - Score the top-minus-bottom spread of a Return Forecast, one entry per quantile.
forecast_quantile_spread - Return the contemporaneous correlation of a Return Forecast against every factor exposure, one row per observation.
forecast_factor_correlation - Score whether the magnitude of a Return Forecast is right, and not only its ordering.
forecast_calibration
The same statistics against a grid of forward windows, every row on one date set.
- Score a Return Forecast against cumulative forward windows, one row per holding period.
forecast_holding_period - Score a Return Forecast against disjoint forward windows, one row per period out.
forecast_decay
The headline table, one entry per forecast, which is also the comparison.
- Summarise one or more Return Forecast evaluations as a
ForecastSummaryResult.forecast_evaluation_summary - The headline statistics of one or more Return Forecast evaluations, one entry per forecast.
ForecastSummaryResult - Put a set of Return Forecast evaluations on the evaluation grid they share.
forecast_evaluation_align
The quantity the forecast is scored against.
- Scores a Return Forecast against the forward idiosyncratic return.
IdiosyncraticTarget - Scores a Return Forecast against the forward asset return.
AssetReturnTarget - Scores a Return Forecast against the forward mean of a named numeric Panel Field.
PanelFieldTarget
Moment estimation
Expected returns
Overloads Statistics.mean.
- Computes the expected returns as the sample mean of the asset returns.
SimpleExpectedReturns - Computes the expected excess returns that a set of equilibrium weights implies, by reverse optimisation.
EquilibriumExpectedReturns - Subtracts a risk-free rate from the expected returns that a nested estimator computes.
ExcessExpectedReturns
Shrinks the sample expected returns toward a target chosen by the shrinkage algorithm. ShrunkExpectedReturns
ShrunkExpectedReturnsAlgorithms
- James-Stein
JamesStein - Bayes-Stein
BayesStein - Bodnar-Okhrin-Parolya
BodnarOkhrinParolya
Targets: all algorithms can have any of the following targets
- Grand Mean
GrandMean - Volatility Weighted
VolatilityWeighted - Mean Squared Error
MeanSquaredError
- Expected returns estimator that returns the asset standard deviations.
StandardDeviationExpectedReturns - Expected returns estimator that returns the asset variances.
VarianceExpectedReturns - Computes the expected returns as the per-asset median of the asset returns.
MedianExpectedReturns - Returns a caller-supplied value for each asset instead of estimating one from the data.
CustomValueExpectedReturns - Expected returns estimator that restricts computation to a rolling or indexed observation window.
WindowedExpectedReturns - Estimates expected returns by an exponentially weighted recursion that freezes on a holiday and resets on an inactive period.
ExpWeightedExpectedReturns
Variance and standard deviation
Overloads Statistics.var and Statistics.std.
- Computes the marginal variance and standard deviation, optionally weighted and optionally bias-corrected.
SimpleVariance - Variance estimator that restricts computation to a rolling or indexed observation window.
WindowedVariance
Covariance and correlation
Overloads Statistics.cov and Statistics.cor.
- Adapts any
StatsBase.CovarianceEstimatorto the library's calling convention, carrying its observation weights alongside it.GeneralCovariance
Estimates the covariance matrix of asset returns from a centring estimator, a covariance estimator, and a moment algorithm. Covariance
Covariance- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
Configures and applies Gerber covariance estimators. GerberCovariance
GerberCovariance- Normalises the net co-movement vote by the observations on which both assets crossed their threshold.
Gerber0 - Normalises the net co-movement vote by every observation on which at least one asset crossed its threshold.
Gerber1 - Normalises the raw net co-movement vote by the geometric mean of its own diagonal.
Gerber2
Configures and applies Smyth-Broby covariance estimators. SmythBrobyCovariance
SmythBrobyCovariance- Divides the difference of the concordant and discordant Smyth-Broby contribution sums by their sum.
SmythBroby0 - Divides the difference of the concordant and discordant Smyth-Broby contribution sums by their sum plus the neutral sum.
SmythBroby1 - Normalises the net Smyth-Broby contribution of a pair by the geometric mean of its own diagonal.
SmythBroby2 - Weights each Smyth-Broby contribution sum by its own observation count, then divides the difference by the sum.
SmythBrobyGerber0 - Weights each Smyth-Broby contribution sum by its own count, then divides the difference by the sum plus the neutral term.
SmythBrobyGerber1 - Weights each Smyth-Broby contribution sum by its own count, then normalises the net score by the geometric mean of its own diagonal.
SmythBrobyGerber2 - Counts concordant and discordant observations, discards the contribution sums, and divides their difference by their sum.
SmythBrobyCount0 - Counts concordant, discordant and neutral observations, discards the contribution sums, and divides the net count by the total.
SmythBrobyCount1 - Counts concordant and discordant observations, discards the contribution sums, and normalises the net count by the geometric mean of its own diagonal.
SmythBrobyCount2
Gerber Information Quality GerberIQCovariance with custom variance, demeaning, temporal decay and numerator + denominator estimators
GerberIQCovariance with custom variance, demeaning, temporal decay and numerator + denominator estimators- Implements the basic Gerber IQ covariance template.
BasicGerberIQ - Gerber Information Quality template with asymmetric thresholds.
PartialGerberIQ - Gerber Information Quality template with fine-grained asymmetric thresholds.
FullGerberIQ - Exponential Gerber IQ temporal decay.
ExpGerberIQDecay - Scales the threshold parameters using the individual asset volatilities.
AssetVolatilityGerberIQScaler
- Measures linear and non-linear codependence from doubly-centred pairwise distance matrices.
DistanceCovariance - Measures co-movement in the lower tail: the share of an asset's worst returns that fall on the same dates as another's.
LowerTailDependenceCovariance
Rank covariances
- Measures monotonic association with Kendall's tau, counting concordant against discordant pairs.
KendallCovariance - Measures monotonic association with Spearman's rho, the Pearson correlation of the rank-transformed returns.
SpearmanCovariance
Measures codependence with mutual information, which captures a non-linear relationship a correlation misses. MutualInfoCovariance
MutualInfoCovarianceAbstract supertype for all histogram binning algorithms based on a bin width selection rule. BinWidthBins
BinWidthBins- Knuth's optimal bin width
Knuth - Freedman Diaconis bin width
FreedmanDiaconis - Scott's bin width
Scott
- Histogram binning algorithm using the Hacine-Gharbi–Ravier rule.
HacineGharbiRavier - Predefined number of bins
- Convenience constructor.
DenoiseCovariance - Convenience constructor.
DetoneCovariance - Convenience constructor.
ProcessedCovariance
Covariance estimator based on implied volatility scaling. ImpliedVolatility
ImpliedVolatility- Implied volatility algorithm that divides the latest implied volatility by a volatility risk premium adjustment.
ImpliedVolatilityPremium - Implied volatility algorithm that predicts realised volatility via regression on implied volatility.
ImpliedVolatilityRegression
- Runs any covariance estimator, then applies a matrix post-processing step to its result.
PortfolioOptimisersCovariance - Answers both
covandcorwith the wrapped estimator's correlation matrix.CorrelationCovariance - Covariance estimator that restricts computation to a rolling or indexed observation window.
WindowedCovariance
Exponentially weighted covariance and variance
- Estimates a covariance matrix by an exponentially weighted recursion that freezes on a holiday and resets on an inactive period.
ExpWeightedCovariance - Estimates per-asset variance by an exponentially weighted recursion that freezes on a holiday and resets on an inactive period.
ExpWeightedVariance
Regime-adjusted covariance and variance
- Online exponentially weighted covariance estimator with regime-state adjustment.
RegimeAdjustedExpWeightedCovariance - Online exponentially weighted variance estimator with regime-state adjustment.
RegimeAdjustedExpWeightedVariance
Regime adjustment methods
- Regime adjustment method that scales variance by the ratio of the mean absolute deviation of standardised returns to the first-moment normalisation constant
x.FirstMomentRegimeAdjusted - Regime adjustment method that scales variance exponentially with the smoothed log-deviation of standardised squared returns from its expected value under stationarity.
LogRegimeAdjusted - Regime adjustment method that scales variance by the square root of the mean of the standardised squared returns.
RootMeanSquaredAdjusted
Shrinkage targets
- Regime-adjustment target that uses a diagonal baseline covariance structure.
DiagonalTarget - Regime-adjustment target that uses a Mahalanobis-distance-based baseline covariance structure.
MahalanobisTarget - Regime-adjustment target that uses a portfolio-weighted baseline covariance structure.
PortfolioTarget
Demeaning
- Centres the returns series using the (weighted) mean before computing the Median Absolute Deviation.
MeanCentering - Centres the returns series using the (weighted) median before computing the Median Absolute Deviation.
MedianCentering
Correlation smoothing
- Greedy pairwise correlation pruning: drop assets until no surviving pair exceeds
t.PairwiseCorrelation - Group assets by connected component of the over-threshold correlation graph, and keep the best-scoring member of each.
CorrelationComponents
Coskewness
Implements coskewness.
Estimates the coskewness tensor of a returns matrix, together with its negative spectral skewness matrix. Coskewness
Coskewness- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
- Coskewness estimator that restricts computation to a rolling or indexed observation window.
WindowedCoskewness
Cokurtosis
Implements cokurtosis.
Estimates the square cokurtosis matrix of a returns matrix. Cokurtosis
Cokurtosis- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
- Cokurtosis estimator that restricts computation to a rolling or indexed observation window.
WindowedCokurtosis
Windowed moments
Every windowed estimator wraps a base moment estimator and recomputes it over a trailing window, so a moment can vary across the folds of a cross-validation scheme. The window is set by a fixed length or by a WindowSizeEstimator.
- Abstract supertype for estimators that determine the rolling window size.
WindowSizeEstimator
Incremental fit
An estimator whose statistic has an exact update from its running state plus one new observation folds observations into that state, and its read-out verb answers from the state without reading the sample again. The state lives in the estimator's cache field, and ADR 0106 records why it is the one result an estimator holds. The sample mean, the sample variance and the full-moment sample covariance take part, and so does the FullMoment arm of Coskewness and of Cokurtosis. The SemiMoment arm does not, because it clips against a centre that a new observation moves.
Two verbs fold, and ADR 0107 records what each promises. partial_fit! is the method each family writes, and it is that family's cheapest exact fold; it promises nothing about an estimator kept from before the call. partial_fit is one generic method with value semantics: it folds a copy of the state, so the estimator handed over reads what it read before.
- Folds observations into an estimator's partial-fit state, and returns the estimator.
partial_fit! - Folds observations into a copy of an estimator's partial-fit state, and returns the estimator that carries the copy.
partial_fit
An estimator whose statistic has no exact update keeps the observations it has seen instead, and its read-out runs the batch verb over them. Online is the configuration that gives it that buffer, and it is transient: it resolves once at warm-up, before the first fold, and no wrapper survives into the run. Its max_history caps the buffer, which bounds memory and changes what a consumer reading the observations answers; a statistic that folds exactly is unaffected and stays fitted over every observation folded so far.
- Declares that an estimator takes the online step from a buffer of the observations it has seen.
Online
Coverage policy
A plain moment estimator fits on the Coverage Universe of its window: the assets whose return is finite and whose Asset Panel active mask is true at every row of it. That rule is all-or-nothing per asset, and over an expanding window it can never admit an asset that lists after the first row. A CoveragePolicy in the estimator's cvg field replaces it, per estimator and by choice, with available-case estimation: every cell of the answer is fitted on the observations at which every asset of that cell is finite and active, each cell carries its own denominator, and an asset reaches the answer where its coverage share clears min_coverage. It is nothing by default, and that arm is the reduce-and-expand path unchanged.
What happens to a delisted asset is the policy's alg, one member per rule, and a caller whose rule is none of the three subtypes the family and writes its two verbs.
Fits each cell of a moment on the observations that cell has, instead of on the Coverage Universe. CoveragePolicy
CoveragePolicy- Keeps a delisted asset's history, and drops the asset from the frame the moment it goes inactive.
DecayCoverage - Throws a delisted asset's history away, so that a relisting starts the asset cold.
ResetCoverage - Holds a delisted asset in the frame for a stated number of observations, then drops it.
ExpireCoverage
Distance matrices
Implements distance and cor_and_dist.
- Pairs a distance algorithm with an optional integer power, and applies it to a correlation matrix or to the data.
Distance - Measures how differently two assets relate to the whole universe, by applying a metric to a distance matrix.
DistanceDistance
The distance estimators are used together with various distance matrix algorithms.
- Turns a signed correlation into a distance by $\sqrt{(1 - \rho) / 2}$.
SimpleDistance - Turns the magnitude of a correlation into a distance by $\sqrt{1 - \lvert\rho\rvert}$.
SimpleAbsoluteDistance - Turns the magnitude of a correlation into an unbounded distance by $-\log\lvert\rho\rvert$.
LogDistance - Turns a non-negative codependence into a distance by $\sqrt{1 - \rho}$, without halving.
CorrelationDistance
Measures the information one asset loses about another, from the entropies of a joint histogram. VariationInfoDistance
VariationInfoDistanceAbstract supertype for all histogram binning algorithms based on a bin width selection rule. BinWidthBins
BinWidthBins- Knuth's optimal bin width
Knuth - Freedman Diaconis bin width
FreedmanDiaconis - Scott's bin width
Scott
- Histogram binning algorithm using the Hacine-Gharbi–Ravier rule.
HacineGharbiRavier - Predefined number of bins
- Selects the distance algorithm that matches the covariance estimator it is given.
CanonicalDistance
Feature distances
A feature matrix describes assets by their exposures, memberships, loadings or adjacencies rather than by their returns, and can be turned into a distance matrix directly — no correlation matrix in between.
Turns a feature matrix into a distance matrix, by applying a metric to the rows of that matrix. FeatureDistance
FeatureDistance- Normalised angular distance metric.
AngularDist
Stack the Panel Fields a Feature Selector names into the Feature Matrix a distance measures. feature_matrix and feature_labels
feature_matrix and feature_labelsThe Feature Matrix is derived from an AssetPanel and stored nowhere. feature_matrix stacks the Panel Fields the selector names, and feature_labels gives one label per column — a label vector is itself a selector, so it rebuilds the matrix the kernel measured.
Asset Panel producers
ape says which AssetPanel the metric measures. nothing reads the panel the data carrier holds; a producer builds a static one at the point of use, from the prior result and the returns of the subproblem that runs it, so a view passes it through and a fold refits it.
- Builds an Asset Panel holding the factor loadings the wrapped prior fitted.
RegressionPanel
Builds an Asset Panel holding a square proximity matrix graded from a graph or a partition. PhylogenyPanel and phylogeny_features
PhylogenyPanel and phylogeny_featuresGrades a graph neighbourhood into a square assets × assets proximity block, so the distance measures neighbourhood overlap. The one producer whose trailing axis is the asset axis; its source is always an estimator, so every fold and subproblem refits the graph on its own universe.
Phylogeny feature algorithm scoring each pair by how far apart it sits. Proximity
ProximityKeeps the step count phylogeny_matrix's clamp throws away, scoring each pair by how far apart it sits. decay shapes the fall-off and the source's sep truncates it – two knobs, deliberately separate, because an exponential never reaches zero. Apart from NoDecay no decay emits zero inside the budget, so a zero entry means unreachable and nothing else.
Separations: the open AbstractSeparationAlgorithm family, applied by separation_matrix and separation_budget
AbstractSeparationAlgorithm family, applied by separation_matrix and separation_budgetCarried by NetworkEstimator as sep. Says how far apart two assets sit and how far is too far, because the two share a unit. It sits on the network estimator rather than on the producer: every consumer of a network needs to know which pairs it relates, and the constraint path never sees the producer at all.
- Separation measured as the number of graph edges between two assets.
HopCount PathLengthsums the distances along the shortest path instead of counting its edges, and budgets in the distance estimator's units –dmax = nothingmeans the observed diameter
Budget rules: a callable in place of the budget number, resolved by resolve_separation once the data is in hand
resolve_separation once the data is in handA budget cannot always be named in advance – a cross-validation fold and a meta optimiser's subproblem each refit the graph. HopCount(; n = ⋅) takes a HopCountAlgorithm and PathLength(; dmax = ⋅) a PathLengthAlgorithm, each a callable struct; a bare Function is admitted in either field. The hop obligation is an Integer, checked at resolution because a functor's return type is not part of its signature. A rule changes which quantity stays put: a stated budget holds the radius still, a quantile rule holds the related-pair count still.
HopCountQuantileplaces the hop budget at a quantile of the observed hop separations, rounded to a shell – so it lands near the requested share rather than on itPathLengthQuantiledoes the same in distance units with no rounding, so it hits the requested share of related pairs – which is how the radius ball's intermediate cardinalities become reachable by name
Separation decays: the open AbstractSeparationDecayAlgorithm family, applied by separation_decay
AbstractSeparationDecayAlgorithm family, applied by separation_decayThe argument is a real separation, so one family serves a hop count and any continuous separation alike. The contract – f(0) > 0 and maximal, monotone non-increasing, non-negative inside the budget, never assumed to reach zero – is probed by a fail-safe fallback that the shipped members opt out of.
- Separation decay falling off linearly to the edge of the budget.
LinearDecay - Separation decay falling off exponentially.
ExponentialDecay - Separation decay falling off as a power of the separation.
ReciprocalDecay NoDecayis the flat end of the dial, and not no truncation: the budget still cuts, so it yields the neighbourhood indicator
Collapsing a window of time-varying features
- Discards the window and measures the last observation's feature matrix alone.
LastObservation
Collapses the window to one assets × features matrix, then applies the metric once. AggregateFeatures and AggregateDistances
assets × features matrix, then applies the metric once. AggregateFeatures and AggregateDistances- Aggregates along the observation axis with the possibly weighted arithmetic mean.
MeanCollapse - Aggregates along the observation axis with the possibly weighted median, which resists an outlying observation.
MedianCollapse
- Concatenates the window into one long feature vector per asset, so nothing is averaged away.
StackObservations
Similarity matrices
Every similarity matrix algorithm is a pure transformation of a distance matrix, applied by distance_to_similarity. FeatureDistance picks one from its metric via default_similarity; the Planar Maximally Filtered Graph used by DBHT and LoGo takes its own.
The PMFG cannot take a negative weight, so it admits only the narrower AbstractNonNegativeSimilarityMatrixAlgorithm and refuses AngularSimilarity at construction. Two of the admitted members carry a domain precondition on the distance matrix, checked by assert_similarity_domain: ComplementSimilarity needs D <= 1, and MaximumDistanceSimilarity needs a finite D.
- Takes the linear complement $1 - D$, the exact counterpart of a metric that is itself one minus a similarity.
ComplementSimilarity - Recovers a correlation from a normalised angular distance by $\cos(\pi D)$.
AngularSimilarity - Subtracts the squared distance from a ceiling placed above the largest squared distance.
MaximumDistanceSimilarity - Maps a distance of any magnitude into $(0,\,1]$ by $e^{-D}$.
ExponentialSimilarity - Applies $e^{-c D^{p}}$, adding a scale and an exponent to the exponential transformation.
GeneralExponentialSimilarity
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.
Decides how many clusters to cut a dendrogram or a partition into. OptimalNumberClusters and VectorToScalarMeasure
OptimalNumberClusters and VectorToScalarMeasure- Picks the number of clusters at which the within-cluster dispersion curve bends most sharply.
SecondOrderDifference - Picks the number of clusters whose assets sit best inside their own cluster.
SilhouetteScore - Predefined number of clusters.
- Cut a dendrogram at the number of clusters
oncselects.optimal_number_clusters
- Get the vector of cluster indices for each point.
assignments
Hierarchical
- Builds a dendrogram by merging the two nearest clusters until one remains.
HClustAlgorithm
Direct Bubble Hierarchical Trees DBHT and Local Global sparsification of the covariance matrix LoGo, logo!, and logo
DBHT and Local Global sparsification of the covariance matrix LoGo, logo!, and logoRoot selection
- Takes one clique of the planar hierarchy as its single root.
UniqueRoot - Builds one root from the adjacency tree of every root candidate.
EqualRoot
Non-hierarchical
Non-hierarchical clustering algorithms are incompatible with hierarchical clustering optimisations, but they can be used for phylogeny constraints and NestedClustered optimisations.
- Partitions assets into
kgroups by Lloyd's algorithm, with no dendrogram.KMeansAlgorithm
Networks
Adjacency matrices
Adjacency matrices encode asset relationships either with clustering or graph theory via phylogeny_matrix and PhylogenyResult.
Network adjacency NetworkEstimator with custom tree algorithms, covariance, and distance estimators
NetworkEstimator with custom tree algorithms, covariance, and distance estimators- Grows the minimum spanning tree by taking the lightest edge that joins two components.
KruskalTree,BoruvkaTree, andPrimTree
Triangulated Maximally Filtered Graph with various similarity matrix estimators
Any member of AbstractNonNegativeSimilarityMatrixAlgorithm: MaximumDistanceSimilarity, ExponentialSimilarity, GeneralExponentialSimilarity or ComplementSimilarity. AngularSimilarity is refused, because a PMFG cannot take the negative weight it returns whenever a correlation is negative.
Which pairs count as related: the sep separation
sep separationHopCount gives the hop ball, every pair within n edges. PathLength gives the radius ball, every pair whose shortest path is no longer than dmax – which buys the cardinalities between the hop shells, since a hop knob can only step whole neighbourhoods at a time. It does not re-rank: both are selected by distance to begin with, so a path length refines a hop count rather than rivalling it. Note that PathLength() with no dmax means the observed diameter and therefore relates every reachable pair, the opposite end of the dial from HopCount()'s default. Both reach SemiDefinitePhylogenyEstimator and IntegerPhylogenyEstimator; NetworkClustersEstimator takes only the hop count, because its power sum is indexed by edges.
- Turns a return matrix into a clustering of the asset universe.
ClustersEstimatorandClusters - Clusters assets by the pseudo-distances that a network's structure induces.
NetworkClustersEstimator - Group assets by clustering them, and keep the best-scoring member of each cluster.
ClusterGroups
Centrality and phylogeny measures
Centrality estimator CentralityEstimator with custom adjacency matrix estimators (clustering and network) and centrality measures
CentralityEstimator with custom adjacency matrix estimators (clustering and network) and centrality measures- Betweenness
BetweennessCentrality - Closeness
ClosenessCentrality - Degree
DegreeCentrality - Eigenvector
EigenvectorCentrality - Katz
KatzCentrality - Pagerank
Pagerank - Radiality
RadialityCentrality - Stress
StressCentrality
The network is weighted where it can be, in the polarity centrality_polarity answers for the algorithm
centrality_polarity answers for the algorithmDistancePolarityfor the shortest-path algorithms – betweenness, closeness, radiality and stressSimilarityPolarityfor eigenvector centrality, which reads the weighted adjacency matrix itselfTopologyOnlyin theovfield of any of the five polarity-declaring algorithms, which withdraws the declaration and asks for the centrality over the network's topology alone
Five cases run on the plain unweighted graph and none of them raises: a weightless source (a ClustersEstimator, a precomputed Clusters, a precomputed PhylogenyResult), DegreeCentrality, Pagerank, KatzCentrality, and EigenvectorCentrality on a tree branch. Polarity says which weights an algorithm receives, never whether the call succeeds. Note that the sep of a NetworkEstimator is inert on the weighted routes, which read the structure rather than the separation closure – at the default HopCount(; n = 1) the two agree.
The override runs one way: it removes the weights and never supplies them, so there is no value that forces a polarity onto an algorithm. Every source honours it, because the topology-only answer is what a partition source, a precomputed PhylogenyResult and the tree branch already compute. Only the five that declare a polarity carry the field – DegreeCentrality(; ov = TopologyOnly()) is a MethodError, since the other three already read the topology alone. ct is positional on every centrality surface, so a configured algorithm reaches all of them, and a CentralityEstimator stays a pure bundle of pl and ct.
- Fallback no-op for returning a validated centrality vector result as-is.
centrality_vector - Compute the weighted average centrality for a network and centrality algorithm.
average_centrality - Compute the asset phylogeny score for a set of weights and a phylogeny matrix.
asset_phylogeny
Cluster trees
Hierarchical clustering produces a tree of ClusterNodes, walked by to_tree, pre_order, and is_leaf.
- Collects each leaf's
id, which for a leaf is its asset index.PreorderTreeByID
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 UniverseSets. Internally, PortfolioOptimisers.jl uses all the information and calls name_to_val!, and replace_group_by_assets to produce the appropriate arrays.
- Equation parsing
parse_equationandParsingResult - No-op fallback for returning an existing
LinearConstraintobject,nothing, or a vector of them.linear_constraints,LinearConstraintEstimator,PartialLinearConstraint, andLinearConstraint
Factor exposure constraints ExposureConstraintEstimator
ExposureConstraintEstimatorWraps whatever lcse already accepts and declares the AbstractConstraintSpace its rows are written in, so a mandate can be stated in factor names – "at most 30% momentum" – and re-based through the prior's loadings. The projection happens during constraint generation, so what reaches the optimiser is an ordinary asset-space LinearConstraint and every optimiser sharing JuMPOptimiser supports one. The names resolve against the factor axis a UniverseSets declares.
- The factor basis: a constraint written in factor names, re-based through a regression's loadings.
FactorSpace
- No-op fallback for risk budget constraint generation.
risk_budget_constraints,RiskBudgetEstimator, andRiskBudget - Generate phylogeny-based portfolio constraints from an estimator or result.
phylogeny_constraints,centrality_constraints,SemiDefinitePhylogenyEstimator,SemiDefinitePhylogeny,IntegerPhylogenyEstimator,IntegerPhylogeny, andCentralityConstraint - Generate portfolio weight bounds constraints from a
WeightBoundsEstimatorand asset set.weight_bounds_constraints,WeightBoundsEstimator, andWeightBounds - Declares the universes a portfolio problem is written against, and any groupings or partitions of them.
UniverseSets
Budget constraints BudgetEstimator and BudgetRange
BudgetEstimator and BudgetRange- Charges the portfolio budget for transaction costs that grow linearly with the traded volume.
BudgetCosts - Charges the portfolio budget and the return for market impact costs that follow an empirical power law.
BudgetMarketImpact
Constraint values AbstractEstimatorValueAlgorithm
AbstractEstimatorValueAlgorithmWhere a constraint takes one value per asset or group, these algorithms say how to derive it from data rather than stating it outright.
- Fills every entry of a value vector with
1/N, whereNis the number of assets in the universe.UniformValues - Return value for assets or groups, based on a mapping and asset sets.
estimator_to_val - Algorithm for reducing a vector of real values to its minimum.
MinValue - Algorithm for reducing a vector of real values to its maximum.
MaxValue - Algorithm for reducing a vector of real values to its optionally weighted mean.
MeanValue - Algorithm for reducing a vector of real values to its optionally weighted median.
MedianValue - Algorithm for reducing a vector of real values to its mode.
ModeValue - Algorithm for reducing a vector of real values to its sum.
SumValue - Algorithm for reducing a vector of real values to its product.
ProdValue - Algorithm for reducing a vector of real values to its optionally weighted standard deviation.
StdValue - Algorithm for reducing a vector of real values to its optionally weighted variance.
VarValue - Algorithm for reducing a vector of real values to its optionally weighted mean divided by its optionally weighted standard deviation.
StandardisedValue - States that no fold-less value exists.
NoDefault
Varies one optimiser input across the folds of a cross-validation scheme. TimeDependent
TimeDependentA time-dependent input takes a different value in each fold of a cross-validation scheme, and is inert outside one.
- Abstract supertype for the callable structs used as time-dependent values.
TimeDependentCallable - Abstract supertype for callable structs whose per-fold value is a constraint value.
TimeDependentConstraintCallable - Abstract supertype for callable structs whose per-fold value is an optimiser.
TimeDependentOptimiserCallable - Describes one fold to the time-dependent constraints that resolve against it.
TimeDependentContext - Declares that a callable time-dependent entry requires the previous optimisation's weights.
PreviousWeightsFunction
- Construct a binary asset-group membership matrix from asset set groupings.
asset_sets_matrixandAssetSetsMatrixEstimator - Propagate or pass through buy-in threshold portfolio constraints.
threshold_constraints,ThresholdEstimator, andThreshold
Prior statistics
Many optimisations and constraints use prior statistics computed via prior.
Carries the returns, mean and covariance a low order prior estimator produced. LowOrderPrior
LowOrderPrior- Empirical prior estimator for asset returns.
EmpiricalPrior - Factor-based prior estimator for asset returns.
FactorPrior
Estimates a point-in-time cross-sectional factor model from an Asset Panel, and lifts it onto the assets. CrossSectionalFactorPrior
CrossSectionalFactorPriorThe cross-sectional counterpart of FactorPrior. It reads a point-in-time AssetPanel rather than a factor-return series, builds one Factor Exposure per named factor, regresses each observation's returns on the lagged exposures across the assets, and returns a CrossSectionalFactorModel in the rr slot. It composes the Descriptors, the Factor Exposures, the cross-sectional regression, its weight policy and the Factor Family Basis catalogued above. The factor axis it will produce is readable before any fit: cross_sectional_factor_axis answers the raw factor names and their Factor Family labels off the estimator and the Asset Panel, and cross_sectional_factor_sets declares that axis and one group per family on a UniverseSets, so a factor mandate written in a pipeline step never hand-types a one-hot level list.
Black-Litterman
- Unified interface for constructing or passing through Black-Litterman investor views.
black_litterman_views - Black-Litterman prior estimator for asset returns.
BlackLittermanPrior - Bayesian Black-Litterman prior estimator for asset returns.
BayesianBlackLittermanPrior - Factor Black-Litterman prior estimator for asset returns.
FactorBlackLittermanPrior - Augmented Black-Litterman prior estimator for asset returns.
AugmentedBlackLittermanPrior
Reweights the observations of a prior so that its moments and its tails meet a set of views. EntropyPoolingPrior
EntropyPoolingPriorEntropy pooling reweights the observations so that the posterior satisfies the stated views while staying as close as possible to the prior. Alongside the moment views it takes views on the conditional, entropic and relativistic value at risk, each written as constraints of the one entropy pooling problem.
- Container for Black-Litterman investor views in canonical matrix form.
BlackLittermanViews
View constraint algorithms
- Enforces every view in a single entropy pooling optimisation.
H0_EntropyPooling - Enforces the views in stages, and starts every stage from the prior probabilities.
H1_EntropyPooling - Enforces the views in stages, and starts every stage from the previous stage's probabilities.
H2_EntropyPooling
Tail view formulations
- Linear formulation of a conditional value-at-risk view [1].
LinearConditionalValueatRiskView - Integer formulation of a conditional value-at-risk view [1].
IntegerConditionalValueatRiskView - Exponential cone formulation of an entropic value-at-risk view [1].
ConicEntropicValueatRiskView - Grid formulation of an entropic value-at-risk view [1].
GridEntropicValueatRiskView - Power cone formulation of a relativistic value-at-risk view [2].
ConicRelativisticValueatRiskView - Grid formulation of a relativistic value-at-risk view.
GridRelativisticValueatRiskView - Sequential convex formulation of a conditional value-at-risk view.
SequentialConditionalValueatRiskView - Sequential convex formulation of an entropic value-at-risk view.
SequentialEntropicValueatRiskView - Sequential convex formulation of a relativistic value-at-risk view.
SequentialRelativisticValueatRiskView
View groups
A significance level belongs to a view, not to the estimator holding it. These pair a group of view equations with the level, and for a tail view the formulation, they are read under, so one estimator can state views at several levels. A relativistic view group carries its deformation parameter on the same reasoning.
- A group of value at risk views, with the significance level they are read under.
ValueatRiskView - A group of conditional value at risk views, with the significance level and formulation they are read under.
ConditionalValueatRiskView - A group of entropic value at risk views, with the significance level and formulation they are read under.
EntropicValueatRiskView - A group of relativistic value at risk views, with the significance level, the deformation parameter and the formulation they are read under.
RelativisticValueatRiskView - Spans of the two searches that read a relativistic value at risk.
RelativisticValueatRiskViewBracket
Divergence formulations
- Evaluates the entropy pooling objective through the exponential of the dual variables.
ExpEntropyPooling - Evaluates the entropy pooling objective in log space.
LogEntropyPooling
Optimisers
- Solves the dual of the entropy pooling problem with Optim.jl.
OptimEntropyPooling - Solves the primal of the entropy pooling problem with JuMP.jl.
JuMPEntropyPooling
Reweights the observations of a prior so that its moments meet a set of views, and root-finds a CVaR view. MeucciEntropyPoolingPrior
MeucciEntropyPoolingPriorThe earlier entropy pooling estimator, which hunts a conditional value at risk target with the recursive algorithm of Meucci, Ardia and Keel. It takes equality CVaR views alone, and re-solves the whole problem once per candidate value at risk level.
View constraint algorithms
- Enforces every view in a single entropy pooling optimisation.
H0_EntropyPooling - Enforces the views in stages, and starts every stage from the prior probabilities.
H1_EntropyPooling - Enforces the views in stages, and starts every stage from the previous stage's probabilities.
H2_EntropyPooling - Root-finds the value at risk level that meets a single conditional value-at-risk view.
ConditionalValueatRiskEntropyPooling
Opinion pooling prior estimator for asset returns. OpinionPoolingPrior
OpinionPoolingPrior- Pools the opinions as a weighted arithmetic mean of their scenario weights.
LinearOpinionPooling - Pools the opinions as a weighted geometric mean of their scenario weights, renormalised.
LogarithmicOpinionPooling
Carries the coskewness and cokurtosis a high order prior estimator produced, over the low order prior it wraps. HighOrderPrior
HighOrderPrior- High order prior estimator for asset returns.
HighOrderPriorEstimator - Projects factor coskewness and cokurtosis onto the asset axis through the regression loadings.
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.
- Holds the element-wise lower and upper bounds of a box uncertainty set on a mean vector or on a covariance matrix.
BoxUncertaintySetandBoxUncertaintySetAlgorithm
EllipsoidalUncertaintySet and EllipsoidalUncertaintySetAlgorithm with various algorithms for computing the scaling parameter via k_ucs
EllipsoidalUncertaintySet and EllipsoidalUncertaintySetAlgorithm with various algorithms for computing the scaling parameter via k_ucs- Fits the ellipsoid radius
kempirically, as the1 - qquantile of the Mahalanobis distances of the sampled estimation errors.NormalKUncertaintyAlgorithm - Computes the ellipsoid radius
kassqrt((1 - q) / q), the closed form that holds for any distribution of the estimation errors.GeneralKUncertaintyAlgorithm - Computes the ellipsoid radius
kas the square root of the1 - qchi-squared quantile, the closed form that holds when the estimation errors are normal.ChiSqKUncertaintyAlgorithm - Predefined scaling parameter
A third shape holds the worst-case variance of a covariance set as a quadratic penalty on the weights, so the optimisation stays a second-order cone programme and lifts no semidefinite block.
- Holds a worst-case variance penalty as a radius, a diagonal metric square root and a basis of the directions the penalty spares.
CompactCovarianceUncertaintySet
A fourth shape is the image of a norm ball under a geometry map of any rank, on either axis, so a flat set on the directions a factor model does not span needs no full-rank shape matrix. A built ellipsoid converts into it with one Cholesky factorisation.
NormBallUncertaintySetandNormBallUncertaintySetAlgorithm, which take the same scaling algorithms as the ellipsoid and read them off the geometry map viak_norm_ball
It also implements various estimators for the uncertainty sets, the following two can generate box, ellipsoidal and norm-ball sets.
- Fits a box or an ellipsoidal uncertainty set from the sampling laws that normal returns imply: the mean is normal and the covariance is Wishart.
NormalUncertaintySet
Bootstrapping via Autoregressive Conditional Heteroscedasticity ARCHUncertaintySet via arch
ARCHUncertaintySet via arch- Circular
CircularBootstrap - Moving
MovingBootstrap - Stationary
StationaryBootstrap
The following estimator can only generate box sets.
- Fits a box uncertainty set by widening the prior statistics by a fixed fraction of their own absolute value.
DeltaUncertaintySet
Quintile portfolios are expressed as an uncertainty set on the characteristic vector rather than as an optimiser of their own (ADR 0032).
Fits an $\ell_1$ uncertainty set on the characteristic vector, mean-only and with a calibrated radius. CharacteristicUncertaintySet
CharacteristicUncertaintySet\[\ell_1\]
(cross-polytope) uncertainty set on the characteristic vector.L1UncertaintySetandL1UncertaintySetAlgorithm- Signed $\ell_1$ uncertainty set on the characteristic vector, with a separate error budget per sign.
SignedL1UncertaintySetandSignedL1UncertaintySetAlgorithm - Calibrates the $\ell_1$ uncertainty radius to a target number of active assets.
ActiveAssetsUncertaintyAlgorithm
One estimator reads no returns data at all. It is handed the fitted prior of the optimisation it serves, and confines both of its sets to the directions the prior's factor model does not span.
Fits both uncertainty sets from the factor model of the optimisation's own prior, confined to the directions the factors do not span. OrthogonalUncertaintySet
OrthogonalUncertaintySetOrthogonality metrics, the cross-sectional weighting the factor span is taken under
- Names the inverse of the idiosyncratic variances as the cross-sectional weight source, the default.
InverseIdiosyncraticVarianceMetric - Names the regression weights as the cross-sectional weight source.
RegressionWeightMetric - Names the benchmark weights as the cross-sectional weight source.
BenchmarkWeightMetric - Names no weight source: every asset carries the same weight.
IdentityMetric
Scalings of the mean set inside the Orthogonal Subspace
- Gives every direction of the Orthogonal Subspace the same uncertainty, the default.
IdentityScaling - Sizes each direction of the Orthogonal Subspace by the idiosyncratic covariance projected onto it.
IdiosyncraticVarianceScaling
Rules that size the covariance radius from the sample and the span, in place of a stated number
- Sizes the compact radius as the upper confidence bound on the idiosyncratic variance, so the penalty is a quantile rather than a stated magnitude.
ResidualInflation - Sizes the compact radius so the penalty is a stated fraction of the nominal variance at a reference portfolio, giving the caller a unit instead of a bare number.
VarianceFraction
Axis tags of the ellipsoid and the norm ball
- Tags an
EllipsoidalUncertaintySetor aNormBallUncertaintySetas living on the mean axis, where the shape matrix is $N \times N$ and the geometry map has $N$ rows.MuUncertaintySetClass - Tags an
EllipsoidalUncertaintySetor aNormBallUncertaintySetas living on the covariance axis, where the shape matrix is $N^{2} \times N^{2}$ and the geometry map has $N^{2}$ rows.SigmaUncertaintySetClass
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. The proportional and turnover rates are charged on every period, and the two fixed amounts one time for the whole holding period, so calc_total_fees and calc_total_asset_fees report the cost of a stated horizon.
- Resolve the name-keyed fee fields of a
FeesEstimatoragainst a universe, giving aFeesof plain per-asset vectors.fees_constraints - Compute the fixed portfolio fees for assets that have been allocated.
calc_fixed_feesandcalc_asset_fixed_fees - Charge the whole cost of holding a portfolio for
Tperiods.calc_total_feesandcalc_total_asset_fees
Names the per-asset fee rates, for fees_constraints to align to a universe. FeesEstimator and Fees
fees_constraints to align to a universe. FeesEstimator and Fees- Proportional long
- Proportional short
- Fixed long
- Fixed short
- Turnover
- Spreads the one-off terms of a fee, the two fixed charges
flandfs, evenly over a holding period.AmortisedFees - Charges the one-off terms of a fee, the two fixed charges
flandfs, on the first observation of a return series.FirstObservationFees
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. calc_turnover reads the trading a weight path costs, which is the value-level reading of the quantity Turnover bounds.
A window may instead be scored on the weights a fund holds, which grow at their own asset returns while no trade is placed. The series is then the wealth ratio of the drifted holdings.
A fold's realised series may also charge the two fixed fee terms on a clock of its own. The scheme states it in its fa field, which overrides the clock the fee itself carries and reaches the fit not at all.
- Grows each position at its own asset return and holds no trade in between, so the weights drift and the series is the wealth ratio of the drifted holdings.
SelfFinancingDrift
Tracking
It is often useful to create portfolios that track the performance of an index, indicator, or another portfolio.
Compute the benchmark portfolio returns for a weights-based tracking algorithm. tracking_benchmark and TrackingError
tracking_benchmark and TrackingError- Carries the benchmark return series itself, for a benchmark whose weights are unknown.
ReturnsTracking - Builds the benchmark return series by holding a fixed weight vector, net of its own fees.
WeightsTracking
The error can be computed using different algorithms using norm_error.
Norm tracking algorithms
- Norm-one (NOC) error formulation.
L1Norm - Second-order cone (SOC) norm-based error formulation.
L2Norm - Second-order cone (SOC) squared norm-based error formulation.
SquaredL2Norm - L-p norm error estimator.
LpNorm - L-infinity norm (maximum absolute deviation) error estimator.
LInfNorm
The distance may also be a risk distance rather than a norm of the return difference, measured against a WeightsTracking benchmark. Two approaches are available.
Constrains how far a portfolio's risk may stand from a benchmark portfolio's risk. RiskTrackingError
RiskTrackingError- Applies the risk measure to each portfolio, then takes the absolute difference of the two risks.
DependentVariableTracking - Applies the risk measure to the difference between the portfolio weights and the benchmark weights.
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.
Every prior-derived slot on a risk measure – mu, sigma, kt, sk – takes the value itself or the estimator that computes it, a DeferredQuantity. The estimator is resolved against the optimisation's own prior, so it refits per cross-validation fold and per meta-optimiser subset where a pasted matrix cannot. A measure with two or more deferrable slots names one prior estimator in pe instead, and one fit fills every slot the measure leaves unstated. See ADR 0051.
Calibration
A tail probability and a deformation parameter also take a rule in place of the number. The slot names the quantity and the end of the distribution it addresses, so the caller writes the rule alone and the slot stores it. The rule is resolved against the optimisation's own prior, so the quantity refits per cross-validation fold and per meta-optimiser subset where a stated number holds still. Each slot's type bound names the one rule family that computes its quantity, and it admits a callable estimator of that family, a plain function of (key, pr, w, slv, ctx), or the number itself. Five rules ship: two compute a significance level, and three compute a deformation parameter. Forty slots across twenty-seven risk measures and weight builders take one: every alpha and beta, and every kappa, kappa_a and kappa_b. The two inner integration bounds of the tail-Gini family, alpha_i and beta_i, are starting points rather than quantities to estimate, so they keep their numbers and the joint 0 < alpha_i < alpha < 1 bound is checked against the calibrated alpha at fold time.
A significance rule reads the sample length, and reads the effective observation weights where the count it states is a count of observations. A deformation rule reads the probability of its own end, which reaches it in the CalibrationContext the slot owner builds. One spends a stated entropy budget on the sample length. The other two read the shape of the sample's own tail and return the reciprocal of its index: one standardises each column and answers per end, so a skewed sample gives two numbers, and one whitens each observation with the covariance matrix and answers one number for both ends.
A rule that reads the shape of a series is told which series to read. A drawdown measure prices the drawdown series of the portfolio rather than its returns, and the slot key names neither, so the measure states its own series in the CalibrationContext beside the significance level. The two rules then run the same reading over the drawdown series of each column, in place of the columns themselves: the pooled rule pools those series, and the radial rule whitens their rows with the covariance matrix of that same sample, because a prior result states no drawdown moment. The series belongs to the measure, so no rule holds a marker of its own and a caller who runs a rule by hand states the marker in the context the measure would have built.
- Computes a significance level from a count of observations, so that the tail keeps the same number of scenarios whatever the sample length becomes.
ScenarioCount - Computes a significance level that shrinks with the square root of the sample length.
RateSignificance - Computes the Kaniadakis deformation parameter that makes a relativistic measure spend a stated entropy budget.
EntropyBudget - Computes the Kaniadakis deformation parameter whose tail decays at the rate the sample's own tail decays at.
HillTailDecay - Computes the Kaniadakis deformation parameter whose tail decays at the rate the sample's radial series decays at.
RadialTailDecay - Names the returns themselves, the columns of
pr.Xunchanged.ReturnsSeries - Names the absolute drawdown series of a column, which
absolute_drawdown_vecbuilds.AbsoluteDrawdownSeries - Names the relative drawdown series of a column, which
relative_drawdown_vecbuilds.RelativeDrawdownSeries
An ambiguity radius takes a rule on the same terms. It names no end of the distribution, so one bound serves every radius slot, and it reaches the four regularisation coefficients of JuMPOptimiser as well as the two distributionally robust risk measures. Four rules ship, and all four compute a radius. Two shrink the ball at the square-root rate of the sample length, and the third shrinks it at the rate the number of assets sets, which is far slower over a wide universe.
- Computes an ambiguity radius from the concentration of measure, so that the ball shrinks as the sample grows.
ConcentrationRadius - Computes an ambiguity radius that shrinks with the square root of the sample length.
RateRadius - Computes an ambiguity radius that shrinks at the dimensional rate a Wasserstein ball earns, not at the square-root rate.
DimensionalRateRadius
Those three return one number for every slot, and the eight radius slots do not measure distance in one norm. The fourth rule reads the slot's key, picks the ground metric that slot names, and returns the sampling error of the empirical measure in it, so the l1 and linf coefficients of one optimiser get two coefficients rather than one.
- Computes an ambiguity radius in the ground metric that the slot it stands in names, so that two slots of two different norms get two different numbers.
DualNormRadius
The tail weight of an Esfahani-Kuhn loss carries a family of its own. One rule ships there, and it prices the tail term of the loss at a stated multiple of its mean term: a stated tail weight is dimensionless and is not scale-free in the sample, so one number is a different trade-off at every sampling frequency. That rule reads the probability of its own slot, which reaches it in the same context.
- Computes the Esfahani-Kuhn tail weight that prices the tail term of the loss at a stated multiple of its mean term.
TailTermParity
A norm ceiling is a different quantity from a radius, so it carries a family of its own and neither family is admitted in the other's slot. A radius is the coefficient of a norm penalty in the objective; a ceiling bounds that norm in a constraint, and its reciprocal is a floor on the effective number of assets. It reaches the three norm-constraint slots of JuMPOptimiser, l2c, lpc and linfc. One rule ships, and it holds a stated fraction of the universe effective, so the floor moves with the universe the prior carries. The order the ceiling is read against belongs to the constraint rather than to the rule, so each constraint site hands its own order over before the slot resolves.
- Computes a norm ceiling that holds a stated fraction of the universe effective, so that the floor refits whenever the universe changes.
EffectiveAssetFloor
Risk measures for traditional optimisation
These are all subtypes of RiskMeasure, and are supported by all optimisation estimators.
Represents the portfolio variance using a covariance matrix. Variance
VarianceTraditional optimisations also support:
- Risk contribution
Formulations
- Encodes the second moment as an explicit quadratic form, without an auxiliary variable or a cone.
QuadRiskExpr - Encodes the second moment as the square of a second-order cone variable.
SquaredSOCRiskExpr
- Represents the portfolio standard deviation using a covariance matrix.
StandardDeviation - Uncertainty set variance
UncertaintySetVariance(same as variance when used in non-traditional optimisation)
Represents a low-order moment risk measure. LowOrderMoment
LowOrderMoment- Represents the first lower moment risk measure algorithm.
FirstLowerMoment - Represents the mean absolute deviation risk measure algorithm.
MeanAbsoluteDeviation
Represents a second moment (variance or standard deviation) risk measure algorithm. SecondMoment
SecondMomentSecond squared moments
- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
Traditional optimisation formulations
- Encodes the second moment as an explicit quadratic form, without an auxiliary variable or a cone.
QuadRiskExpr - Encodes the second moment as the square of a second-order cone variable.
SquaredSOCRiskExpr - Encodes the second moment as a variable that a rotated second-order cone bounds.
RSOCRiskExpr
Encodes the square root of the second moment as a second-order cone variable. SOCRiskExpr
SOCRiskExpr- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
Represents the square root kurtosis risk measure. Kurtosis
Kurtosis- Actual kurtosis
FullMoment and semi-kurtosis are supported in traditional optimisers via the kt field. Risk calculation uses
kt field. Risk calculation uses- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
Traditional optimisation formulations
- Encodes the second moment as an explicit quadratic form, without an auxiliary variable or a cone.
QuadRiskExpr - Encodes the second moment as the square of a second-order cone variable.
SquaredSOCRiskExpr - Encodes the second moment as a variable that a rotated second-order cone bounds.
RSOCRiskExpr
Encodes the square root of the second moment as a second-order cone variable. SOCRiskExpr
SOCRiskExpr- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
Represents the Negative Skewness risk measure. NegativeSkewness
NegativeSkewnessSquared negative skewness
FullMoment and semi-skewness are supported in traditional optimisers via the sk and V fields. Risk calculation uses
sk and V fields. Risk calculation uses- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
Traditional optimisation formulations
- Encodes the second moment as an explicit quadratic form, without an auxiliary variable or a cone.
QuadRiskExpr - Encodes the second moment as the square of a second-order cone variable.
SquaredSOCRiskExpr
- Encodes the square root of the second moment as a second-order cone variable.
SOCRiskExpr
Represents the Value-at-Risk (VaR) risk measure. ValueatRisk
ValueatRiskTraditional optimisation formulations
- Mixed-integer programming (MIP) formulation for Value-at-Risk.
MIPValueatRisk - Distribution-based formulation for Value-at-Risk.
DistributionValueatRisk
Represents the Value-at-Risk Range risk measure. ValueatRiskRange
ValueatRiskRangeTraditional optimisation formulations
- Mixed-integer programming (MIP) formulation for Value-at-Risk.
MIPValueatRisk - Distribution-based formulation for Value-at-Risk.
DistributionValueatRisk
- Represents the Drawdown-at-Risk (DaR) risk measure.
DrawdownatRisk - Represents the Conditional Value-at-Risk (CVaR) risk measure, also known as Expected Shortfall (ES).
ConditionalValueatRisk - Distributionally Robust Conditional Value at Risk
DistributionallyRobustConditionalValueatRisk(same as conditional value at risk when used in non-traditional optimisation) - Represents the Conditional Value-at-Risk Range (CVaR Range) risk measure.
ConditionalValueatRiskRange - Distributionally Robust Conditional Value at Risk Range
DistributionallyRobustConditionalValueatRiskRange(same as conditional value at risk range when used in non-traditional optimisation) - Represents the Conditional Drawdown-at-Risk (CDaR) risk measure, also known as Expected Maximum Drawdown.
ConditionalDrawdownatRisk - Distributionally Robust Conditional Drawdown at Risk
DistributionallyRobustConditionalDrawdownatRisk(same as conditional drawdown at risk when used in non-traditional optimisation) - Represents the Entropic Value-at-Risk (EVaR) risk measure.
EntropicValueatRisk - Represents the Entropic Value-at-Risk Range (EVaR Range) risk measure.
EntropicValueatRiskRange - Represents the Entropic Drawdown-at-Risk (EDaR) risk measure.
EntropicDrawdownatRisk - Represents the Relativistic Value-at-Risk (RLVaR) risk measure.
RelativisticValueatRisk - Represents the Relativistic Value-at-Risk Range (RLVaR Range) risk measure.
RelativisticValueatRiskRange - Represents the Relativistic Drawdown-at-Risk (RLDaR) risk measure.
RelativisticDrawdownatRisk
Ordered Weights Array
Risk measures
- Ordered Weights Array (OWA) risk measure.
OrderedWeightsArray - Ordered Weights Array Range (OWA Range) risk measure.
OrderedWeightsArrayRange
Traditional optimisation formulations
- OWA formulation that computes the exact OWA risk by solving a linear programme.
ExactOrderedWeightsArray - OWA formulation that approximates the OWA risk using a set of p-norm parameters.
ApproxOrderedWeightsArray - Estimator type for OWA weights using JuMP-based optimization.
OWAJuMP
One-call OWA measures
- Callable OWA weight estimator for the Conditional Value at Risk (CVaR) risk measure.
OrderedWeightsArrayConditionalValueatRisk - Callable OWA weight estimator for the Conditional Value at Risk Range risk measure.
OrderedWeightsArrayConditionalValueatRiskRange - Callable OWA weight estimator for the tail Gini risk measure.
OrderedWeightsArrayTailGini - Callable OWA weight estimator for the tail Gini range risk measure.
OrderedWeightsArrayTailGiniRange
Array functions
- Gini Mean Difference
owa_gmd - Worst Realisation
owa_wr - Range
owa_rg - Conditional Value at Risk
owa_cvar - Weighted Conditional Value at Risk
owa_wcvar - Conditional Value at Risk Range
owa_cvarrg - Weighted Conditional Value at Risk Range
owa_wcvarrg - Tail Gini
owa_tg - Tail Gini Range
owa_tgrg
Linear moments (L-moments)
- Compute the linear moment weights for the linear moments convex risk measure (CRM).
owa_l_moment
Compute Ordered Weights Array (OWA) linear moment convex risk measure (CRM) weights using various estimation methods. owa_l_moment_crm
owa_l_moment_crmL-moment combination formulations
Represents the Maximum Entropy algorithm for Ordered Weights Array (OWA) estimation. MaximumEntropy
MaximumEntropy- Entropy formulation for
MaximumEntropyOWA that uses the exponential cone entropy constraint in JuMP.ExponentialConeEntropy - Entropy formulation for
MaximumEntropyOWA that uses the relative entropy cone constraint in JuMP.RelativeEntropy
- Represents the Minimum Squared Distance algorithm for Ordered Weights Array (OWA) estimation.
MinimumSquaredDistance - Represents the Minimum Sum of Squares algorithm for Ordered Weights Array (OWA) estimation.
MinimumSumSquares
- Represents the Average Drawdown risk measure.
AverageDrawdown - Represents the Ulcer Index risk measure.
UlcerIndex - Represents the Maximum Drawdown risk measure.
MaximumDrawdown
Represents the Brownian Distance Variance (BDVar) risk measure. BrownianDistanceVariance
BrownianDistanceVarianceTraditional optimisation formulations
Distance matrix constraint formulations
- Norm-one cone formulation for the Brownian Distance Variance optimisation constraint.
NormOneConeBrownianDistanceVariance - Inequality formulation for the Brownian Distance Variance optimisation constraint.
IneqBrownianDistanceVariance
Risk formulation
- Encodes the second moment as an explicit quadratic form, without an auxiliary variable or a cone.
QuadRiskExpr - Encodes the second moment as a variable that a rotated second-order cone bounds.
RSOCRiskExpr
- Represents the Worst Realisation risk measure.
WorstRealisation - Represents the Range risk measure.
Range - Represents the Turnover risk measure.
TurnoverRiskMeasure
Represents the Tracking Error risk measure. TrackingRiskMeasure
TrackingRiskMeasure- Norm-one (NOC) error formulation.
L1Norm - Second-order cone (SOC) norm-based error formulation.
L2Norm - Second-order cone (SOC) squared norm-based error formulation.
SquaredL2Norm - L-p norm error estimator.
LpNorm - L-infinity norm (maximum absolute deviation) error estimator.
LInfNorm
Risk Tracking Risk Measure
- Applies the risk measure to each portfolio, then takes the absolute difference of the two risks.
DependentVariableTracking - Applies the risk measure to the difference between the portfolio weights and the benchmark weights.
IndependentVariableTracking
- Represents the Power Norm Value-at-Risk (PNVaR) risk measure.
PowerNormValueatRisk - Represents the Power Norm Value-at-Risk Range (PNVaRRange) risk measure.
PowerNormValueatRiskRange - Represents the Power Norm Drawdown-at-Risk (PNDaR) risk measure.
PowerNormDrawdownatRisk - Represents a generic Value-at-Risk range risk measure that combines any pair of XatRisk-type measures applied to the loss and gain sides of the return distribution.
GenericValueatRiskRange - Represents the Risk Tracking risk measure.
RiskTrackingRiskMeasure - Risk measure that contributes no risk.
NoRisk
Risk measure settings
Every risk measure carries a settings object saying how it enters the problem: as the objective, as a constraint with an upper bound, and with what scale.
- Weights a risk measure inside an aggregate, and bounds its risk expression from above.
RiskMeasureSettings - Weights a hierarchical risk measure inside an aggregate, and carries no bound.
HierarchicalRiskMeasureSettings - Weights a risk measure inside an aggregate, and bounds its risk expression from below.
MaxRiskMeasureSettings
Risk measures for hierarchical optimisation
These are all subtypes of HierarchicalRiskMeasure, and are only supported by hierarchical optimisation estimators.
Represents a high-order moment risk measure. HighOrderMoment
HighOrderMoment- Represents the unstandardised semi-skewness risk measure algorithm.
ThirdLowerMoment - Represents a standardised high-order moment risk measure algorithm.
StandardisedHighOrderMomentandThirdLowerMoment
Represents the unstandardised fourth moment (kurtosis or semi-kurtosis) risk measure algorithm. FourthMoment
FourthMoment- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
Represents a standardised high-order moment risk measure algorithm. StandardisedHighOrderMoment and FourthMoment
StandardisedHighOrderMoment and FourthMoment- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment reads the downside alone.
SemiMoment
- Represents the Relative Drawdown-at-Risk risk measure for hierarchical optimisation.
RelativeDrawdownatRisk - Represents the Relative Conditional Drawdown-at-Risk risk measure for hierarchical optimisation.
RelativeConditionalDrawdownatRisk - Represents the Relative Entropic Drawdown-at-Risk (Relative EDaR) risk measure for hierarchical optimisation.
RelativeEntropicDrawdownatRisk - Represents the Relative Relativistic Drawdown-at-Risk (Relative RLDaR) risk measure for hierarchical optimisation.
RelativeRelativisticDrawdownatRisk - Represents the Relative Average Drawdown risk measure for hierarchical optimisation.
RelativeAverageDrawdown - Represents the Relative Ulcer Index risk measure for hierarchical optimisation.
RelativeUlcerIndex - Represents the Relative Maximum Drawdown risk measure for hierarchical optimisation.
RelativeMaximumDrawdown - Represents the Relative Power Norm Drawdown-at-Risk (Relative PNDaR) risk measure for hierarchical optimisation.
RelativePowerNormDrawdownatRisk - Represents a risk ratio risk measure for hierarchical portfolio optimisation.
RiskRatio - Represents the Equal Risk Measure for hierarchical portfolio optimisation.
EqualRisk - Represents the Median Absolute Deviation (MAD) risk measure for hierarchical portfolio optimisation.
MedianAbsoluteDeviation - Composite risk measure combining variance, skewness, and kurtosis into a single expression.
VarianceSkewKurtosis - Represents an even-order moment risk measure algorithm.
EvenMoment - Callable estimator that generates OWA linear moment convex risk measure (CRM) weights for a given number of observations.
LinearMoment
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.
- Represents a simple mean return measure for use in non-optimisation contexts.
MeanReturn - Represents the Third Central Moment risk measure.
ThirdCentralMoment - Represents the standardised Skewness risk measure.
Skewness - Return-based risk measure.
ExpectedReturn - Ratio-based risk measure.
ExpectedReturnRiskRatio - Represents a mean return to risk ratio measure.
MeanReturnRiskRatio - Represents a non-optimisation risk ratio measure.
NonOptimisationRiskRatio
Performance metrics
Every reader here takes one risk measure or a vector of them, scalarised into one number by a sca keyword bounded Scalariser — all four scalarisers, MinScalariser included, because the value level combines computed numbers rather than building a model expression. Where a return axis is present it takes one term or a vector of them, summed at the terms' own combination weights; there is no scalariser on the return axis. A result carries the measure and scalariser it ran under, so expected_risk(res.r, res.w, res.pr; sca = res.sca) reports the optimised figure without naming either by hand.
- Compute the expected value of a risk measure.
expected_risk - Compute the effective number of assets (Herfindahl-Hirschman inverse index).
number_effective_assets
Risk contribution
- Compute the risk contribution of each asset to the total portfolio risk using numerical differentiation.
risk_contribution - Compute the risk contribution of each factor (and the idiosyncratic component) to the total portfolio risk using a factor regression.
factor_risk_contribution
Factor attribution
factor_attribution decomposes a portfolio's volatility and mean return over the factors, the factor families and the assets of a factor model, and returns one FactorAttributionResult. The predicted methods read the moments the optimiser saw; the realised methods read a net return series, and each has a rolling twin. What the model does not explain is a fourth component of its own.
- Decompose a portfolio's volatility and mean return over the factors of a factor model.
factor_attributionandFactorAttributionResult - One row of a factor attribution: the volatility, the volatility contribution, the variance share, the mean return contribution and the correlation of one component of the portfolio return.
AttributionComponent - The factor axis or the family axis of a factor attribution, one entry per row of the axis.
AttributionBreakdown - The asset axis of a factor attribution, one entry per asset.
AssetAttributionBreakdown - The asset-by-factor contributions of a factor attribution, two matrices of assets by factors.
AssetFactorContribution
Compute the expected portfolio return using the specified return estimator. expected_return
expected_return- Arithmetic
ArithmeticReturn - Logarithmic
LogarithmicReturn - None
NoReturn
- Compute the expected risk of a measure from a precomputed net-return series.
expected_risk_from_returns - Compute the expected risk of a risk measure over rolling windows of the returns data.
rolling_window_measure - Sort the successful paths in a
PopulationPredictionResultby their expected risk underr.sort_by_measure - Compute the expected risk-adjusted return ratio for a portfolio.
expected_ratioandexpected_risk_ret_ratio - Compute the risk-adjusted ratio information criterion (SRIC) for a portfolio.
expected_sricandexpected_risk_ret_sric - Compute Brinson performance attribution aggregated per asset class [3].
brinson_attribution - Summarise a realised return series as a
PerformanceSummaryResult.performance_summaryandPerformanceSummaryResult
Portfolio optimisation
Optimisations are implemented via optimise. Optimisations consume an estimator and return a result.
Naive
These return a NaiveOptimisationResult.
- Allocates each asset a weight inversely proportional to its volatility, or to its variance when
sq = true.InverseVolatility - Allocates the same weight to every asset in the universe.
EqualWeighted - Draws portfolio weights at random from a Dirichlet distribution with concentration parameter
alpha.RandomWeighted - Holds the weights it was handed, and solves nothing.
PreviousWeights
Naive optimisation features
- Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds
Weight finalisers
- Iteratively projects weights into the feasible region defined by weight bounds.
IterativeWeightFinaliser
Uses a JuMP optimisation model to enforce weight bounds. JuMPWeightFinaliser
JuMPWeightFinaliser- Minimises the L1 norm of relative weight deviations when enforcing weight bounds.
RelativeErrorWeightFinaliser - Minimises the L2 norm of relative weight deviations when enforcing weight bounds.
SquaredRelativeErrorWeightFinaliser - Minimises the L1 norm of absolute weight deviations when enforcing weight bounds.
AbsoluteErrorWeightFinaliser - Minimises the L2 norm of absolute weight deviations when enforcing weight bounds.
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.
- Configures one solver backend, its attributes, and the statuses its solutions must reach.
Solver - Main JuMP-based portfolio optimiser configuration.
JuMPOptimiser
Objective functions
- Minimum risk
MinimumRisk - Maximum utility
MaximumUtility - Maximum return over risk ratio
MaximumRatio - Maximum return
MaximumReturn - Internal objective that maximises the expression of one return term.
MaximumElementReturn
Mean-Risk portfolio optimiser. MeanRisk and NearOptimalCentering
MeanRisk and NearOptimalCenteringSweeps the efficient frontier by solving the model once at each of N evenly spaced bound values. Frontier
N evenly spaced bound values. Frontier- Return based
- Risk based
Bound spacing FrontierBoundEstimator
FrontierBoundEstimator- Passes bound values through unchanged (identity transformation).
LinearBound - Applies a square-root transformation to bound values before enforcing them.
SquareRootBound - Applies a squaring transformation to bound values before enforcing them.
SquaredBound
Optimisation estimators
- Mean-Risk
MeanRiskreturns aMeanRiskResult - Near Optimal Centering
NearOptimalCenteringreturns aNearOptimalCenteringResult - Factor Risk Contribution
FactorRiskContributionreturns aFactorRiskContributionResult
Near Optimal Centering formulations NearOptimalCentering
NearOptimalCentering- Constrained Near Optimal Centering algorithm.
ConstrainedNearOptimalCentering - Unconstrained Near Optimal Centering algorithm.
UnconstrainedNearOptimalCentering - Intermediate result type storing the setup data for Near Optimal Centering.
NearOptimalSetup
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-level Risk Budgeting algorithm.
AssetRiskBudgeting
Fromulations
- Log-barrier formulation for Risk Budgeting.
LogRiskBudgeting - Mixed-integer formulation for Risk Budgeting.
MixedIntegerRiskBudgeting
- Factor-level Risk Budgeting algorithm.
FactorRiskBudgeting
Optimisation estimators
- Risk Budgeting
RiskBudgetingreturns aRiskBudgetingResult
Relaxed Risk Budgeting RelaxedRiskBudgeting returns a RelaxedRiskBudgetingResult
RelaxedRiskBudgeting returns a RelaxedRiskBudgetingResult- Bounds the risk variable by the portfolio standard deviation alone, which is the relaxation with no extra term.
BasicRelaxedRiskBudgeting - Adds a second cone on an auxiliary scalar, which lifts the floor on the risk variable and improves numerical stability.
RegularisedRelaxedRiskBudgeting - Bounds the auxiliary scalar by the individual standard deviations rather than the portfolio one, weighted by
p.RegularisedPenalisedRelaxedRiskBudgeting
Traditional optimisation features
- Abstract supertype for custom JuMP objective implementations.
CustomJuMPObjective - Abstract supertype for custom JuMP constraint implementations.
CustomJuMPConstraint - Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds
Budget
Directionality
- Long
- Short
Type
- Exact
- Bounds the sum of the portfolio weights inside a closed interval, rather than pinning it to one value.
BudgetRange
Resolves a minimum-holding threshold written in asset or group names against a universe. ThresholdEstimator and Threshold
ThresholdEstimator and ThresholdDirectionality
- Long
- Short
Type
- Asset
- Names the group name key a binary asset-group membership matrix is built from.
AssetSetsMatrixEstimator
- Holds the linear constraint equations to parse, and the universe key their names resolve against.
LinearConstraintEstimatorandLinearConstraint - Bundles a network source with the centrality algorithm that scores its assets.
CentralityEstimator
Cardinality
- Asset
- Holds the linear constraint equations to parse, and the universe key their names resolve against.
LinearConstraintEstimatorandLinearConstraint - Set(s)
- Holds the linear constraint equations to parse, and the universe key their names resolve against.
LinearConstraintEstimatorandLinearConstraint
- Names the per-asset turnover bounds, for
turnover_constraintsto align to a universe.TurnoverEstimatorandTurnover - Names the per-asset fee rates, for
fees_constraintsto align to a universe.FeesEstimatorandFees - Bounds how far the portfolio return series may drift from a benchmark return series.
TrackingError - Caps how many related assets may be held at once, refitting the structure from returns.
IntegerPhylogenyEstimatorandSemiDefinitePhylogenyEstimator
Portfolio returns
- One return term, or a vector of them weighted-summed into the model's return expression
- Carries one return term's own weight in the return sum, its own lower bound, and the two charges netted out of it.
JuMPReturnsSettings
Arithmetic ArithmeticReturn
ArithmeticReturn- Holds the element-wise lower and upper bounds of a box uncertainty set on a mean vector or on a covariance matrix.
BoxUncertaintySet,BoxUncertaintySetAlgorithm,EllipsoidalUncertaintySet,EllipsoidalUncertaintySetAlgorithm,NormBallUncertaintySet, andNormBallUncertaintySetAlgorithm - Custom expected returns vector
- Deferred expected returns estimator, resolved against the optimisation's own prior
- Logarithmic
LogarithmicReturn - None
NoReturn
Risk vector scalarisation
- Adds the scaled risk measures together.
SumScalariser - Reports the largest of the scaled risk measures, so the aggregate is the worst of them.
MaxScalariser - Smooths the maximum of the scaled risk measures, so every measure keeps a share of the aggregate.
LogSumExpScalariser
- Custom constraint
- Number of effective assets
Regularisation penalty
- L1
- L2-norm regularisation term added to the optimisation objective.
L2Regularisation - Lp-norm regularisation term added to the optimisation objective.
LpRegularisation - L-Inf
Weight-norm constraints
Where a regularisation penalty prices a norm in the objective, these bound it instead.
- L2 (
l2c) - Lp (
lpc) - L-Inf (
linfc)
- Estimator type for normalised constant relative risk aversion (CRRA) OWA weights.
NormalisedConstantRelativeRiskAversion
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.
- Base configuration for hierarchical clustering-based portfolio optimisers.
HierarchicalOptimiser
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.
Each result carries the measures and scalarisers its optimisation ran under, stored resolved, and shares its remaining fields through an embedded HierarchicalResult core reached as res.hr or directly as res.w, res.pr and the rest.
- Hierarchical Risk Parity
HierarchicalRiskParityreturns aHierarchicalRiskParityResult - Hierarchical Equal Risk Contribution
HierarchicalEqualRiskContributionreturns aHierarchicalEqualRiskContributionResult - Shared field core for hierarchical (clustering-based) optimisation results.
HierarchicalResult
Hierarchical clustering optimisation features
- Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds - Names the per-asset fee rates, for
fees_constraintsto align to a universe.FeesEstimatorandFees
Risk vector scalarisation
- The clustering optimisers accept every scalariser; a
JuMPoptimiser accepts only the non-hierarchical three - Adds the scaled risk measures together.
SumScalariser - Reports the largest of the scaled risk measures, so the aggregate is the worst of them.
MaxScalariser - Smooths the maximum of the scaled risk measures, so every measure keeps a share of the aggregate.
LogSumExpScalariser - Reports the smallest of the scaled risk measures, so the aggregate is the mildest of them.
MinScalariser
Weight finalisers
- Iteratively projects weights into the feasible region defined by weight bounds.
IterativeWeightFinaliser
Uses a JuMP optimisation model to enforce weight bounds. JuMPWeightFinaliser
JuMPWeightFinaliser- Minimises the L1 norm of relative weight deviations when enforcing weight bounds.
RelativeErrorWeightFinaliser - Minimises the L2 norm of relative weight deviations when enforcing weight bounds.
SquaredRelativeErrorWeightFinaliser - Minimises the L1 norm of absolute weight deviations when enforcing weight bounds.
AbsoluteErrorWeightFinaliser - Minimises the L2 norm of absolute weight deviations when enforcing weight bounds.
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
Collects the risk measure, the interpolation parameter $\gamma$, and the two algorithms that one Schur complement bundle runs with. SchurComplementParams
SchurComplementParams- Searches $[0, \gamma]$ for the value that gives the lowest portfolio variance.
MonotonicSchurComplement - Runs the allocation at the $\gamma$ the caller gave, with no search.
NonMonotonicSchurComplement
Schur complementary optimisation features
- Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds - Names the per-asset fee rates, for
fees_constraintsto align to a universe.FeesEstimatorandFees
Weight finalisers
- Iteratively projects weights into the feasible region defined by weight bounds.
IterativeWeightFinaliser
Uses a JuMP optimisation model to enforce weight bounds. JuMPWeightFinaliser
JuMPWeightFinaliser- Minimises the L1 norm of relative weight deviations when enforcing weight bounds.
RelativeErrorWeightFinaliser - Minimises the L2 norm of relative weight deviations when enforcing weight bounds.
SquaredRelativeErrorWeightFinaliser - Minimises the L1 norm of absolute weight deviations when enforcing weight bounds.
AbsoluteErrorWeightFinaliser - Minimises the L2 norm of absolute weight deviations when enforcing weight bounds.
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.
- Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds - Names the per-asset fee rates, for
fees_constraintsto align to a universe.FeesEstimatorandFees
Weight finalisers
- Iteratively projects weights into the feasible region defined by weight bounds.
IterativeWeightFinaliser
Uses a JuMP optimisation model to enforce weight bounds. JuMPWeightFinaliser
JuMPWeightFinaliser- Minimises the L1 norm of relative weight deviations when enforcing weight bounds.
RelativeErrorWeightFinaliser - Minimises the L2 norm of relative weight deviations when enforcing weight bounds.
SquaredRelativeErrorWeightFinaliser - Minimises the L1 norm of absolute weight deviations when enforcing weight bounds.
AbsoluteErrorWeightFinaliser - Minimises the L2 norm of absolute weight deviations when enforcing weight bounds.
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.
- Names the per-asset fee rates, for
fees_constraintsto align to a universe.FeesEstimatorandFees - Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds
Weight finalisers
- Iteratively projects weights into the feasible region defined by weight bounds.
IterativeWeightFinaliser
Uses a JuMP optimisation model to enforce weight bounds. JuMPWeightFinaliser
JuMPWeightFinaliser- Minimises the L1 norm of relative weight deviations when enforcing weight bounds.
RelativeErrorWeightFinaliser - Minimises the L2 norm of relative weight deviations when enforcing weight bounds.
SquaredRelativeErrorWeightFinaliser - Minimises the L1 norm of absolute weight deviations when enforcing weight bounds.
AbsoluteErrorWeightFinaliser - Minimises the L2 norm of absolute weight deviations when enforcing weight bounds.
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.
- Names the per-asset fee rates, for
fees_constraintsto align to a universe.FeesEstimatorandFees - Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds
Weight finalisers
- Iteratively projects weights into the feasible region defined by weight bounds.
IterativeWeightFinaliser
Uses a JuMP optimisation model to enforce weight bounds. JuMPWeightFinaliser
JuMPWeightFinaliser- Minimises the L1 norm of relative weight deviations when enforcing weight bounds.
RelativeErrorWeightFinaliser - Minimises the L2 norm of relative weight deviations when enforcing weight bounds.
SquaredRelativeErrorWeightFinaliser - Minimises the L1 norm of absolute weight deviations when enforcing weight bounds.
AbsoluteErrorWeightFinaliser - Minimises the L2 norm of absolute weight deviations when enforcing weight bounds.
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 Allocation portfolio optimiser. DiscreteAllocation
DiscreteAllocationWeight finalisers
- Iteratively projects weights into the feasible region defined by weight bounds.
IterativeWeightFinaliser
Uses a JuMP optimisation model to enforce weight bounds. JuMPWeightFinaliser
JuMPWeightFinaliser- Minimises the L1 norm of relative weight deviations when enforcing weight bounds.
RelativeErrorWeightFinaliser - Minimises the L2 norm of relative weight deviations when enforcing weight bounds.
SquaredRelativeErrorWeightFinaliser - Minimises the L1 norm of absolute weight deviations when enforcing weight bounds.
AbsoluteErrorWeightFinaliser - Minimises the L2 norm of absolute weight deviations when enforcing weight bounds.
SquaredAbsoluteErrorWeightFinaliser
- Greedy Allocation portfolio optimiser.
GreedyAllocation - Problem data fed to a finite allocation optimiser.
FiniteAllocationInput
Cross validation
- Prediction on unseen data
PredictionReturnsResult,PredictionResult,MultiPeriodPredictionResult,PopulationPredictionResultviapredict(res::NonFiniteAllocationOptimisationResult, rd::ReturnsResult),fit_and_predict - Union of concrete
PredictionScorersubtypes and plain functions that score aPopulationPredictionResult.PredictionCrossValScorer,NearestQuantilePrediction, andquantile_by_measure - Run cross-validated portfolio optimisation and return predictions over all folds.
cross_val_predict - Fit optimisation estimator
opton returns datardand immediately produce aPredictionResultfor the same data.fit_predict - Return the number of cross-validation splits (folds) that would be produced by
cvfor the given returns datard.n_splits - Find the optimal
(n_folds, n_test_folds)pair for combinatorial cross-validation by minimising a weighted cost that balances the average training size against the number of test paths.optimal_number_folds
Split str into an array of substrings on occurrences of the delimiter(s) dlm. split and fit_and_predict
str into an array of substrings on occurrences of the delimiter(s) dlm. split and fit_and_predict- K-Fold
KFoldreturns aKFoldResult - Combinatorial
CombinatorialCrossValidationreturns aCombinatorialCrossValidationResult
Walk forward WalkForwardEstimator return a WalkForwardResult
WalkForwardEstimator return a WalkForwardResult- Implements index-based walk-forward cross-validation for time series, supporting purging and flexible train/test windowing.
IndexWalkForwardandDateWalkForward - Fold Fit
OnlineStepfits each fold by the online step, threading one estimator from fold to fold - Resume
Resumecontinues an online walk-forward from its Result over the full history extended, andvcatstacks the two Results
- Multiple randomised
MultipleRandomisedreturns aMultipleRandomisedResult
A scheme reads a fold under an evaluation convention. SelfFinancingDrift reads a fold's series on the weights the fund holds rather than the weights the optimiser chose, and the fold then carries a HeldWeightsResult. A walk-forward may also thread those held weights into the fold that follows it.
- Thread the weights a fold held after its last observation into the fold that follows it.
DriftedWeights - Records what a fold actually held, so a reader can recover the weight path of that fold.
HeldWeightsResult
Performs grid search cross-validation for portfolio optimisation estimators. search_cross_validation
search_cross_validation- Performs grid search cross-validation for portfolio optimisation estimators.
GridSearchCrossValidation - Randomised search cross-validation estimator for portfolio optimisation.
RandomisedSearchCrossValidation
Scoring a parameter set CrossValidationSearchScorer
CrossValidationSearchScorer- A
CrossValidationSearchScorerthat selects the parameter set with the highest mean score across cross-validation splits.HighestMeanScore
- Wraps a cross-validation scheme and an optional scorer to form a complete optimisation cross-validation pipeline.
OptimisationCrossValidation - Abstract supertype for estimators that determine the number of random subsets to draw.
NumberSubsetsEstimatorandSubsetSizeEstimator
Covariance forecast evaluation
covariance_forecast_evaluation judges a covariance estimator's, or a prior's, forecast on the returns realised after it, step by step over a walk-forward, in batch when the scheme refits and online when it declares a Fold Fit. The test rows are centred on the location the forecast is about, read off the estimator, and the diagnostics are kept per step so the summary, the comparison and the re-projection are verbs over one Result.
Evaluate a covariance forecast out of sample over a walk-forward, in batch or online. covariance_forecast_evaluation
covariance_forecast_evaluation- The per-step diagnostics of a covariance forecast over a walk-forward, and its forecasts on request.
CovarianceForecastEvaluationResult - The per-step kernel on bare arrays
covariance_forecast_step, for a forecast the library did not produce
The quantity the forecast is judged against.
- Judges a covariance forecast against the realised covariance of the returns that follow it.
RealisedCovariance - Judges a covariance forecast against the outer product of the return earned over the horizon.
HorizonReturn
The verbs above the Result.
- Summarise one or more covariance forecast evaluations, one entry per evaluation.
covariance_forecast_summary - The headline statistics of one or more covariance forecast evaluations, one entry per evaluation.
CovarianceForecastSummaryResult - Test whether two covariance forecasts differ in expected loss, per loss.
covariance_forecast_compare - The Diebold–Mariano–West comparison of two covariance forecasts, one row per loss.
CovarianceForecastComparisonResult - Re-project the stored forecasts of an evaluation on a new test portfolio.
covariance_forecast_portfolio
Pipeline
A Pipeline reifies an end-to-end workflow as data: an ordered list of steps run left-to-right over a PipelineContext, so preprocessing, priors, and the optimiser travel together as one estimator and can be cross-validated or tuned as a unit.
- A reified end-to-end portfolio workflow: an ordered list of steps executed left-to-right over a
PipelineContext.PipelineandPipelineResult - Explicit pipeline step wrapper — used when a step's slots or its routing intent must be stated rather than inferred.
PipelineStep - The accumulating blackboard threaded through a pipeline's steps.
PipelineContext - The mu/sigma pair held by the
uncertaintyslot of aPipelineContext.PipelineUncertaintySets
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.
- Plot the cumulative returns of a portfolio.
plot_portfolio_cumulative_returns - Plot the cumulative returns of individual assets, selecting the most relevant via
N.plot_asset_cumulative_returns
Portfolio composition.
- Plot portfolio composition as a bar chart of asset weights.
plot_composition
Multi portfolio.
- Plot portfolio composition as a stacked bar chart.
plot_stacked_bar_composition - Plot portfolio composition as a stacked area chart.
plot_stacked_area_composition
Risk contribution.
- Plot per-asset risk contribution as a bar chart.
plot_risk_contribution - Plot per-factor risk contribution as a bar chart, including the constant (idiosyncratic) term.
plot_factor_risk_contribution
- Plot a hierarchical clustering dendrogram with coloured cluster regions.
plot_dendrogram - Plot a reordered correlation/covariance heatmap with flanking dendrograms and coloured cluster boxes.
plot_clusters - Plot portfolio drawdown over time.
plot_drawdowns - Line plot of the rolling maximum drawdown over a sliding window.
plot_rolling_drawdowns - Plot a histogram of portfolio returns with vertical risk-measure lines and an optional fitted Normal distribution.
plot_histogram - Scatter plot of risk/return measures across a collection of portfolio weight vectors.
plot_measures - Line plot of a risk or return measure evaluated over a rolling window of portfolio returns.
plot_rolling_measure - Sort a collection of portfolio results by risk (
x), connect them with a line to trace the efficient frontier, and optionally annotate the minimum-risk and maximum-score portfolios.plot_efficient_frontier - Box plot of per-asset weight distributions across cross-validation folds or population members.
plot_weight_stability - Line plot of portfolio turnover (L1 weight change) over time.
plot_turnover - Overlay portfolio cumulative returns against one or more benchmark return series from
rd.B.plot_benchmark
Moments and priors
- Bar chart of per-asset expected returns (μ vector).
plot_mu - Bar chart of per-asset volatility (√diag(Σ)).
plot_sigma - Standalone correlation (or covariance) heatmap without clustering or dendrograms.
plot_correlation - Heatmap of the coskewness matrix (N × N²) from a
HighOrderPrior.plot_coskewness - Eigenvalue spectrum of the cokurtosis matrix (N² × N²) from a
HighOrderPrior.plot_cokurtosis - Bar chart of eigenvalues of the covariance/correlation matrix, sorted in descending order.
plot_eigenspectrum - Three-panel composite plot summarising a prior result:
plot_prior
Factor models
- Bar chart of per-factor expected returns (
pr.fpr.mu, from a factor model prior).plot_factor_mu - Correlation/covariance heatmap of the factor covariance matrix (
pr.fpr.sigma).plot_factor_sigma - Heatmap of the factor loadings matrix B (assets × factors) from a prior with a regression model.
plot_factor_loadings
Cross-sectional regression diagnostics
- Plot the weighted cross-sectional coefficient of determination of every observation.
plot_cs_regression_r2 - Plot the adjusted cross-sectional coefficient of determination of every observation.
plot_cs_regression_adjusted_r2 - Plot the Akaike information criterion of every cross-sectional fit.
plot_cs_regression_aic - Plot the Bayesian information criterion of every cross-sectional fit.
plot_cs_regression_bic - Plot the t-statistic of every factor return, one series per factor.
plot_cs_regression_t_stats - Plot the fraction of observations at which each factor's t-statistic exceeds a threshold.
plot_cs_regression_t_stat_exceedance_rate - Plot the variance inflation factor of every factor, one series per factor.
plot_exposure_vif - Plot the condition number of the cross-sectional design of every observation.
plot_exposure_condition_number
Cross-sectional exposure diagnostics
- Plot the time-averaged correlation between every pair of factor exposures as a heatmap.
plot_exposure_correlation - Plot the stability of every factor exposure, one series per factor.
plot_exposure_stability - Plot the weighted cross-sectional standard deviation of every factor exposure, one series per factor.
plot_exposure_dispersion - Plot the cross-sectional distribution of one factor exposure as a histogram.
plot_exposure_distribution - Plot the running sum of the information coefficient of every factor exposure, one series per factor.
plot_cumulative_exposure_ic
Cross-sectional idiosyncratic diagnostics
- Plot the cross-sectional standard deviation of the standardised idiosyncratic returns against the observation axis.
plot_idio_calibration - Plot the share of assets whose standardised idiosyncratic return exceeds a threshold, against the observation axis.
plot_idio_tail_rate - Plot the cross-sectional excess kurtosis of the standardised idiosyncratic returns against the observation axis.
plot_idio_kurtosis - Plot the cross-sectional skewness of the standardised idiosyncratic returns against the observation axis.
plot_idio_skewness - Plot the information coefficient of the predicted idiosyncratic volatility against the observation axis.
plot_idio_vol_ic - Plot the residual dependence of the standardised idiosyncratic returns on the predicted volatility, against the observation axis.
plot_idio_vol_residual_dependence
Factor model summary and factor forecasts
- Plot the columns of a factor model summary as a grouped bar chart, one group per column and one bar per factor.
plot_factor_model_summary - Plot the cumulative return of every factor, one series per factor.
plot_factor_cumulative_returns - Plot the forecast correlation of the factor returns as a heatmap.
plot_factor_forecast_correlation - Plot the forecast volatility of every factor return as a horizontal bar chart, ordered from the smallest.
plot_factor_forecast_volatilities
Forecast evaluation
- Plot the running sum of the information coefficient of a Return Forecast: both coefficients of one forecast, or one coefficient of several forecasts overlaid.
plot_forecast_cumulative_ic - Plot the running mean of both information coefficients of a Return Forecast over a window.
plot_forecast_rolling_ic - Plot the cumulative return of the books a Return Forecast states on its own: both books of one forecast, or one book of several forecasts overlaid.
plot_forecast_cumulative_returns - Plot the cumulative top-minus-bottom spread of a Return Forecast, one series per quantile.
plot_forecast_quantile_returns - Plot the calibration curve of a Return Forecast against the slope fitted through it.
plot_forecast_calibration - Plot both mean information coefficients of a Return Forecast against the holding period.
plot_forecast_ic_by_holding_period - Plot the annualised return and the Sharpe ratio of both books against the holding period.
plot_forecast_portfolio_by_holding_period - Plot both mean information coefficients of a Return Forecast against the forward window.
plot_forecast_ic_decay - Plot the annualised return and the Sharpe ratio of both books against the forward window.
plot_forecast_portfolio_decay - Plot the contemporaneous correlation of a Return Forecast with every factor exposure.
plot_forecast_factor_correlation - Plot a
ForecastSummaryResultas a grouped bar chart, one series per forecast.plot_forecast_evaluation_summary - Comparison overlays of several forecasts, one series per evaluation on the dates they share, through the vector methods of
plot_forecast_cumulative_icandplot_forecast_cumulative_returns
Phylogeny
- Plot the asset network (MST, PMFG, TMFG, or adjacency) as a graph using
GraphRecipes.graphplot.plot_network - Bar chart of asset centrality scores, sorted in descending order.
plot_centrality
Cross validation
- Bar chart of cross-validation scores (one bar per fold or population member).
plot_cv_scores - Four-panel composite plot for a walk-forward cross-validation result:
plot_cv_dashboard
Factor attribution
- Plot the volatility contribution of each factor, or of each factor family, as a bar chart.
plot_attribution_vol_contrib - Plot the mean return contribution of each factor, or of each factor family, as a bar chart with error bars.
plot_attribution_mu_contrib - Plot the portfolio's exposure to each factor, or to each factor family, as a bar chart with its spread.
plot_attribution_exposure - Plot the mean return contribution of each factor against its volatility contribution, as a labelled scatter.
plot_attribution_mu_vs_vol
Dashboards
- Four-panel composite plot for a single optimisation result:
plot_portfolio_dashboard - Bar chart of annualised portfolio performance metrics: annualised return, annualised volatility, Sharpe ratio, Sortino ratio, Calmar ratio, maximum drawdown %, and CVaR %.
plot_performance_summary