Capability catalogue
This page lists what PortfolioOptimisers.jl can do, grouped by the job that each type or function does. Each entry links to its docstring, on a public API page, or on a private API page for a name outside the public API.
The documentation build writes this page with docs/generate_capability_catalogue.jl. The grouping comes from docs/capability_catalogue.jl. The description of an entry is the first sentence of its docstring, unless the catalogue gives the entry its own label. The build fails when a type that you can choose, such as an estimator or an algorithm, has no entry here.
The type hierarchy lists the same types by their supertypes.
Core abstractions
Every component of the library is one of three kinds. An estimator is a configuration, which names a method and holds its hyperparameters. An algorithm selects a behaviour, and you pass it to an estimator. A result holds what a computation returns. You choose the estimators and the algorithms, and you get the results back.
Every estimator, algorithm and result is immutable, so the library passes a value it computes at run time down a composed estimator by rebuilding that estimator.
- Rebuild an estimator, an algorithm or a result with runtime values.
factory
A field that takes the size of a part of a set, such as the assets of a subset or the rows of a window, holds a count of its members or a fraction of the set. The wrapper states which, so a search grid that promotes its values keeps each reading.
- The size of a part of a set, stated as a number of its members.
CountOfandFractionOf
Preprocessing
- Compute returns from the price data.
prices_to_returnsandReturnsResult - Holds asset prices with optional factor, benchmark, Exogenous Series and implied volatility series, each a
TimeSeries.TimeArray.PricesResult - Build the Currency Excess Index of each currency, a level series for the Exogenous Series of a
PricesResult.currency_excess_index
Preprocessing estimator that converts price-level data into returns-level data. PricesToReturns, fit_preprocessing, and apply_preprocessing
PricesToReturns, fit_preprocessing, and apply_preprocessing- Preprocessing estimator that drops the assets and the observations of a price window whose share of missing prices exceeds a threshold.
MissingDataFilterandMissingDataFilterResult
Rules for the column shares of the missing-data filter
- Reads the column shares of a
MissingDataFilteragain over the kept observations, until no asset drops.FixedPointFilter - Reads the column shares of a
MissingDataFilterone time, over every observation of the training window.SinglePassFilter
Price gap conventions
- Fills the price gaps inside the listing of each asset with a stated convention, and changes no other price.
PriceGapFillandPriceGapFillResult - States that a price did not move across a gap, so the fill holds the last observed price forward.
CarriedPrice
Conventions for the return that ends a price gap
- Books the whole move across a Held Gap on the observation that ends it, so the gap holds
knon-finite returns.CatchUpGapReturn
Asset selection
- Asset selector that scores every asset with a risk measure or an Asset Scorer, and keeps the assets that a rule admits.
ScoreSelector,ZeroVarianceFilter, andCompleteAssetSelector - Asset selector that drops the assets whose information other assets already carry.
RedundancySelector - Fitted result of any
AbstractAssetSelector.AssetSelectorResult
Selection rules
- Take a number of assets from each end of the order of the scores, then keep them or drop them.
RankRule - Keep the assets whose score is strictly inside the band
(lo, hi).ThresholdRule
Asset scorers
- Scores each asset with a risk measure, or with a vector of them, on each test window of a cross-validation scheme, and aggregates the values over the windows.
FoldRiskScorer - Scores each asset by the mean weight, or by the selection frequency, that an optimiser gives it over the splits of a cross-validation scheme.
WeightMassScorer - Scores each asset by a statistic of its Panel Fields, or of a Descriptor, over the observations of the returns data.
PanelFieldScorer
Fold aggregations
- Scores an asset by the mean of its statistic over the test windows that cover it.
MeanFoldScore - Scores an asset by the median of its statistic over the test windows that cover it.
MedianFoldScore - Scores an asset by its worst statistic over the test windows that cover it.
WorstFoldScore
The universe a price panel states
The position of a gap in a price column tells you whether the asset was in the universe. A run of gaps at the start means that the asset was not yet listed. A run at the end means that it was delisted. A gap between two prices is a suspension, and the asset stays listed through it. listing_span applies that rule to a table of prices, and universe_masks moves the answer onto the dates of the returns. The answer is the two masks an AssetPanel holds, one for the assets that are listed at each date and one for the listed assets whose return is also finite. If you have a listing calendar of your own, pass it at the same point, and it replaces the answer derived from the prices.
- 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 price table that the conversion to returns reads. It unifies the two conventions for an absent price, joins the factor and benchmark tables, and collapses the frequency. It runs once on the whole history, not as a Pipeline step, for two reasons. The join can add or drop dates, and the collapse renumbers the observations, but a cross-validation cuts its folds once, on the dates of the table. The rule for gaps above also needs the whole history, and a step sees only one window. The table it returns holds the listing span of each asset, the dates from its first price to its last. PricesToReturns moves that span onto the dates of the returns and gives the ReturnsResult an AssetPanel that states the universe. It does this for every table, a table with no gaps included. If a returns result holds no panel, you built it without the ingestion layer.
- Estimator that assembles raw price series into a
PricesResultand its Listing Span, which the conversion then reads.PriceIngestionandprice_ingestion
- Cut price or returns data into a training window of the first rows and a test window of the last rows.
train_test_split,TrainTestSplit, andTrainTestSplitResult
Return the asset returns of rd that a reader with the source x_src fits on. benchmark_relative_returns
rd that a reader with the source x_src fits on. benchmark_relative_returnsSources of the returns that a reader fits on
- Makes a reader of the returns fit on the asset returns
rd.X, as the caller gave them.DataSource - Makes a reader of the returns fit on the returns in excess of the benchmark,
rd.X - rd.B, the Excess Frame.ExcessSource - Makes a reader of the returns read the Prior Result in place of the returns data.
PriorSource
Build the AssetPanel that a PricesResult or a ReturnsResult holds, from the raw, blank-carrying form of each Panel Field. asset_panel, AssetPanel, panel_field, panel_field_values, panel_feature_matrix, panel_dataframe, panel_manifest, panel_info, panel_align_active, feature_matrix, feature_labels, and panel_input
AssetPanel that a PricesResult or a ReturnsResult holds, from the raw, blank-carrying form of each Panel Field. asset_panel, AssetPanel, panel_field, panel_field_values, panel_feature_matrix, panel_dataframe, panel_manifest, panel_info, panel_align_active, feature_matrix, feature_labels, and panel_inputKinds of panel field, the named quantities such as a market capitalisation or a sector that a panel holds per asset
- 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 label axis carries its own labels, and optionally its own groups.
TensorPanelField
Inputs that build a panel field
- 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 label axis, its second axis, carries its own labels, and optionally its own groups.
TensorPanelInput
Blank-cell policies
The default fill policy nothing refuses a blank cell, with an error that names the panel field.
- 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 the values of the assets at one observation against each other, through cross_sectional_transform. You pass the benchmark weights and the group labels to the call. cross_sectional_groups derives the group labels from a one-hot array or from a categorical panel field, such as a sector.
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 co-moment matrix to the nearest positive definite matrix. Posdef, posdef!, and posdef
Posdef, posdef!, and posdef- Repairs a covariance matrix by a clip of the eigenvalues of its correlation matrix, and keeps its variances.
ClippedNearestCorrelation
Applies a denoising algorithm to a covariance or correlation matrix. Denoise, denoise!, and denoise
Denoise, denoise!, and denoise- Denoises a matrix by setting its noise eigenvalues to zero.
SpectralDenoise - Denoises a matrix by replacing its noise eigenvalues with their own mean.
FixedDenoise - Shrinks the off-diagonal part of the noise block of a matrix towards zero, and keeps the diagonal of that block.
ShrunkDenoise
- Removes the
nlargest principal components, the market modes, from a covariance or correlation matrix, or fewer when then-th of them ties with the next one.Detone,detone!, anddetone - Runs a positive definite repair, a denoising, a detoning and a custom algorithm on a matrix, in a set order.
MatrixProcessing,matrix_processing!,matrix_processing_step!, andmatrix_processing
Square roots of a covariance matrix
- Adds a growing ridge to the diagonal of a covariance matrix until its Cholesky factor exists.
RidgeCholeskySquareRootandmatrix_square_root - Takes the square root of a positive semidefinite covariance matrix from its eigendecomposition where the matrix has no Cholesky factor.
EigenFallbackSquareRoot
Regression models
A factor prior that regresses on a series of factor returns fits it with regression, which returns a Regression. ImpliedVolatilityRegression does not call it: it fits one of the regression targets below to each asset and predicts its realised volatility.
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
Fits each response by the elastic net, a least-squares fit with a penalty on the $L_1$ norm and on the squared $L_2$ norm of the coefficients. ElasticNet
ElasticNet- Sets the regularisation strength of an
ElasticNetat the geometric middle of its regularisation path.MiddleOfPath - Sets the regularisation strength of an
ElasticNetto a value that the caller states.FixedStrength - Adds the term of a strength that reads the response to the effective degrees of freedom of an
ElasticNet.StrengthDivergence
- Names the column of ones that a regression estimator adds to its design.
InterceptColumn
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
DimensionReductionRegressionBoth regressions make a choice over every observation: the factor set of each asset, or the components. A factor prior wrapped in Online fits again at each step, so the choice can move. A PinnedChoice in the choice field of the regression keeps the choice of the first fit, and the default BatchChoice chooses again at each step.
Cross-sectional regression types
A cross-sectional regression fits one model per observation, across the assets. cross_sectional_regression runs it and returns a CrossSectionalRegression. 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 - Solves the full-rank design directly, and drops the dependent columns of a rank-deficient one.
DependentColumnDrop - Solves the normal equations of a well-conditioned design, and gives every other design to
PseudoInverseFallback.NormalEquationsSolve
- Fits one external regression model per observation across the assets.
CrossSectionalTargetRegression
Cross-sectional regression weight policies
A weight policy sets the weight of each asset in the cross-sectional fit at one observation. A one-pass policy reads the cross-section alone. A two-pass policy also 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. It returns a series over the observations or one value per factor. You can pass the histories as bare arrays, already aligned for the lag. Every function except cs_gram also takes a CrossSectionalFactorModel. From the model, it lags the exposures and applies the factor family basis itself. The section on the factor family basis below says what that basis does.
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 Gram matrix 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 exposures as the AssetPanel holds them, with no lag and with one column per named factor. It returns a matrix over the factors, a series over the observations, or one value per factor. The input is bare arrays or a CrossSectionalFactorModel. With a model, the correlation, stability, dispersion and coverage functions derive the cross-sectional weights from an AbstractOrthogonalityMetric. The information coefficient uses the weights of the regression, and its reduced keyword maps the exposures through the factor family basis.
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, which by default is the volatility estimated at the observation before, so the forecast has not read the residual it scores. It then reads the cross-section of those ratios one observation at a time. Each function takes the residuals and the predicted volatilities as two bare arrays. A CrossSectionalFactorModel holds both histories, and every function except standardised_idio_returns also accepts one. Neither history has one column per factor, so this group applies no lag and no factor family basis.
The standardised residuals from which every series of this group is computed.
- 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 puts the diagnostics above into one table, with one row per named factor, before the factor family basis drops any. For each column it calls one function of the regression group or of the exposure group, and it aggregates the series over the observations. If the model holds no exposure history, every column that reads the exposures is nothing.
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 is a value per asset and observation that is computed from the panel fields of an AssetPanel, such as a momentum or a book-to-price ratio. descriptor computes it from a descriptor estimator. Each named descriptor below is a constructor function for one of the general estimators. It fixes the panel fields, the window or the half-life, and a keyword overrides each value 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
A factor exposure is the loading of one asset on one factor at one observation. factor_exposure computes it from an exposure estimator, which takes descriptors, one categorical panel field, the exposure of another factor, or only the active mask of the AssetPanel. An estimator for one factor returns an observations by assets matrix. The one-hot estimator 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
Observed factors
An observed factor has a return that you observe, and the fit does not estimate it. Its exposure estimator gives the exposures and names the column of E, the series of the returns data that belong to no asset, that holds the return.
- An observed factor whose exposure another Exposure Estimator gives, and whose return is one named column of the Exogenous Series.
ObservedExposure - The observed one-hot exposure of the currency of each asset, which gives the Currency Factors of a
CrossSectionalFactorPrior.CurrencyExposure
Factor family basis
A factor family is a set of one-hot factors, such as the sectors, whose exposures are collinear with a global factor. One member of each family is therefore redundant, and the fit changes the basis before it runs. factor_family_basis drops one member of each family and returns the change of basis, which varies over time. After the fit, the factor returns of the smaller basis expand back to one return per named factor.
- 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 is a prediction of the idiosyncratic return of each asset over the next period. return_forecast computes one from a return forecast estimator, which reads the descriptor scores and a fitted factor model, or takes a vector you state. Every fitted estimator starts from descriptor_scores. It winsorises and standardises each descriptor, can neutralise it against named factor exposures, and standardises it again. The forecast unit says what the descriptors forecast, the idiosyncratic return or the idiosyncratic Sharpe ratio. The estimator converts either one to a return.
- The shared recipe that turns Descriptors into cross-sectional scores.
DescriptorScoresanddescriptor_scores - A Return Forecast that the caller states.
CustomValueReturnForecast - A Return Forecast that is a fixed signed combination of Descriptor scores.
FixedWeightedReturnForecast - A Return Forecast that fits its Descriptor weights by exponentially weighted least squares.
ExpWeightedReturnForecast
A Return Forecast fitted by a regression target over every observation and asset at once. TargetReturnForecast
TargetReturnForecastThe calibration rule: the prequential default reads the forecast that the estimator published at each observation, and its linear fit folds through its normal equations.
- The prequential rule of the calibration of a
TargetReturnForecast.PrequentialCalibration - The least squares fit of a
LinearModelwith no keyword argument, solved from its normal equations.NormalEquationsFit
The calibration warm-up: the prediction that the calibration reads under a cross-validation estimator while no prediction is out of fold.
- Gives a
NaNuncalibrated prediction to every sample while no prediction is out of fold, so the calibration coefficient isNaN.NaNWarmup - Calibrates on the in-sample predictions of the fitted model while no prediction is out of fold.
InSampleWarmup
- The Descriptors forecast the idiosyncratic return itself.
IdiosyncraticReturnUnit - The Descriptors forecast the idiosyncratic return divided by the idiosyncratic volatility.
IdiosyncraticSharpeUnit
The weights of the neutralisation of the descriptor scores: the estimation mask, or the regression weights of the factor model.
- Weigh the Neutralisation of a
DescriptorScoresby the estimation mask of the Asset Panel.EstimationMaskWeights - Weigh the Neutralisation of a
DescriptorScoresby the regression weightsrwof the factor-model block.BlockRegressionWeights
A fitted estimator regresses the idiosyncratic return, which the factor model makes orthogonal to the exposures, so the part of its forecast that the exposures do not span is too small. The cross-sectional factor prior repairs it by one of these rules.
- Neutralise the scores of a fitted member against every estimated factor of the block, before the fit.
ScoreNeutralisation - Fit the calibration slope of a
TargetReturnForecaston the orthogonal part of its prediction too, and scaleα⊥by it.OrthogonalPartCalibration - Read the Return Forecast as the member states it.
UnadjustedForecast
Forecast evaluation
forecast_evaluation pairs each return forecast with the return it forecast, out of sample, and returns one result. Every statistic below is a function of that result. It accepts bare matrices as well as a fitted return forecast, so it scores a forecast from outside the library in the same way as one the library made.
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 function of 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, by name.
forecast_ic_summary - Return the share of the universe an evaluation scored, one entry per evaluation date.
forecast_coverage - Score the long-short portfolio that a Return Forecast states by itself.
forecast_portfolio - Score the top-minus-bottom spread of a Return Forecast, one column 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 order.
forecast_calibration
The same statistics over a range of forward windows, with every row computed on the same dates.
- 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
A summary table with one row per forecast, which compares the forecasts.
- 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 test of the mean information coefficient, which every summary takes as mt, the kernel of its long-run variance, the span its bandwidth reads, the algorithm that draws its bootstrap, and the law of the overlap test.
mt, the kernel of its long-run variance, the span its bandwidth reads, the algorithm that draws its bootstrap, and the law of the overlap test.- Tests the mean of a series against zero with a fixed-bandwidth long-run variance and a Gaussian wild bootstrap of its null law.
WildBootstrapMeanTest - Tests the mean of a series against zero over the untapered long-run variance at the order that the overlap of its windows sets.
OverlapMeanTest - Reads the divisor and the degrees of freedom off the first two moments of the sum of the centred products under the null hypothesis of the test.
NullMomentLaw - Divides the sum of the centred products by the number of entries less the width of the band, and reads the Student law with as many degrees of freedom.
BandCountLaw - Weights the autocovariance at lag $j$ by $1 - j / B$ up to the bandwidth $B$, and by zero after it.
BartlettKernel - Weights the autocovariance at every lag by the quadratic spectral kernel, which is positive near zero and decays with an oscillation.
QuadraticSpectralKernel - Sets the span of a series to the entries from its first finite entry to its last.
FiniteEntrySpan - Sets the span of a series to every entry of its grid, the missing entries at its ends included.
FullGridSpan - Draws one multiplier for each finite entry of the series, and computes the statistic of each draw from the product.
ObservationDraws - Draws the statistic of each draw from a few Gaussian sums, through quadrature features of the
QuadraticSpectralKernel.QuadratureSumDraws - Draws the statistic of each draw from a few Gaussian sums, through an eigen factor of the matrix of the kernel weights.
EigenSumDraws - Computes the weighted sum of the observed series through the quadrature features of the draws, as $\lVert \mathbf{\Phi}^{\intercal} \boldsymbol{d} \rVert^{2}$.
FeatureLongRunForm - Computes the weighted sum of the observed series at the exact kernel weights, by
long_run_quadratic_form.ExactLongRunForm
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 numeric Panel Fields, or of a Descriptor.
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, which every algorithm above accepts
- Grand mean
GrandMean - Volatility weighted
VolatilityWeighted - Mean squared error
MeanSquaredError
Intensity rules of James-Stein and Bayes-Stein, where nothing applies no clamp
nothing applies no clamp- Clamp into [0, 1]
UnitIntervalIntensity - Clamp at zero
NonNegativeIntensity
- 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 - Fits an inner expected returns estimator on a rolling or indexed window of observations.
WindowedExpectedReturns
Estimates expected returns by an exponentially weighted recursion that freezes on a holiday and resets on an inactive period. ExpWeightedExpectedReturns
ExpWeightedExpectedReturns- Divides the state of an exponentially weighted mean that starts at zero by the sum of its weights, so the mean is a weighted mean of the valid inputs whose weights sum to one.
ZeroStartDebias
Forecasts the next return of each asset as the move from the last price level to a statistic of a window of price levels. PriceLevelExpectedReturns
PriceLevelExpectedReturns- Averages the last
windowprice levels, which is the forecast of the on-line moving average reversion, OLMAR.MovingAverage - Averages the price levels with weights that fall exponentially with age, which is the forecast of the second form of the on-line moving average reversion, OLMAR-2.
ExponentialMovingAverage - Takes the spatial ($L_1$) median of the last
windowprice levels, which is the forecast of the robust median reversion, RMR.SpatialMedian - Takes the highest of the last
windowprice levels, which is the forecast of the peak price tracking, PPT.WindowPeak - Takes the price level
lagobservations ago, which is the forecast of the first form of the transaction-cost optimisation, TCO.LaggedPrice - Averages the price levels with a weight per asset that depends on the data, which is the forecast of the reweighted price relative tracking, RPRT.
ReweightedPriceRelative - Takes an exponential average of the last
windowprice levels, truncated and not normalised, which is the forecast of a rising asset in the trend promote price tracing, TPPT.TruncatedExponentialMovingAverage - Averages two Gaussian-weighted estimates of the next price level, which is the forecast of the Gaussian weighting reversion, GWR.
GaussianWeightedDoubleEstimate
Switches per asset between three statistics on the sign of a trend test, one statistic for a rising asset, one for a flat asset and one for a falling asset. TrendSwitch
TrendSwitch- Takes the sign of the sum of the slopes between every pair of the last
windowlevels, per asset, which is the trend test of the trend promote price tracing, TPPT.PairwiseSlopeSum - Compares the ridge-regularised slope of a straight line through the last
windowlevels with a threshold, per asset, which is the trend test of the local adaptive learning, LOAD.RegressionSlope
- Mixes several trend forecasts with radial basis weights, centred on the trend whose simplex-projected forecast had the best worst return over the last
windowperiods, which is the forecast of the adaptive input and composite trend representation, AICTR.CompositeTrend - Predicts the next price level in three states, which is the forecast of the kernel-based trend pattern tracking, KTPT.
KernelTrendPattern
- Reads the mean of a Prior as an expected-returns vector, so that any
meslot can hold a prior estimator.PriorExpectedReturns
Variance and standard deviation
Overloads Statistics.var and Statistics.std.
- Computes the marginal variance and standard deviation, with optional observation weights and an optional bias correction.
SimpleVariance - Fits an inner variance estimator on a rolling or indexed window of observations.
WindowedVariance
Covariance and correlation
Overloads Statistics.cov and Statistics.cor.
- Adapts a
StatsBase.CovarianceEstimatorto the calling convention of the library, and holds its observation weights with 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 measures only the downside.
SemiMoment
Estimates a covariance matrix from how often the two assets of each pair cross their thresholds together. GerberCovariance
GerberCovariance- Counts only the observations on which both assets cross their thresholds, as the original Gerber statistic does.
Gerber0 - Adds the observations on which exactly one asset crosses its threshold to the denominator of the Gerber statistic.
Gerber1 - Divides each net co-movement count by the geometric mean of the crossing counts of the two assets.
Gerber2
Estimates a covariance matrix from the co-movements of each pair of assets outside a confusion zone and an indecision zone. 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 covariance GerberIQCovariance, with a choice of estimator for the variance, the demeaning, the decay over time, the numerator and the denominator, and the rule of the effective number of observations
GerberIQCovariance, with a choice of estimator for the variance, the demeaning, the decay over time, the numerator and the denominator, and the rule of the effective number of observations- Squeezing template with one boundary and one weight for the whole return plane.
BasicGerberIQ - Squeezing template with four boundaries, one for each sign of a return in a concordant and in a discordant co-movement.
PartialGerberIQ - Squeezing template with three magnitude classes for each sign of a return.
FullGerberIQ - Exponential Gerber IQ temporal decay.
ExpGerberIQDecay - Scales the thresholds of each asset by the volatility of that asset.
AssetVolatilityGerberIQScaler - Counts the observations that a vector of weights is worth with the Kish count.
KishObservationCountandweight_observation_count
- Measures linear and non-linear codependence from doubly-centred pairwise distance matrices.
DistanceCovariance - Measures co-movement in the lower tail, the share of the worst returns of one asset that fall on the same dates as the worst returns of another asset.
LowerTailDependenceCovariance
Rank covariances
- Measures monotonic association with Kendall's tau, which counts concordant pairs against discordant pairs.
KendallCovariance - Measures monotonic association with Spearman's rho, the Pearson correlation of the rank-transformed returns.
SpearmanCovariance
- Estimates the covariance of a short window as a rank-one matrix along the principal direction of its price relatives.
RankOneCovariance
Measures codependence with mutual information, which detects a non-linear relationship that a correlation can miss. 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
- Returns a
PortfolioOptimisersCovariancethat projects the covariance matrix to the positive definite cone and then denoises it.DenoiseCovariance - Returns a
PortfolioOptimisersCovariancethat projects the covariance matrix to the positive definite cone and then detones it.DetoneCovariance
Shrinks a covariance matrix towards a target along the geodesic of the positive definite matrices. GeodesicShrinkageCovariance
GeodesicShrinkageCovarianceShrinkage targets
- Targets the identity matrix, which ignores the scale of the matrix being shrunk.
IdentityTarget - Targets the identity matrix scaled by the average variance, the target with condition number one.
ScaledIdentityTarget - Targets a matrix with the average variance on the diagonal and the average covariance everywhere else.
CommonCovarianceTarget - Targets a matrix that keeps the variances and gives every pair of assets the average correlation.
ConstantCorrelationTarget
- Returns a
PortfolioOptimisersCovariancethat projects the covariance matrix to the positive definite cone and then applies a matrix processing algorithm of the caller.ProcessedCovariance
Covariance estimator that scales a correlation matrix by the realised volatilities that it predicts from implied volatilities. ImpliedVolatility
ImpliedVolatility- Divides the last implied volatility of each asset by a volatility risk premium adjustment factor.
ImpliedVolatilityPremium - Predicts realised volatility by a log-linear regression on implied volatility and on the realised volatility of the window before.
ImpliedVolatilityRegression
- Runs a covariance estimator, then applies a matrix processing step to its result.
PortfolioOptimisersCovariance - Returns the correlation matrix of the wrapped estimator from both
covandcor.CorrelationCovariance - Fits an inner covariance estimator on a rolling or indexed window of observations.
WindowedCovariance
Exponentially weighted covariance and variance
- Estimates a covariance matrix by an exponentially weighted recursion in which each pair of assets ages on its own common observations, and which 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
Centring
- Estimates the location of each asset, and divides each deviation by the bias that the estimate puts in it.
EstimatedCentring - Takes the returns as deviations from a mean of zero, so each deviation is the return itself.
PreCentred - Takes each deviation from a location that starts at zero and is not divided by its weight.
ZeroStartCentring
Regime-adjusted covariance and variance
- Online exponentially weighted covariance estimator with regime-state adjustment.
RegimeAdjustedExpWeightedCovariance - Estimates the exponentially weighted variance of each asset, and scales it by one regime multiplier.
RegimeAdjustedExpWeightedVariance
Debias, HAC floor and HAC row volatility
- Divides the regime statistic by the exact bias that its method reads in the inverse of an estimated variance.
ExactDebias - Divides the regime statistic by the bias of the law of the estimate alone, without the dependence of the deviation on the estimate.
LawDebias - Floors each HAC-adjusted square at zero before it enters the variance recursion.
PerTermHacFloor - Divides each row of the separate correlation path under HAC by the volatility before the variance takes the row.
VolatilityBeforeUpdate - Divides each row of the separate correlation path under HAC by the volatility after the variance takes the row.
VolatilityAfterUpdate
Volatility of the separate correlation path
- Standardises each product of the separate correlation path by the bias-corrected variance.
BiasCorrectedVolatility
Level recursion of the Mahalanobis target
- Computes the Mahalanobis bias factor with the level recursion of
mahalanobis_level_biasalone, which takes the mean log-determinant of each level inside the exponential.MeanLevelRecursion - Computes the Mahalanobis bias factor with a second-order closure of the level recursion, which carries the covariance of the log-determinant of each level as well as its mean.
GaussianLevelRecursion
Indefinite block of the portfolio target
- Refuses a covariance block with a negative eigenvalue while the block is young, and scores it once the block is old.
RefuseIndefiniteWarmUp - Clips the eigenvalues of the correlation of a covariance block at zero, keeps the variances, and scores the direction on the clipped block, at every count.
ClipIndefiniteBlock - Scores a covariance block as it is, positive definite or not.
ScoreIndefiniteBlock
Regime adjustment methods
- Scales the volatility by the smoothed mean absolute standardised return over its expectation
x.FirstMomentRegimeAdjusted - Scales the volatility by the exponential of half the smoothed mean log of the standardised squared returns.
LogRegimeAdjusted - Scales the volatility by the root of the smoothed mean of the standardised squared returns.
RootMeanSquaredAdjusted
Shrinkage targets
- Targets the diagonal of a covariance matrix, in a regime adjustment and in a geodesic shrinkage.
DiagonalTarget - Scores an observation by its squared Mahalanobis distance against the covariance that stands before it.
MahalanobisTarget - Scores an observation by its squared return along each portfolio direction over the variance of that direction.
PortfolioTarget
Demeaning
- Centres the portfolio returns on their mean.
MeanCentering - Centres the portfolio returns on their median.
MedianCentering
Correlation smoothing
- Greedy removal of correlated assets.
PairwiseCorrelation - Group the assets by the connected components of a correlation graph, and keep the member of each group with the best score.
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 measures only the downside.
SemiMoment
- Fits an inner coskewness estimator on a rolling or indexed window of observations.
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 measures only the downside.
SemiMoment
- Fits an inner cokurtosis estimator on a rolling or indexed window of observations.
WindowedCokurtosis
Windowed moments
Every windowed estimator wraps a base moment estimator and recomputes it over a subset of the observations. An integer window selects the last window observations, a vector selects the observations at those indices, and the default nothing selects them all.
The rule field says which observations the window keeps when the estimator receives its observations one block at a time. A RollingWindow, the default, keeps the window at every fit, so the estimator is fitted again over the last observations at each step. A SeedWindow keeps the window at the first fit alone. After it, the inner estimator folds every new observation, so it needs an inner estimator with an exact update. The two rules give the same result in a batch fit.
- Keeps the last observations of the window at every fit, so the window rolls with each new observation.
RollingWindow - Keeps the last observations of the window at the first fit alone.
SeedWindow
Incremental fit
Some statistics have an exact update, in which the new value follows from a running state and one new observation. An estimator of such a statistic folds each new observation into its state, and it returns the statistic from the state without reading the sample again. The state is in the estimator's cache field. The sample mean, the sample variance and the full-moment sample covariance have an exact update. So do the FullMoment forms of Coskewness and Cokurtosis. The SemiMoment forms do not, because they clip each observation against a centre, and a new observation moves the centre.
Two functions fold an observation into the state. Each family of estimators implements partial_fit! as its fastest exact update, and the call can change the estimator you pass in. partial_fit returns a new estimator and leaves the one you pass in unchanged.
- Folds observations into an estimator's partial-fit state, and returns the estimator.
partial_fit! - Folds observations into a copy of the partial-fit state of an estimator, and returns the estimator that holds the copy.
partial_fit
An estimator of a statistic with no exact update keeps the observations it has seen instead, and it runs the batch computation over them to return the statistic. Online gives the estimator that store of observations. It applies once, at the warm-up before the first fold, and no Online wrapper remains in the estimator after that. Its max_history sets the largest number of observations the store keeps, and so the window of the fit. A wrapped estimator returns the batch statistic over the last max_history observations, and the scenario risk measures such as the conditional value at risk use the same rows. The store replaces the exact update of a statistic that has one, so the cap applies to it too. An estimator you leave unwrapped uses its exact update and stays fitted over every observation so far.
- Declares that an estimator takes the online step from a buffer of the observations it has seen.
Online
Coverage policy
By default, a moment estimator fits on the assets whose return is finite, and which the active mask of the AssetPanel marks as listed, at every observation of its window. This set of assets is the coverage universe. The rule keeps or drops each asset whole, so over an expanding window it can never admit an asset that lists after the first observation. A CoveragePolicy in the estimator's cvg field replaces the rule with available-case estimation, for that estimator alone. The estimator fits each entry of the result on the observations at which every asset of that entry is finite and active, and each entry has its own number of observations. An asset enters the result where its share of observations reaches min_coverage. The cvg field is nothing by default, and the estimator then fits on the coverage universe and writes NaN for every other asset.
The policy's alg field says what happens to an asset after it is delisted, with one type per rule. If your rule is none of the three below, write a new subtype of the family and implement its two functions, fold_inactive! and admits.
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
Two admitted assets can each have a variance and share too few observations for a covariance. The policy's peel field removes a set of assets that leaves no such pair, before the covariance is returned, and the covariance warns and names them, or refuses under strict = true. A removed asset is NaN across its row and column, so it is not investable. Set peel = nothing to skip the peel. If your rule is none of the two below, write a new subtype of AbstractPeel and implement peel_assets.
- Peels the fewest assets that remove every undetermined pair, and keeps the greedy peel whenever it is one of them.
MinimalPeel - Peels assets greedily, the asset with the most undetermined pairs first.
GreedyPeel
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 a metric over the columns of a distance matrix.
DistanceDistance
Each distance estimator takes one of the distance matrix algorithms below.
- 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}$, with no factor $1/2$.
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 the assets by their exposures, memberships, loadings or adjacencies, not by their returns. A feature distance turns it into a distance matrix directly, with no correlation matrix between the two.
Applies a metric to the rows of a feature matrix to make a distance matrix. FeatureDistance
FeatureDistance- Measures the angle between two feature vectors as a fraction of $\pi$.
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 library derives the feature matrix from an AssetPanel each time it needs it, and stores it nowhere. feature_matrix stacks the panel fields that a selector names. feature_labels gives one label per column. A vector of labels is also a selector, so if you pass it back, it rebuilds the matrix that the distance measured.
- Selects the labels of a tensor Panel Field whose group is one name, as the right side of a Feature Selector entry.
LabelGroup
Estimators that build the AssetPanel a distance measures
AssetPanel a distance measuresThe ape field says which AssetPanel the metric measures. With nothing, the metric reads the panel that the returns data holds. An estimator below builds a static panel when the metric runs. RegressionPanel builds it from the prior result of the subproblem that runs it, and PhylogenyPanel from the returns of that subproblem. A view of the assets therefore leaves the estimator unchanged, and each fold of a cross-validation refits it.
- Builds an Asset Panel that holds the factor loadings of the wrapped prior.
RegressionPanel
Builds an Asset Panel that holds a square proximity matrix, graded from a graph or a partition. PhylogenyPanel and phylogeny_features
PhylogenyPanel and phylogeny_featuresIt grades the neighbourhood of each asset in a graph into a square assets × assets block of proximities. The distance then measures how much two neighbourhoods overlap. It is the one estimator here whose last axis is the asset axis. Its source is always an estimator, so every fold and every subproblem refits the graph on its own assets.
Phylogeny feature algorithm that scores each pair of assets by a decay of their separation. Proximity
Proximityphylogeny_matrix clamps each entry to zero or one, and so loses the number of steps between two assets. A proximity keeps that number and scores each pair by its separation. The decay sets how the score falls as the separation grows, and the sep of the source sets where the score stops. These are two settings because an exponential decay never reaches zero. No decay that the library ships gives zero inside the budget, so a zero entry means only that the pair is out of reach.
Separations, the open AbstractSeparationAlgorithm family, which separation_matrix and separation_budget apply
AbstractSeparationAlgorithm family, which separation_matrix and separation_budget applyA NetworkEstimator holds it in its sep field. It says how far apart two assets are, and also how far is too far, because the two numbers have the same unit. It is a field of the network estimator and not of the panel estimator, because every user of a network needs to know which pairs it relates, and the constraints never see the panel estimator.
- 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 states its budget in the units of the distance estimator. Withdmax = nothingthe budget is the observed diameter of the graph
Budget rules, a callable in place of the budget number, which resolve_separation evaluates when the data is known
resolve_separation evaluates when the data is knownYou cannot always state a budget in advance, because a cross-validation fold and a subproblem of a meta optimiser each refit the graph. In place of a number, either budget takes a FractionOf of the reachable pairs to relate. HopCount(; n = FractionOf(0.25)) sets the hop budget at the quantile of the observed hop separations, rounded to a whole number of hops, so the share of related pairs is near the requested share and not equal to it. PathLength(; dmax = FractionOf(0.25)) does the same in the units of the distance, with no rounding, so it reaches the requested share. This is how you ask for a number of related pairs between two hop counts. A fraction changes which quantity stays fixed. A stated budget keeps the radius fixed, and a fraction keeps the number of related pairs fixed.
The n field of HopCount also takes a HopCountAlgorithm, and the dmax field of PathLength takes a PathLengthAlgorithm. Each is a callable struct, and either field also accepts a plain Function. A rule for a hop count must return an Integer. The library checks this when it evaluates the rule, because the return type of a callable is not part of its signature.
Separation decays, the open AbstractSeparationDecayAlgorithm family, which separation_decay applies
AbstractSeparationDecayAlgorithm family, which separation_decay appliesA decay takes a real separation, so one family works for a hop count and for any continuous separation. A decay f must meet three conditions. f(0) is positive and is the largest value, f never increases, and f is not negative inside the budget. The library never assumes that f reaches zero. A fallback method checks a new decay against these conditions, and the decays that the library ships skip that check.
- Separation decay that falls linearly to the edge of the budget.
LinearDecay - Separation decay that falls exponentially.
ExponentialDecay - Separation decay that falls as a power of the separation.
ReciprocalDecay
decay = nothing gives the same score to every pair inside the budget. The budget still applies, and the result is the indicator of the neighbourhood.
Collapsing a window of time-varying features
Discard the window and measure one row of each asset's features LastObservation
LastObservation- Reads every asset at the last row of the window.
LastRow - Reads each asset at its last readable row of the window, the most recent value that an investor had.
LastActiveRow
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 median, weighted or not, so that one outlying observation moves it little.
MedianCollapse
- Concatenates the window into one long feature vector per asset, so the collapse aggregates nothing.
StackObservations
A pair of assets with no shared active row
- Refuses a pair of assets with no shared active row, the default rule for an empty pair.
RefusePair - Drops the asset of an empty pair that has fewer active rows, at the entry of a fit.
DropFewerRows - Measures an empty pair by the features of the two assets, each aggregated over its own active rows.
FeatureFallback
Similarity matrices
A similarity matrix algorithm turns a distance matrix into a similarity matrix and reads nothing else. distance_to_similarity applies it. FeatureDistance picks one from its metric through default_similarity. The triangulated maximally filtered graph (TMFG) that DBHT and LoGo use takes its own.
The TMFG cannot take a negative weight. It therefore accepts only an AbstractNonNegativeSimilarityMatrixAlgorithm, and it throws an error at construction for AngularSimilarity. Two of the algorithms it accepts need a condition on the distance matrix, which assert_similarity_domain checks. ComplementSimilarity needs D <= 1, and MaximumDistanceSimilarity needs a finite D.
- Takes the linear complement $1 - D$, the exact inverse of a metric that is one minus a similarity.
ComplementSimilarity - Recovers a correlation from a normalised angular distance by $\cos(\pi D)$.
AngularSimilarity - Subtracts each squared distance from the largest squared distance, rounded up to an integer.
MaximumDistanceSimilarity - Maps a distance of any magnitude into $(0,\,1]$ by $e^{-D}$.
ExponentialSimilarity - Applies $e^{-c D^{p}}$, the exponential transformation with a scale and an exponent.
GeneralExponentialSimilarity
Phylogeny
PortfolioOptimisers.jl uses the relationships between assets in three ways. They drive the clustering optimisers, they constrain the weights, and they measure how related the assets of a portfolio are.
Clustering
Phylogeny constraints and the clustering optimisers cluster the assets through ClustersEstimator, Clusters and clusterise. Most of the clustering algorithms come from Clustering.jl.
Selects the number of clusters of a dendrogram or a flat partition, under a ceiling. OptimalNumberClusters and VectorToScalarMeasure
OptimalNumberClusters and VectorToScalarMeasure- Selects the number of clusters at which the within-cluster dispersion has its largest second-order difference.
SecondOrderDifference - Selects the number of clusters from the silhouettes of the assets.
SilhouetteScore - Predefined number of clusters.
- Select the number of clusters at which to cut a dendrogram.
optimal_number_clusters
- Get the vector of cluster indices for each point.
assignments
Hierarchical
- Builds a dendrogram that merges the two nearest clusters at each step, until one cluster 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
- Joins every root candidate of the planar hierarchy under one root.
UniqueRoot - Joins the root candidates of the planar hierarchy to each other, and adds no root clique.
EqualRoot
Non-hierarchical
The hierarchical clustering optimisers cannot use a non-hierarchical clustering algorithm. Phylogeny constraints and NestedClustered can.
- Partitions assets into
kgroups by Lloyd's algorithm, with no dendrogram.KMeansAlgorithm
Networks
Adjacency matrices
An adjacency matrix records which assets are related, from a clustering or from a graph. phylogeny_matrix computes it, and a PhylogenyResult holds it.
Network adjacency NetworkEstimator, with a choice of tree algorithm, covariance estimator and distance estimator
NetworkEstimator, with a choice of tree algorithm, covariance estimator and distance estimator- Grows the minimum spanning tree with the lightest edge that joins two components, one edge at a time.
KruskalTree,BoruvkaTree, andPrimTree
Triangulated maximally filtered graph, with a choice of similarity matrix algorithm
The graph accepts any AbstractNonNegativeSimilarityMatrixAlgorithm: MaximumDistanceSimilarity, ExponentialSimilarity, GeneralExponentialSimilarity or ComplementSimilarity. It does not accept AngularSimilarity, which returns a negative weight for every negative correlation, because a TMFG cannot take a negative weight.
The sep separation, which says which pairs count as related
sep separation, which says which pairs count as relatedHopCount relates every pair of assets within n edges of each other. PathLength relates every pair whose shortest path is no longer than dmax. A hop count can only add whole neighbourhoods at a time, and a path length reaches the numbers of related pairs between them. It does not put the pairs in a different order, because the graph already selects its edges by distance. A path length refines a hop count and does not compete with it. PathLength() with no dmax uses the observed diameter of the graph, so it relates every pair that is connected at all. That is the other extreme from HopCount(), whose default relates only direct neighbours. SemiDefinitePhylogenyEstimator and IntegerPhylogenyEstimator take either one. NetworkClustersEstimator takes only a hop count, because it sums the powers of the adjacency matrix, one power per edge.
- Clusters the assets of a universe from a return matrix.
ClustersEstimatorandClusters - Clusters assets by the pseudo-distances that a network's structure induces.
NetworkClustersEstimator - Group the assets into clusters, and keep the member of each cluster with the best score.
ClusterGroups
Centrality and phylogeny measures
Centrality estimator CentralityEstimator, with a choice of centrality measure and of adjacency matrix estimator, from a clustering or from a network
CentralityEstimator, with a choice of centrality measure and of adjacency matrix estimator, from a clustering or from a network- Betweenness
BetweennessCentrality - Closeness
ClosenessCentrality - Degree
DegreeCentrality - Eigenvector
EigenvectorCentrality - Katz
KatzCentrality - Pagerank
Pagerank - Radiality
RadialityCentrality - Stress
StressCentrality
Where it can, the centrality reads a weighted network, with the weights in the polarity that centrality_polarity returns for the algorithm
centrality_polarity returns for the algorithmDistancePolarityfor the shortest-path algorithms, which are betweenness, closeness, radiality and stressSimilarityPolarityfor eigenvector centrality, which reads the weighted adjacency matrix itselfTopologyOnlyin theovfield of any of the five algorithms that declare a polarity, which removes the weights and computes the centrality on the topology of the network alone
Five cases run on the unweighted graph, and none of them throws an error. The first is a source with no weights, which is a ClustersEstimator, a precomputed Clusters or a precomputed PhylogenyResult. The others are DegreeCentrality, Pagerank, KatzCentrality, and EigenvectorCentrality on a tree network. The polarity says which weights an algorithm gets, and it never decides whether the call succeeds. The sep of a NetworkEstimator has no effect on the weighted computations, which read the edges of the network and not the pairs that sep relates. At the default HopCount(; n = 1) the two sets of pairs are the same.
The override works in one direction. It removes the weights and never adds them, so no value forces a polarity onto an algorithm. Every source accepts it, because a partition, a precomputed PhylogenyResult and a tree network already give the answer on the topology alone. Only the five algorithms that declare a polarity have the field. DegreeCentrality(; ov = TopologyOnly()) throws a MethodError, because the other three already read the topology alone. Every centrality function takes ct as a positional argument, so an algorithm you configure works with all of them. A CentralityEstimator holds only pl and ct.
- Return a precomputed centrality vector unchanged.
centrality_vector - Compute the average centrality of a portfolio, weighted by
w.average_centrality - Compute the asset phylogeny score of the weights
won the phylogeny matrixX.asset_phylogeny
Cluster trees
Hierarchical clustering makes a tree of ClusterNodes. to_tree builds the tree, and pre_order and is_leaf walk it.
- Collects the
idof each leaf, which is the index of its asset.PreorderTreeByID
Optimisation constraints
The traditional optimisers, which build a JuMP problem, take the constraints below. The naive and clustering optimisers take weight bounds only. The entropy pooling priors take views, which are constraints on the posterior. You can state each constraint by hand, or derive its values from data with a type such as AbstractEstimatorValueAlgorithm or UniformValues.
You can state a constraint through its estimator, or directly as its result type. An estimator can name assets and groups of assets in key-value pairs. UniverseSets declares those assets and groups, and the library maps the names onto the assets with name_to_val! and replace_group_by_assets.
- Equation parsing
parse_equationandParsingResult - Return an assembled
LinearConstraint,nothing, or a vector of assembled constraints unchanged.linear_constraints,LinearConstraintEstimator,PartialLinearConstraint, andLinearConstraint
Factor exposure constraints ExposureConstraintEstimator
ExposureConstraintEstimatorIt wraps a linear constraint, an estimator of one, or a vector of those, and declares the AbstractConstraintSpace its rows are written in. You can then state a mandate in factor names, such as "at most 30% momentum", and the library maps it onto the assets through the loadings of the prior. The mapping happens when the library builds the constraints. The optimiser receives an ordinary LinearConstraint on the assets, and every optimiser built on JuMPOptimiser supports it. The factor names resolve against the factor axis that a UniverseSets declares.
- The factor basis.
FactorSpace
- Makes the uniform risk budget when the caller gives no risk budget.
risk_budget_constraints,RiskBudgetEstimator, andRiskBudget - Build a phylogeny constraint result from an estimator, or pass a result through.
phylogeny_constraints,centrality_constraints,SemiDefinitePhylogenyEstimator,SemiDefinitePhylogeny,IntegerPhylogenyEstimator,IntegerPhylogeny, andCentralityConstraint - Resolve a
WeightBoundsEstimatoragainst a universe.weight_bounds_constraints,WeightBoundsEstimator, andWeightBounds - Bounds the magnitude of each weight by a multiple of the score of its asset, on the returns of each fit.
ScoreWeightBounds - 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 derive the values from data in place of values you state.
- Fills every entry of a value vector with
1/N, whereNis the number of assets in the universe.UniformValues - Return one value per asset of the universe, from a mapping of asset names and group names to values.
estimator_to_val - Algorithm that reduces a vector of real values to its minimum.
MinValue - Algorithm that reduces a vector of real values to its maximum.
MaxValue - Algorithm that reduces a vector of real values to its mean, with or without weights.
MeanValue - Algorithm that reduces a vector of real values to its median, with or without weights.
MedianValue - Algorithm that reduces a vector of real values to its mode.
ModeValue - Algorithm that reduces a vector of real values to its sum.
SumValue - Algorithm that reduces a vector of real values to its product.
ProdValue - Algorithm that reduces a vector of real values to its standard deviation, with or without weights.
StdValue - Algorithm that reduces a vector of real values to its variance, with or without weights.
VarValue - Algorithm that reduces a vector of real values to its mean divided by its standard deviation, with or without weights.
StandardisedValue - States that no value exists for a field outside every fold loop.
NoDefault
Changes one optimiser input from fold to fold of a cross-validation scheme. TimeDependent
TimeDependentA time-dependent input takes a different value in each fold of a cross-validation scheme, and has no effect outside one.
- Abstract supertype for the callable structs that compute the value of a schedule at each fold.
TimeDependentCallable - Abstract supertype for the callable structs whose value at a fold is a constraint value.
TimeDependentConstraintCallable - Abstract supertype for the callable structs whose value at a fold is an optimiser.
TimeDependentOptimiserCallable - Describes one fold to the schedules that resolve against it.
TimeDependentContext - States that a function in a schedule reads the weights of the previous fold.
PreviousWeightsFunction
- Build a binary asset-group membership matrix from a Universe Sets key.
asset_sets_matrixandAssetSetsMatrixEstimator - Returns a resolved threshold or
nothingunchanged.threshold_constraints,ThresholdEstimator, andThreshold
Prior statistics
Many optimisations and constraints use prior statistics, which prior computes.
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 - Forecasts the next price relative and its covariance by averaging many low-dimensional lagged regressions, weighted by their in-sample fit.
LowDimensionEnsemblePrior
Estimates a point-in-time cross-sectional factor model from an Asset Panel, and lifts it onto the assets. CrossSectionalFactorPrior
CrossSectionalFactorPriorIt is the cross-sectional counterpart of FactorPrior. It reads a point-in-time AssetPanel in place of a series of factor returns, and builds one factor exposure per named factor. At each observation it regresses the returns of the assets on their lagged exposures, and it returns a CrossSectionalFactorModel in the rr field. It uses the descriptors, the factor exposures, the cross-sectional regression, its weight policy and the factor family basis from the sections above. You can read the factors it will produce before any fit. cross_sectional_factor_axis returns the name of each factor and its family, from the estimator and the AssetPanel. cross_sectional_factor_sets writes those factors, and one group per family, into a UniverseSets. A factor mandate in a pipeline step then needs no list of one-hot levels typed by hand. An observed factor in the factor list, such as a currency factor, follows the estimated factors on every axis, and cross_sectional_factor_returns reads the estimated and the observed factor returns side by side.
- Return the factor returns of a
CrossSectionalFactorModelon the axis of its loadingsL: the factors the fit estimated, then the observed factors.cross_sectional_factor_returns
Wrapped in Online, it fits again over the observations it has received at each step, so each step gives the same result as a fit over the same observations. When a factor family drops a member that the fit chooses, the choice field says which observations choose it. A BatchChoice, the default, chooses again over every observation at each step. A PinnedChoice keeps the member that the first fit chose.
- Makes the choice again over every observation at each fit.
BatchChoice - Keeps the choice of the first fit.
PinnedChoice
The asset covariance is the systematic block, the factor covariance seen through the latest exposures, plus the idiosyncratic block. The prior always repairs the sum under mp. The srep field says whether it also repairs the systematic block first. The default srep = nothing does not, because the block has the rank of the factor covariance and a repair moves it by round-off alone. SystematicRepair runs every step of mp on the block.
- Repairs the systematic block before the lift of a
CrossSectionalFactorPrioradds the idiosyncratic block.SystematicRepair
Unwrapped, the prior folds as a carry: each step reads the new observations, and folds each part that has a fold of its own. The carry field says what the carry does with a part that has none, such as a Descriptor with no finite look-back or a ve that does not fold. FoldOrRefit, the default, fits the part again over every row that it reads, so the answer stays exact and the cost of a step grows with the stream. FoldOnly refuses such a part when the prior is built, and names it.
- Folds each part of a
CrossSectionalFactorPriorthat has a fold, and fits every other part again at each step of the carry fold.FoldOrRefit - Accepts only a
CrossSectionalFactorPriorwhose every step of the carry fold has a cost that does not grow with the stream.FoldOnly
The exposures lag the returns, so the zero-sum condition of a constrained family of factors reads earlier benchmark weights, which can still weight a member after its last asset delists. The unseen field says what return such a member gets. ZeroUnseenMember, the default, gives it a return of zero and holds the condition over the other members, so the factor returns do not depend on the dropped member. SolvedUnseenMember keeps it in the condition and lets the solve algorithm of cre give its return.
- The Unseen Member rule that gives an Unseen Member a return of zero at its observation, and holds the zero-sum condition of the observation over the other members of its family.
ZeroUnseenMember - The Unseen Member rule that keeps an Unseen Member in the zero-sum condition of its observation, and lets the solve algorithm of the regression state its return.
SolvedUnseenMember
An asset that is the only member of its level of a one-hot factor at an observation has a residual of zero whatever its return, so that residual says nothing about its specific risk. The l1mask field says how the prior reads it when it scales the residuals into its scenarios. MaskedLeverageOne, the default, reads it as a gap, so the scenario takes the mean scaled residual of the other assets of that observation, and the idiosyncratic correlation leaves it out. UnmaskedLeverageOne reads the zero as it stands.
- Read the residual of a Leverage-One Pair as a gap in the standardised idiosyncratic returns.
MaskedLeverageOne - Read the residual of a Leverage-One Pair as it stands.
UnmaskedLeverageOne
lambda and c take a rule in place of the number. lambda gives the weight of the fitted factor mean against the spanned part of the return forecast, and its default is a rule. PrecisionBlend weighs the two estimates by the error of each. With no return forecast, it shrinks the factor mean towards zero. SteinShrinkage reads the shrinkage intensity of a shrunk expected-returns algorithm instead. c scales the part of the forecast that the factors do not span, and it stays one unless you state ForecastCalibrationSlope. That rule reads the history of the return forecast, which a fitted forecast makes slowly. Each variation of a rule is the type of one of its fields.
Shrinks the factor mean towards the spanned part of a Return Forecast by the precision of each. PrecisionBlend
PrecisionBlend- Measures the error of the spanned part of a Return Forecast from its latest row alone.
CurrentForecastError - Measures the error of the spanned part of a Return Forecast from the rows of its history.
ForecastHistoryError
- Shrinks the factor mean towards the spanned part of a Return Forecast by the intensity of a shrunk expected-returns estimator.
SteinShrinkage
Computes the Orthogonal Forecast Scale as the calibration slope of the orthogonal forecast on the forward idiosyncratic return. ForecastCalibrationSlope
ForecastCalibrationSlope- Takes the target below a count of history rows, and the calibration slope at or above it.
ThresholdWarmUp - Shrinks the calibration slope towards the target by the plug-in weight of its standard error.
PlugInWarmUp - Shrinks the calibration slope towards the target by the positive-part weight of its standard error.
PositivePartWarmUp
Black-Litterman
- Assemble Black-Litterman views into a
BlackLittermanViews, or return precomputed views unchanged.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 views you state and stays as close as possible to the prior. It takes views on the moments, and also on the conditional, entropic and relativistic value at risk. Each view is a constraint of the one entropy pooling problem.
- Black-Litterman views in matrix form: the views matrix
Pand the view returnsQ.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 [2].
ConicEntropicValueatRiskView - Power cone formulation of a relativistic value-at-risk view [2].
ConicRelativisticValueatRiskView - Sequential convex formulation of a tail view.
SequentialTailView - Grid formulation of an entropic or a relativistic value-at-risk view.
GridTailView
View groups
A significance level belongs to a view, not to the estimator that holds the view. Each type below pairs a group of view equations with its significance level, and a tail view also with its formulation. One estimator can therefore state views at several levels. For the same reason, a relativistic view group holds its own deformation parameter.
- A group of value at risk views, with their significance level.
ValueatRiskView - A group of conditional value at risk views, with their significance level and their formulation.
ConditionalValueatRiskView - A group of entropic value at risk views, with their significance level and their formulation.
EntropicValueatRiskView - A group of relativistic value at risk views, with their significance level, their deformation parameter and their formulation.
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
MeucciEntropyPoolingPriorIt is the earlier entropy pooling estimator. It searches for a conditional value at risk target with the recursive algorithm of Meucci, Ardia and Keel. Its views on the conditional value at risk must be equalities, one asset per view, and it solves the whole problem again for each candidate value at risk.
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 - Finds with a root finder the value at risk level that meets one 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
An uncertainty set on the expected returns or on the covariance makes an optimisation less sensitive to noise and to errors in the estimates. Any optimisation that uses one of the two quantities accepts a set on it. ucs, mu_ucs and sigma_ucs build the sets.
The first two shapes of set are a box and an ellipsoid.
- 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 a choice of algorithm for the scaling parameter, which k_ucs computes
EllipsoidalUncertaintySet and EllipsoidalUncertaintySetAlgorithm, with a choice of algorithm for the scaling parameter, which k_ucs computes- Computes the radius
kof the ellipsoid from a sample, as the1 - qquantile of the Mahalanobis distances of the sampled estimation errors.NormalKUncertaintyAlgorithm - Computes the radius
kof the ellipsoid assqrt((1 - q) / q), a closed form that holds for every distribution of the estimation errors.GeneralKUncertaintyAlgorithm - Computes the radius
kof the ellipsoid as the square root of a chi-squared quantile, a closed form for normal estimation errors.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 needs no semidefinite constraint.
- Holds a worst-case variance penalty as a radius, a diagonal metric square root and a basis of the directions that the penalty spares.
CompactCovarianceUncertaintySet
A fourth shape is the image of a norm ball under a geometry map of any rank, for the expected returns or for the covariance. A set that is flat in the directions a factor model does not span then needs no full-rank shape matrix. An ellipsoid you already built converts to it with one Cholesky factorisation.
NormBallUncertaintySetandNormBallUncertaintySetAlgorithm, which take the same scaling algorithms as the ellipsoid and apply them to the geometry map throughk_norm_ball
Several estimators build the sets. The next two build a box, an ellipsoid or a norm ball.
Fits a box, an ellipsoidal or a norm-ball uncertainty set from the sampling laws of normal returns. NormalUncertaintySet
NormalUncertaintySetConstructions of the diagonal covariance shape, read when the ellipsoid or the norm ball keeps only the diagonal
- Takes the diagonal of the full covariance shape.
DiagonalOfShape - Sets the covariances of $\hat{\mathbf{\Sigma}}$ to zero, then builds the covariance shape.
ShapeOfDiagonal
Block bootstrap of the returns with the arch package, ARCHUncertaintySet
arch package, ARCHUncertaintySet- Circular
CircularBootstrap - Moving
MovingBootstrap - Stationary
StationaryBootstrap
The next estimator builds a box only.
- Fits a box uncertainty set whose half-width is a fixed fraction of the absolute value of each prior moment.
DeltaUncertaintySet
The library states a quintile portfolio as an uncertainty set on the characteristic vector, not as an optimiser of its own.
Fits an $\ell_1$ uncertainty set with a calibrated radius on the characteristic vector, for the mean only. CharacteristicUncertaintySet
CharacteristicUncertaintySet\[\ell_1\]
uncertainty set on the characteristic vector, a cross-polytope around the estimate.L1UncertaintySetandL1UncertaintySetAlgorithm- Signed $\ell_1$ uncertainty set on the characteristic vector, with a separate error budget per sign.
SignedL1UncertaintySetandSignedL1UncertaintySetAlgorithm - Calibrates the radius of an $\ell_1$ uncertainty set to a target number of active assets.
ActiveAssetsUncertaintyAlgorithm
One estimator reads no returns at all. It receives the fitted prior of its optimisation, and it limits both of its sets to the directions that the factor model of the prior 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 weights under which the span of the factors is computed
- Names the inverse of the idiosyncratic variances as the cross-sectional weight source.
InverseIdiosyncraticVarianceMetric - Names the regression weights as the cross-sectional weight source.
RegressionWeightMetric - Names the benchmark weights as the cross-sectional weight source.
BenchmarkWeightMetric
Scalings of the set on the expected returns, in the directions the factors do not span
- Sizes each direction of the Orthogonal Subspace by the idiosyncratic covariance projected onto it.
IdiosyncraticVarianceScaling
Rules that compute the radius of the covariance set from the sample and the factors, in place of a number you state
- Sizes the compact radius from a chi-squared upper confidence bound on each idiosyncratic variance.
ResidualInflation - Sizes the compact radius so that the penalty at a reference portfolio equals a stated fraction of its nominal variance.
VarianceFraction
Axis tags of the ellipsoid and the norm ball
- Marks an uncertainty set as a set on the mean axis, where the shape matrix is $N \times N$ and the geometry map has $N$ rows.
MuUncertaintySetClass - Marks an uncertainty set as a set 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 the absolute difference, asset by asset, between the current weights and a vector of benchmark weights. You can use it as a constraint, as the base of a fee, or as a risk measure. turnover_constraints, TurnoverEstimator and Turnover implement it.
Fees
Every optimisation except BudgetedHindsightPath can include fees, the naive ones too. A finite allocation takes them in its input, FiniteAllocationInput. calc_fees and calc_asset_fees compute the fees of a portfolio and of each asset, which you can subtract from the expected returns. The proportional and turnover rates apply in every period, and the two fixed amounts apply one time for the whole holding period. calc_total_fees and calc_total_asset_fees therefore give the cost over a horizon you state.
- Resolve the name-keyed fee fields of a
FeesEstimatoragainst a universe into aFeesof plain per-asset vectors.fees_constraints - Compute the fixed portfolio fees for the assets the portfolio holds.
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 fixed charges
fl,fsandflq, evenly over a holding period.AmortisedFees - Charges the one-off terms of a fee, the fixed charges
fl,fsandflq, on the first observation of a return series.FirstObservationFees
Portfolio returns and drawdowns
Many risk measures and analyses need the returns, the cumulative returns and the drawdowns of a portfolio, in total and per asset. calc_net_returns, calc_net_asset_returns, cumulative_returns and drawdowns compute them. calc_turnover computes the trading that a path of weights needs, which is the value of the quantity that Turnover bounds.
You can also score a window on the weights a fund holds, which move with the returns of their assets while no trade happens. The series is then the wealth ratio of those drifted holdings.
The realised series of a fold can also charge the two fixed fees on a schedule of its own. The scheme states that schedule in its fa field. It replaces the schedule of the fee itself, and it has no effect on the fit.
- 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
A tracking constraint keeps a portfolio close to a benchmark, which can be an index, an indicator or another portfolio.
Compute the net return series of the benchmark weights of a WeightsTracking. tracking_benchmark and TrackingError
WeightsTracking. tracking_benchmark and TrackingError- Holds the return series of a benchmark whose weights are unknown.
ReturnsTracking - Tracks the benchmark that the returns data carries, so the benchmark follows the rows that each reader holds.
DataBenchmarkTracking - Builds the benchmark return series from a vector of benchmark weights, net of the fees of those weights.
WeightsTracking
norm_error computes the error with one of the norms below.
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 error estimator, which is the maximum absolute deviation.
LInfNorm
The distance can also be a difference of risk, measured against a WeightsTracking benchmark, in place of a norm of the difference of returns. Two methods compute it.
Bounds how far the risk of a portfolio can move from the risk of a benchmark portfolio. 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
The sections below group the risk measures by the optimisations that accept them.
The fields of a risk measure that come from the prior, mu, sigma, kt and sk, take either the value or the estimator that computes it, a DeferredQuantity. The optimisation evaluates the estimator on its own prior, so the value is refitted in each cross-validation fold and in each subset of a meta optimiser. A matrix you pass in stays the same. A measure with two or more such fields can instead name one prior estimator in pe, and one fit then fills every field you leave empty.
Calibration
A tail probability and a deformation parameter also take a rule in place of the number. The field fixes the quantity and the end of the distribution, so you write only the rule. The optimisation evaluates the rule on its own prior, as it does a deferred estimator. The type of each field accepts the one family of rules that computes its quantity. It takes a callable estimator of that family, a plain function of (key, pr, w, slv, ctx), or the number. Four rules ship. One computes a significance level, and three compute a deformation parameter. A CountOf in a significance field keeps a stated count of scenarios in the tail at every sample length, and a FractionOf there is the level itself. Forty fields over twenty-seven risk measures and weight builders take a rule, and they are 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 and not quantities to estimate. They keep their numbers, and each fold checks the bound 0 < alpha_i < alpha < 1 against the calibrated alpha.
A significance rule reads the length of the sample. Where the count it states is a count of observations, it reads the effective weights of the observations. A deformation rule reads the probability of its own end of the distribution, which it gets in the CalibrationContext that the owner of the field builds. One deformation rule spends a stated entropy budget on the length of the sample. The other two estimate the tail index of the sample and return its reciprocal. One of them standardises each column and returns a value per end, so a skewed sample gives two numbers. The other whitens each observation with the covariance matrix and returns one number for both ends.
A rule that reads the shape of a series needs to know which series. A drawdown measure is computed on the drawdown series of the portfolio, not on its returns, and the key of the field does not say which. The measure therefore states its series in the CalibrationContext, beside the significance level. The two tail rules then read the drawdown series of each column in place of the column itself. The pooled rule pools those series. The radial rule whitens their rows with the covariance matrix of the same drawdown series, because a prior result holds no moment of the drawdowns. If you run a rule by hand, build the context with a series, such as AbsoluteDrawdownSeries(), as the measure would.
- Computes a significance level that decreases 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 of the tail of the sample.
HillTailDecay - Computes the Kaniadakis deformation parameter whose tail decays at the rate of the radial series of the sample.
RadialTailDecay - Names the returns, the columns of
pr.Xwith no change.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 also takes a rule. A radius applies to no end of the distribution, so one type bound serves every radius field. The fields are the four regularisation coefficients of JuMPOptimiser and the radii of the distributionally robust risk measures. Four rules ship, and all four compute a radius. Two shrink the ball at the rate of the square root of the sample length. The third shrinks it at a rate that the number of assets sets, which is much slower over a wide universe.
- Computes an ambiguity radius from a chi-squared quantile, so that the ball becomes smaller as the sample becomes longer.
ConcentrationRadius - Computes an ambiguity radius that decreases with the square root of the sample length.
RateRadius - Computes an ambiguity radius that decreases at the dimensional rate of a Wasserstein ball, and not at the square-root rate.
DimensionalRateRadius
Those three return the same number for every field, but the eight radius fields do not all measure distance in one norm. The fourth rule reads the key of the field, picks the ground metric that the field names, and returns the sampling error of the empirical measure in that metric. As a result, the l1 and linf coefficients of one optimiser get two different values.
- Computes an ambiguity radius in the ground metric that its slot names, so that two slots of two different norms get two different numbers.
DualNormRadius
The tail weight of an Esfahani-Kuhn loss has a family of its own. One rule ships for it, and it sets the tail term of the loss to a stated multiple of its mean term. A tail weight you state has no unit, but its effect depends on the scale of the sample, so one number gives a different trade-off at each sampling frequency. The rule reads the probability of its own field, which it gets 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 and has a family of its own. Neither family is accepted in the field of the other. A radius is the coefficient of a norm penalty in the objective. A ceiling bounds that norm in a constraint. The bound sets a floor on the effective number of assets. The three norm-constraint fields of JuMPOptimiser, l2c, lpc and linfc, take one. The field takes a FractionOf of the assets or a CountOf effective assets as the floor, and no rule ships. A fraction keeps a stated share of the assets effective, so the floor changes with the assets of the prior. The order of the norm belongs to the constraint and not to the floor, so each constraint states its own order before the field is evaluated.
Risk measures for traditional optimisation
Each is a subtype of RiskMeasure. Every JuMP optimisation estimator that takes a risk measure accepts it, and so do hierarchical risk parity and hierarchical equal risk contribution.
Measures the portfolio variance, the quadratic form of the weights in a covariance matrix. Variance
VarianceTraditional optimisations also support:
- Risk contribution
Formulations
- Encodes the second moment as an explicit quadratic form in the risk expression.
QuadRiskExpr - Encodes the second moment as the square of a second-order cone variable.
SquaredSOCRiskExpr
Ratio term of a lifted variance
- Makes
MaximumRatiodivide the excess return by the square root of a lifted variance.SquareRootRatio - Makes
MaximumRatiodivide the excess return by a lifted variance itself, not by its square root.LinearRatio
- Measures the portfolio standard deviation, the square root of the variance.
StandardDeviation - Uncertainty set variance
UncertaintySetVariance, which is the variance outside traditional optimisation
Measures a low-order moment of the deviations of the net portfolio returns from the Moment Target. LowOrderMoment
LowOrderMoment- Measures the mean shortfall of the net portfolio returns below the Moment Target.
FirstLowerMoment - Measures the mean absolute deviation of the net portfolio returns from the Moment Target.
MeanAbsoluteDeviation - Measures the $p$-th root of the even moment of order $2p$ of the net portfolio returns about the Moment Target.
EvenMoment
Measures the second moment of the net portfolio returns about the Moment Target, or its square root. 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 measures only the downside.
SemiMoment
Traditional optimisation formulations
- Encodes the second moment as an explicit quadratic form in the risk expression.
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 measures only the downside.
SemiMoment
Measures the fourth central moment of the portfolio returns, or its square root, from the cokurtosis matrix kt. Kurtosis
kt. Kurtosis- Actual kurtosis
Traditional optimisers take the full or the semi kurtosis through the kt field, and the alg1 field sets which of these moments the risk computation from returns uses
kt field, and the alg1 field sets which of these moments the risk computation from returns 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 measures only the downside.
SemiMoment
Traditional optimisation formulations
- Encodes the second moment as an explicit quadratic form in the risk expression.
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 measures only the downside.
SemiMoment
Measures the negative quadratic skewness of a portfolio, a convex part of its third moment. NegativeSkewness
NegativeSkewnessSquared negative skewness
Traditional optimisers take the full or the semi skewness through the sk and V fields, and the moment algorithm of the coskewness estimator that fills them sets which one
sk and V fields, and the moment algorithm of the coskewness estimator that fills them sets which one- Keeps every deviation from the target, so the moment is two-sided.
FullMoment - Clips every deviation above the target to zero, so the moment measures only the downside.
SemiMoment
Traditional optimisation formulations
- Encodes the second moment as an explicit quadratic form in the risk expression.
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
- Measures a weighted sum of the variance, the third central moment and the fourth central moment of the portfolio returns.
VarianceSkewKurtosis
Measures the Value-at-Risk (VaR), the loss that the portfolio exceeds with probability alpha. ValueatRisk
alpha. ValueatRiskTraditional optimisation formulations
- Computes the Value-at-Risk as the empirical quantile of the sample, through a mixed-integer programme.
MIPValueatRisk - Computes the Value-at-Risk as a quantile of a parametric distribution, from the mean and the covariance of the asset returns.
DistributionValueatRisk
Measures the Value-at-Risk Range, the spread between the loss quantile at alpha and the gain quantile at beta. ValueatRiskRange
alpha and the gain quantile at beta. ValueatRiskRangeTraditional optimisation formulations
- Computes the Value-at-Risk as the empirical quantile of the sample, through a mixed-integer programme.
MIPValueatRisk - Computes the Value-at-Risk as a quantile of a parametric distribution, from the mean and the covariance of the asset returns.
DistributionValueatRisk
- Measures the Drawdown-at-Risk (DaR), the uncompounded drawdown that the portfolio exceeds with probability
alpha.DrawdownatRisk - Measures the Conditional Value-at-Risk (CVaR), the average loss over the worst
alphafraction of the portfolio returns.ConditionalValueatRisk - Distributionally Robust Conditional Value at Risk
DistributionallyRobustConditionalValueatRisk, which is the conditional value at risk outside traditional optimisation - Measures the spread between the two tails of the portfolio returns, the CVaR of the losses plus the CVaR of the gains.
ConditionalValueatRiskRange - Distributionally Robust Conditional Value at Risk Range
DistributionallyRobustConditionalValueatRiskRange, which is the conditional value at risk range outside traditional optimisation - Measures the Conditional Drawdown-at-Risk (CDaR), the average of the worst
alphafraction of the uncompounded drawdowns.ConditionalDrawdownatRisk - Distributionally Robust Conditional Drawdown at Risk
DistributionallyRobustConditionalDrawdownatRisk, which is the conditional drawdown at risk outside traditional optimisation - Measures the Entropic Value-at-Risk (EVaR), the tightest upper bound on the Value-at-Risk that the Chernoff inequality gives.
EntropicValueatRisk - Measures the spread of the returns as the sum of the Entropic Value-at-Risk of the losses and that of the gains.
EntropicValueatRiskRange - Measures the Entropic Drawdown-at-Risk (EDaR), the Entropic Value-at-Risk of the absolute drawdown series of the portfolio.
EntropicDrawdownatRisk - Measures the Relativistic Value-at-Risk (RLVaR), the worst expected loss over a Kaniadakis entropy ball about the sample distribution.
RelativisticValueatRisk - Measures the spread of the returns as the sum of the Relativistic Value-at-Risk of the losses and that of the gains.
RelativisticValueatRiskRange - Measures the Relativistic Drawdown-at-Risk (RLDaR), the Relativistic Value-at-Risk of the absolute drawdown series of the portfolio.
RelativisticDrawdownatRisk
Ordered Weights Array
Risk measures
- Measures risk as a weighted sum of the sorted portfolio returns, the ordered weights array (OWA) risk.
OrderedWeightsArray - Measures risk as the sum of a loss tail and a gain tail of the sorted portfolio returns, each an OWA risk.
OrderedWeightsArrayRange
Traditional optimisation formulations
- Encodes the exact OWA risk with the linear programme that sorts the sample.
ExactOrderedWeightsArray
OWA formulation that computes the exact OWA risk through a relaxed sorting network of $O(T \log^{2} T)$ linear rows. SortingNetworkOrderedWeightsArray
SortingNetworkOrderedWeightsArraySorting networks
- Sorts with Batcher's odd-even merge network, which has the fewest comparators of the two merge networks.
OddEvenMerge - Sorts with Batcher's bitonic merge network, which QDLDL, the default linear solver of Clarabel, factorises with less work under its AMD order.
BitonicMerge
Orders of the network variables
- Puts the network variables in the order of the comparators that write them.
ComparatorOrdering - Puts the network variables in the order of the positions they hold, one position after the other.
WireOrdering
- Encodes an upper bound on the OWA risk with one power cone block for each p-norm order in
p.ApproxOrderedWeightsArray - Solves a programme for the risk aversion coefficients of an L-moment OWA weight vector.
OWAJuMP
Callable weights, which the w field of an ordered weights array measure takes in place of a vector
w field of an ordered weights array measure takes in place of a vector- Builds the OWA weight vector of the conditional value at risk at level
alpha.OrderedWeightsArrayConditionalValueatRisk - Builds the OWA weight vector of the tail Gini at level
alpha.OrderedWeightsArrayTailGini - Builds the OWA weight vector of the L-moment convex risk measure of the orders
2tok.LinearMoment
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 OWA weight vector of the sample L-moment of order
k.owa_l_moment
Combine the columns of a signed L-moment weight matrix into one OWA weight vector, with the risk aversion coefficients that method finds. owa_l_moment_crm
method finds. owa_l_moment_crmL-moment combination formulations
Selects the risk aversion coefficients of maximum entropy in the L-moment programme of OWAJuMP. MaximumEntropy
OWAJuMP. MaximumEntropy- Encodes the entropy objective of
MaximumEntropywith one exponential cone for each risk aversion coefficient.ExponentialConeEntropy - Encodes the entropy objective of
MaximumEntropywith one relative entropy cone.RelativeEntropy
- Selects the smoothest OWA weights in the L-moment programme of
OWAJuMP.MinimumSquaredDistance - Selects the OWA weights of least sum of squares in the L-moment programme of
OWAJuMP.MinimumSumSquares
- Measures the Average Drawdown, the mean depth of the uncompounded drawdown over the sample.
AverageDrawdown - Measures the Ulcer Index, the root mean square of the uncompounded drawdown over the sample.
UlcerIndex - Measures the Maximum Drawdown, the deepest fall of the uncompounded cumulative return below its running peak.
MaximumDrawdown
Represents the Brownian Distance Variance (BDVar) risk measure. BrownianDistanceVariance
BrownianDistanceVarianceTraditional optimisation formulations
Distance matrix constraint formulations
- Bounds each distance of a
BrownianDistanceVariancemodel with a norm-one cone of dimension two.NormOneConeBrownianDistanceVariance - Bounds each distance of a
BrownianDistanceVariancemodel with two linear inequalities.IneqBrownianDistanceVariance
Risk formulation
- Encodes the second moment as an explicit quadratic form in the risk expression.
QuadRiskExpr - Encodes the second moment as a variable that a rotated second-order cone bounds.
RSOCRiskExpr
- Measures the Worst Realisation, the largest loss of the sample, which is the negated minimum return.
WorstRealisation - Measures the Range, the largest return of the sample minus the smallest one.
Range - Measures the turnover of a portfolio, the $L^1$ distance of its weights from a vector of reference weights.
TurnoverRiskMeasure
Measures the tracking error, a scaled norm of the gap between the net portfolio returns and a benchmark return series. 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 error estimator, which is the maximum absolute deviation.
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
- Measures the Power Norm Value-at-Risk (PNVaR), a threshold plus the power norm of the losses above it, divided by the significance level.
PowerNormValueatRisk - Measures the spread of the returns as the sum of the Power Norm Value-at-Risk of the losses and that of the gains.
PowerNormValueatRiskRange - Measures the Power Norm Drawdown-at-Risk (PNDaR), the Power Norm Value-at-Risk of the absolute drawdown series of the portfolio.
PowerNormDrawdownatRisk - Measures the spread of the returns as the sum of a tail measure of the losses and a tail measure of the gains, two measures that the caller states.
GenericValueatRiskRange - Measures how far the risk of a portfolio is from the risk of a benchmark portfolio, under any risk measure.
RiskTrackingRiskMeasure - Measures no risk: its value is zero for every portfolio.
NoRisk
Risk measure settings
Every risk measure except RiskRatio holds a settings object in its settings field. A RiskMeasureSettings says whether the measure enters the objective, which upper bound constrains it, and its scale. A HierarchicalRiskMeasureSettings states only the scale. A MaxRiskMeasureSettings, which Skewness holds, states a lower bound in place of the upper one.
- 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
Each is a subtype of HierarchicalRiskMeasure, and only the hierarchical optimisation estimators accept it.
Measures a moment of order three or four of the deviations of the net portfolio returns from the Moment Target, or that moment divided by a power of the second moment. HighOrderMoment
HighOrderMoment- Measures the negated third moment of the deviations below the Moment Target.
ThirdLowerMoment
Measures the fourth moment of the net portfolio returns about the Moment Target. 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 measures only the downside.
SemiMoment
- Standardised moment: a variance estimator in
vedivides the moment by a power of the second moment of the same deviations.
- Measures the Relative Drawdown-at-Risk, the compounded drawdown that the portfolio exceeds with probability
alpha.RelativeDrawdownatRisk - Measures the Relative Conditional Drawdown-at-Risk, the average of the worst
alphafraction of the compounded drawdowns.RelativeConditionalDrawdownatRisk - Measures the Relative Entropic Drawdown-at-Risk, the Entropic Value-at-Risk of the compounded drawdown series, for hierarchical optimisation.
RelativeEntropicDrawdownatRisk - Measures the Relative Relativistic Drawdown-at-Risk, the Relativistic Value-at-Risk of the compounded drawdown series, for hierarchical optimisation.
RelativeRelativisticDrawdownatRisk - Measures the Relative Average Drawdown, the mean depth of the compounded drawdown over the sample.
RelativeAverageDrawdown - Measures the Relative Ulcer Index, the root mean square of the compounded drawdown over the sample.
RelativeUlcerIndex - Measures the Relative Maximum Drawdown, the deepest fall of the compounded wealth below its running peak, as a fraction of that peak.
RelativeMaximumDrawdown - Measures the Relative Power Norm Drawdown-at-Risk, the Power Norm Value-at-Risk of the compounded drawdown series, for hierarchical optimisation.
RelativePowerNormDrawdownatRisk - Measures the risk of
r1divided by the risk ofr2, for a hierarchical optimiser.RiskRatio - Measures the same risk for every portfolio, so that a hierarchical optimiser splits every cluster evenly.
EqualRisk - Measures the dispersion of the portfolio returns as the median of their absolute deviations from a centre.
MedianAbsoluteDeviation
Non-optimisation risk measures
These risk measures can return a negative value, so no optimisation accepts them on their own. You can use them as performance metrics. Skewness enters an optimisation only as the skewness term of VarianceSkewKurtosis.
- Measures the mean of the portfolio returns, or the mean of their logarithmic returns.
MeanReturn - Measures the third central moment of the portfolio returns, or the standardised skewness when
veis a variance estimator.ThirdCentralMoment - Measures the third central moment of the portfolio returns from the coskewness matrix
sk.Skewness - Risk measure whose value is the expected portfolio return of a prior result.
ExpectedReturn - Risk measure whose value is the ratio of the expected return of a portfolio to its expected risk.
ExpectedReturnRiskRatio - Measures the mean portfolio return in excess of a risk-free rate, per unit of risk.
MeanReturnRiskRatio - Measures the risk of
r1divided by the risk ofr2, for analysis and for scoring.NonOptimisationRiskRatio
Performance metrics
Every function here that takes a risk measure also takes a vector of them. The sca keyword takes a Scalariser, which combines the vector into one number. All four scalarisers work here, MinScalariser included, because these functions combine numbers and build no model expression. A function that also reads a return takes one return term or a vector of them, and sums them at the weights of the terms. No scalariser applies to the returns. A result holds the risk measure and the scalariser of its optimisation, so expected_risk(res.r, res.w, res.pr; sca = res.sca) gives the optimised value and you name neither one.
- Compute the expected value of a risk measure.
expected_risk - Compute the effective number of assets of a portfolio, the participation ratio of its absolute weights.
number_effective_assets
Risk contribution
- Compute the contribution of each asset to the risk of a portfolio with a finite difference.
risk_contribution - Compute the gradient of a risk measure with respect to the weights, with one entry for each asset.
risk_gradient - Compute the contribution of each risk factor, and of the directions that no factor spans, to the risk of a portfolio.
factor_risk_contribution
Factor attribution
factor_attribution splits the volatility and the mean return of a portfolio into four components, the systematic part, the idiosyncratic part, the part that the model does not explain, and the total, and returns one FactorAttributionResult. The result also breaks the portfolio down by factor, by factor family when the model names families, and by asset when you pass assets = true. The predicted methods read the moments that the optimiser used. The realised methods read a series of net returns, and each has a rolling version. The keyword unknown says what the numbers do with a holding the prior could not estimate: EntrywiseUnknown, the default, gives NaN for every number that reads an entry the prior does not state, and ZeroUnknown reads each such entry as zero. A pair of leverage one has an exact total and a split that the data do not identify, so the default gives NaN for the variance split of a held pair, and KindwiseUnknown sets one rule for each kind of unknown entry.
- 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 - Keeps every entry the factor model states, and gives
NaNfor every number that reads an entry it does not state.EntrywiseUnknown - Reads every entry the factor model does not state as zero, and an absent return as a zero return.
ZeroUnknown - Applies one rule to each kind of unknown entry.
KindwiseUnknown
Compute the expected return of a portfolio with a 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 risk of a portfolio over each rolling window of the returns matrix, at constant weights.
rolling_window_measure - Sort the successful paths in a
PopulationPredictionResultfrom the best to the worst underr.sort_by_measure - Compute the ratio of the expected return of a portfolio to its expected risk.
expected_ratioandexpected_risk_ret_ratio - Compute the Sharpe ratio information criterion (SRIC) of a portfolio.
expected_sricandexpected_risk_ret_sric - Compute the Brinson performance attribution of each asset class [3].
brinson_attribution - Summarise one or more realised return series as a
PerformanceSummaryResult.performance_summaryandPerformanceSummaryResult
Portfolio report
portfolio_report builds a Report that compares prediction results: an overview with the table of their performance summary, and one entry for each prediction with its statistics, its weights, its allocation and its figures. A prediction can be one fold, a walk-forward path or a population of paths. write_report writes the report as Markdown or as one HTML file that holds its style, its script and its figures, and loads nothing from the network. With the plotting extension loaded, default_report_figures gives the default figures. A report is made of blocks, and you can build one by hand.
- Build a Portfolio Report that compares prediction results: one entry for each prediction, and an overview table of their statistics.
portfolio_reportandReport - Write a Portfolio Report to a file, as Markdown or as one self-contained HTML file.
write_report - The weights of member
jof a prediction, on asset names, with one row for each portfolio that the prediction holds.prediction_weights - The default figures of a Portfolio Report, as the keywords
overview_figuresandentry_figuresofportfolio_reporttake them.default_report_figures - One portfolio of a Portfolio Report, a candidate of the comparison.
ReportEntry - A titled list of blocks of a Portfolio Report.
ReportSection - A block of plain text in a Portfolio Report.
ReportText - A table of a Portfolio Report, from a
DataFrame.ReportTable - A figure of a Portfolio Report.
ReportFigure
Sharpe ratio inference
These functions ask whether a Sharpe ratio shows skill or luck. probabilistic_sharpe_ratio gives the probability that the true Sharpe ratio of a return series exceeds a benchmark, from the length of the series and the skewness and kurtosis of its returns. minimum_track_record_length gives the number of observations that the series needs for that probability to reach a confidence level. When you select the best of several trials, deflated_sharpe_ratio measures it against the expected_max_sharpe_ratio of the search, and implied_independent_trials counts correlated trials as fewer independent ones. Every quantity is per period, so give the returns, the risk-free rate and the benchmark in one frequency.
- Compute the Probabilistic Sharpe Ratio, the probability that the true Sharpe ratio of a return series is greater than a benchmark.
probabilistic_sharpe_ratio - Compute the Minimum Track Record Length, the number of observations that a return series needs for its Sharpe ratio to exceed a benchmark at a confidence level.
minimum_track_record_length - Compute the Deflated Sharpe Ratio, the probability that the true Sharpe ratio of the best of several trials is greater than zero.
deflated_sharpe_ratio - Approximate the expected maximum of the Sharpe ratios of
Nindependent trials.expected_max_sharpe_ratio - Estimate the number of independent trials among
Mtrials whose returns have the mean correlationrho.implied_independent_trials
Portfolio optimisation
optimise runs an optimisation. It takes an optimisation estimator and returns 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 of the Coverage Universe of the window.
EqualWeighted - Draws portfolio weights at random from a Dirichlet distribution with concentration
alpha.RandomWeighted - Holds the weights it was handed, and solves nothing.
PreviousWeights - The best constant rebalanced portfolio in hindsight, from Cover's fixed point with no solver,
BestConstantRebalancedPortfolio. For the exact portfolio, or for one with bounds, useMeanRiskwithLogarithmicReturnandMaximumReturn
Naive optimisation features
- Resolves weight bounds written in asset or group names against a universe.
WeightBoundsEstimator,UniformValues, andWeightBounds
Weight finalisers
- Moves the weights into their bounds by a repeated clip and a proportional redistribution of the clipped mass.
IterativeWeightFinaliser - Moves weights into their bounds by the exact Euclidean projection, which needs no solver.
EuclideanWeightFinaliser - Moves long-only weights into their bounds by the exact entropic projection, which needs no solver and keeps the ratios of the free weights.
EntropicWeightFinaliser
Moves the weights into their bounds with the solution of a JuMP programme. JuMPWeightFinaliser
JuMPWeightFinaliser- Selects the norm of a weight deviation as the objective of a JuMP weight finaliser.
ErrorWeightFinaliser - Selects the deviation relative to the target weights, $\boldsymbol{x} \oslash (c\, \tilde{\boldsymbol{w}}_{0}) - \boldsymbol{1}$.
RelativeWeightDeviation - Selects the deviation from the target weights, $\boldsymbol{x} - c\, \boldsymbol{w}_{0}$.
AbsoluteWeightDeviation
Online portfolio selection
Online portfolio selection updates the weights after each new price relative, which is the price of each asset divided by its price one period before. Most of its rules need no solver. You choose a rule and hold it in OnlinePortfolioSelection. A batch fit runs the rule over every row of the window in order, from the start weights, and returns the weights for the next period. An online fit returns the weights the rule reached after its last update.
- Updates its allocation from each realised price relative through the Online Selection Rule on
alg.OnlinePortfolioSelection
Benchmark rules
- Lets the allocation drift with the market and never trades it, the buy-and-hold benchmark (BAH).
BuyAndHold - Rebalances to the same allocation
wafter every price move, the constant rebalanced portfolio (CRP).ConstantRebalancedPortfolio
Follow-the-winner rules
Takes one mirror-descent step on the period's gradient, then projects the result back onto the Allocation Set. MirrorDescent
MirrorDescent- Builds the exponentiated gradient, a
MirrorDescentrule underEntropicProjection(EG).ExponentiatedGradient - Builds the gradient projection, a
MirrorDescentrule underEuclideanProjection(GP, OGD).GradientProjection - Builds the exponentiated gradient with the momentum of an exponential moving average,
ExponentiatedGradientunderGradientMomentum(EGE).EGE - Builds the exponentiated gradient with a root-mean-square scale on the gradient,
ExponentiatedGradientunderRootMeanSquareGradient(EGR).EGR - Builds the exponentiated gradient with an adaptive-moment scale on the gradient,
ExponentiatedGradientunderAdaptiveMomentGradient(EGA).EGA - Builds the moving-window adaptive exponential gradient,
ExponentiatedGradientunder aWindowedBestRateoverwindowperiods (MAEG).MAEG - Builds the adaptive exponential gradient,
ExponentiatedGradientunder aWindowedBestRateover the whole history (AEG).AEG - Takes the negative log of the period's wealth as the loss of a first-order Online Selection Rule.
LogWealth - Takes a risk measure over the last
windowrows the head holds as the loss of a first-order Online Selection Rule.RiskLoss - Takes the last gradient as the hint of the optimistic step.
LastGradient - Takes the running mean of the past gradients as the hint of the optimistic step.
MeanGradient - Forms the hint of the optimistic step from a Price Relative Forecast.
ForecastGradient
- Steps to the Newton point of the log wealth of the past periods, the online Newton step (ONS).
NewtonStep - Steps each asset at its own rate, set by the gradient mass that the asset has accrued (AdaGrad).
AdaptiveSubgradient - Moves the allocation a share
etaof the way to the wealth held at the end of the period.ExpectationMaximisation - Builds the universal portfolio as an expert mixture over
n_expertsconstant rebalanced portfolios sampled from a Dirichlet prior on the simplex (UP).UniversalPortfolio - Builds the mixture of exponentiated-gradient experts under the weak aggregating algorithm, with a uniform prior.
AggregatingExponentialGradient
Learning-rate schedules
- Shrinks the learning rate with the square root of the period count, and needs no horizon.
InverseSquareRootRate - Runs the rule in stages of growing length, and restarts it at the Start Allocation after the last period of each stage.
DoublingTrickRate - Reads the learning rate from the running excess of each period's best asset over the played allocation.
SelfConfidentRate - Sets the learning rate of an optimistic step from the hint residuals that the step has accrued.
HintResidualRate - Chooses the learning rate of each period from a set of rates, by the recent wealth of one exponentiated-gradient run per rate.
WindowedBestRate
Gradient transforms, where nothing applies none
nothing applies none- Replaces the gradient with its exponential moving average, which gives the step a momentum.
GradientMomentum - Divides the gradient by the root of a moving average of its square, per asset.
RootMeanSquareGradient - Divides the moving average of the gradient by the root of the moving average of its square, per asset.
AdaptiveMomentGradient
Debias of their averages, where nothing divides none
nothing divides none- Divides the state of an exponentially weighted mean that starts at zero by the sum of its weights, so the mean is a weighted mean of the valid inputs whose weights sum to one.
ZeroStartDebias
Follow-the-loser rules
Moves the allocation the least distance that brings the last period's gross return down to eps, the passive aggressive mean reversion (PAMR). PassiveAggressiveMeanReversion
eps, the passive aggressive mean reversion (PAMR). PassiveAggressiveMeanReversion- Caps the step of PAMR, the step of
slack = nothing, at the aggressivenessC, the step-length rule of PAMR-1.LinearSlack - Softens the step of PAMR, the step of
slack = nothing, by adding1 / (2C)to its denominator, the step-length rule of PAMR-2.QuadraticSlack
Moves the allocation by the least amount that gives a forecast return of at least eps, then projects. ForecastReversion
eps, then projects. ForecastReversion- Builds the on-line moving average reversion, OLMAR.
MovingAverageReversion - Builds the second form of the on-line moving average reversion, OLMAR-2.
ExponentialMovingAverageReversion - Builds the robust median reversion, RMR.
RobustMedianReversion - Builds the reweighted price relative tracking, RPRT.
ReweightedPriceRelativeTracking - Builds the Gaussian weighting reversion, GWR.
GaussianWeightingReversion - Builds the local adaptive learning, LOAD.
LocalAdaptiveLearning
Moves the allocation a fixed distance eps along the centred Price Relative Forecast, then projects. ForecastTracking
eps along the centred Price Relative Forecast, then projects. ForecastTracking- Builds the peak price tracking, PPT.
PeakPriceTracking - Builds the adaptive input and composite trend representation, AICTR.
AdaptiveInputCompositeTrend - Builds the trend promote price tracing, TPPT.
TrendPromotePriceTracking
Moves the allocation along the kernel-scaled centred Price Relative Forecast at a fixed rate eta, then projects. KernelTrendTracking
eta, then projects. KernelTrendTracking- Builds the kernel-based trend pattern tracking, KTPT.
KernelTrendPatternTracking
- Takes one soft-thresholded, linearised step of the log forecast return from the Price-Adjusted Allocation (TCO).
TransactionCostOptimisation
Solves a linear programme on the log of the forecast with an $L_1$ penalty, then projects the scaled solution (SSPO). ShortTermSparsePortfolio
ShortTermSparsePortfolio- Puts the whole budget on the asset with the largest Price Relative Forecast, and splits it in equal parts between tied assets.
L1Optimum - Finds the fixed point of the alternating direction iteration of the short-term sparse portfolio in closed form.
HuberOptimum - Runs the alternating direction iteration of the short-term sparse portfolio until its stopping rule holds.
AlternatingDirectionMethod
Moves a Gaussian belief over the weights by the least relative entropy that puts the last return below eps with confidence. ConfidenceWeightedMeanReversion
eps with confidence. ConfidenceWeightedMeanReversion- Selects the confidence constraint that reads the variance of the belief along the price relative.
VarianceUpdate - Selects the confidence constraint that reads the standard deviation of the belief along the price relative.
StandardDeviationUpdate
- Moves wealth from an asset that grew more to one whose log returns follow its own one window later.
AntiCorrelation
Pattern-matching and solved rules
Re-solves an optimisation estimator on a sample of past periods at every step, the follow-the-leader rule. FollowTheLeader
FollowTheLeader- Selects every period so far, the sample of follow the leader.
Prefix - Selects the last
Wperiods, the sample of the successive variable rebalanced portfolio.LastRows - Selects the periods whose preceding window falls in the same histogram cell as the latest window (BH).
HistogramMatch - Selects the periods whose preceding window lies within
radiusof the latest window (BK).KernelMatch - Selects the periods whose preceding windows are the
neighboursnearest to the latest window (BNN).NearestNeighbourMatch - Selects the periods whose preceding window correlates with the latest window at
rhoor more (CORN).CorrelationMatch - Selects the periods whose preceding window falls in the same cluster as the latest window (KMNLOG).
ClusterMatch - Builds the short-term portfolio optimisation with loss control (SPOLC).
ShortTermLossControlPortfolio - Builds the online low-dimension ensemble method (OLDEM).
LowDimensionEnsemblePortfolio
Meta-learning rules
Mixes the allocations of several expert rules, with weights that a second rule moves on the experts' returns. ExpertMixture
ExpertMixture- Makes every expert of a mixture read its gradient at its own iterate, the default Gradient Point.
OwnPoint - Makes every first-order expert of a mixture read its gradient at the blend that the mixture played, while it steps from its own iterate.
BlendPoint - Builds the improved Ader, an
ExpertMixtureofKGradientProjectionexperts on a geometric grid of rates.Ader - Builds the small-loss Sword, an
ExpertMixtureofKGradientProjectionexperts on a geometric grid of rates, from the uniform start.Sword - Builds the switching portfolio, the
ExpertMixtureunderSwitchingWeightingover theNsingle-assetConstantRebalancedPortfolios of the pinned universe (SP).SwitchingPortfolio
Weightings over the experts
- Multiplies each weight by its price relative raised to the rate
eta, then normalises the result.AggregatingAlgorithm - Holds the $k$ wealthiest assets, or experts, each weighted by its wealth.
TopK - Weights each asset, or expert, by its prior times its wealth raised to a power that shrinks with the period.
WeakAggregatingAlgorithm - Moves each weight to the other entries with probability $\gamma$ after the wealth step, the switching weighting (SP).
SwitchingWeighting
- Mixes copies of one rule started at different periods, with a fixed share for the newest copy (FLH).
FollowTheLeadingHistory
Projection geometries
- Projects the raw step onto the Allocation Set in squared Euclidean distance.
EuclideanProjection - Projects the raw step onto the Allocation Set in relative entropy.
EntropicProjection - Projects the raw step onto the Allocation Set in the Bregman divergence of the Tsallis potential of power
alpha.TsallisProjection - Projects the raw step onto the Allocation Set in the Itakura–Saito divergence, the Bregman divergence of the Burg entropy.
LogBarrierProjection - Projects the raw step onto the Allocation Set in the norm of the rule's Gram matrix.
GramProjection
Allocation sets
- Limits the allocation to the budget and to per-asset weight bounds, with closed-form projections and no solver.
BoundedAllocationSet - Constrains an online allocation with every constraint kind of a JuMP optimiser, and projects onto the set with a solver.
ProgrammeAllocationSet
Traditional
These optimisations build a JuMP problem through JuMPOptimiser, which holds every constraint they support. The constraints and the penalties are in its ConstraintBlock, and each of them is also a keyword of the optimiser. Build a block directly to give one feasible set to more than one optimiser.
Objective function optimisations
These optimisations take one of the objective functions below.
- Names one JuMP solver, the attributes to set on it, and the solution statuses to accept.
Solver - Holds the problem definition and the solver settings that every JuMP optimiser shares.
JuMPOptimiser - Holds the feasible set of the weights of a programme, and the terms that the programme adds to the Objective Penalty.
ConstraintBlock
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
Optimises one objective of risk and return over the portfolios that the constraints of a JuMP model admit. 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 - The data that
near_optimal_centering_setupcomputes before the centring model ofNearOptimalCenteringis built.NearOptimalSetup
Risk budgeting optimisations
These optimisations find the weights at which each asset, or each factor, contributes the share of risk that a risk budget vector states.
Budget targets
- Selects a risk budget over the assets, and the formulation that solves for it.
AssetRiskBudgeting
Formulations
- Selects the log-barrier formulation of the risk budgeting condition, in one orthant of the weights.
LogRiskBudgeting - Selects the mixed-integer formulation of the risk budgeting condition, which searches every orthant of the weights.
MixedIntegerRiskBudgeting
- Selects a risk budget over the factors of a loadings regression.
FactorRiskBudgeting
Optimisation estimators
- Risk Budgeting
RiskBudgetingreturns aRiskBudgetingResult
Relaxed Risk Budgeting RelaxedRiskBudgeting returns a RelaxedRiskBudgetingResult
RelaxedRiskBudgeting returns a RelaxedRiskBudgetingResult- Selects Model (A) of
RelaxedRiskBudgeting, where the standard deviation of the portfolio alone bounds $\psi$.BasicRelaxedRiskBudgeting - Selects Model (B) of
RelaxedRiskBudgeting, which adds a regulating term $\rho$ that the standard deviation of the portfolio bounds.RegularisedRelaxedRiskBudgeting - Selects Model (C) of
RelaxedRiskBudgeting, where the variances of the single assets, times the penaltyp, bound the regulating term $\rho$.RegularisedPenalisedRelaxedRiskBudgeting
Traditional optimisation features
- Abstract supertype for a term that the user adds to the objective of the JuMP model.
CustomJuMPObjective - Abstract supertype for a constraint that the user writes into the JuMP model.
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 Universe Sets key whose groups become the rows of a binary asset-group membership matrix.
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
- Turnover bounds before
turnover_constraintsaligns them to a universe.TurnoverEstimatorandTurnover - Names the per-asset fee rates, for
fees_constraintsto align to a universe.FeesEstimatorandFees - Bounds the deviation of the portfolio return series from a benchmark return series.
TrackingError - Fits the relatedness of the assets to returns, and caps the number of related assets that the portfolio holds at once.
IntegerPhylogenyEstimatorandSemiDefinitePhylogenyEstimator
Portfolio returns
- One return term, or a vector of them, summed at their weights into the return expression of the model
- 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 - An expected returns vector you state
- An expected returns estimator, which the optimisation evaluates on its 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 penalty term that a
JuMPOptimiseradds to the objective.L2Regularisation - Lp-norm penalty term that a
JuMPOptimiseradds to the objective, or a ceiling on the Lp norm of the weights.LpRegularisation - L-Inf
Weight-norm constraints
A regularisation penalty puts a norm of the weights in the objective. These constraints bound the norm instead.
- L2 (
l2c) - Lp (
lpc) - L-Inf (
linfc)
- Sets the risk aversion coefficients of an L-moment OWA weight vector to the normalised constant relative risk aversion coefficients of
g.NormalisedConstantRelativeRiskAversion
Clustering optimisation
Clustering optimisations split the assets into clusters from their relationships, and optimise the clusters in a hierarchy or one at a time.
- Holds the prior, the clustering, the bounds and the fees that a hierarchical optimiser shares with its siblings.
HierarchicalOptimiser
Hierarchical clustering optimisation
These optimisations split the assets into a hierarchy of clusters, compute the risk of each cluster, and combine the clusters by the hierarchy.
Each result holds the risk measures and the scalarisers of its optimisation, after the optimisation resolved them. It holds its other fields in an embedded HierarchicalResult, which you reach as res.hr, or one field at a time as res.w, res.pr and so on.
- Hierarchical Risk Parity
HierarchicalRiskParityreturns aHierarchicalRiskParityResult - Hierarchical Equal Risk Contribution
HierarchicalEqualRiskContributionreturns aHierarchicalEqualRiskContributionResult - Holds the fields that the results of hierarchical risk parity and hierarchical equal risk contribution share.
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 every scalariser exceptMinScalariser. - 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
- Moves the weights into their bounds by a repeated clip and a proportional redistribution of the clipped mass.
IterativeWeightFinaliser - Moves weights into their bounds by the exact Euclidean projection, which needs no solver.
EuclideanWeightFinaliser - Moves long-only weights into their bounds by the exact entropic projection, which needs no solver and keeps the ratios of the free weights.
EntropicWeightFinaliser
Moves the weights into their bounds with the solution of a JuMP programme. JuMPWeightFinaliser
JuMPWeightFinaliser- Selects the norm of a weight deviation as the objective of a JuMP weight finaliser.
ErrorWeightFinaliser - Selects the deviation relative to the target weights, $\boldsymbol{x} \oslash (c\, \tilde{\boldsymbol{w}}_{0}) - \boldsymbol{1}$.
RelativeWeightDeviation - Selects the deviation from the target weights, $\boldsymbol{x} - c\, \boldsymbol{w}_{0}$.
AbsoluteWeightDeviation
Schur complementary optimisation
Schur complementary hierarchical risk parity interpolates between hierarchical risk parity and mean-variance optimisation through one parameter, gamma. At gamma = 0 it is hierarchical risk parity, and a larger gamma moves it towards mean variance. It adjusts the weights of each group of assets with the Schur complement of the covariance matrix, which puts back the covariance between the groups that hierarchical risk parity ignores.
- Schur Complementary Hierarchical Risk Parity
SchurComplementHierarchicalRiskParityreturns aSchurComplementHierarchicalRiskParityResult
Collects the risk measure, the interpolation parameter $\gamma$ and the two algorithms of one Schur complement bundle. SchurComplementParams
SchurComplementParams- Caps $\gamma$ at the first turning point of the portfolio variance in $[0, \gamma]$.
MonotonicSchurComplement - Selects the allocation at the value of $\gamma$ that the caller gives, 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
- Moves the weights into their bounds by a repeated clip and a proportional redistribution of the clipped mass.
IterativeWeightFinaliser - Moves weights into their bounds by the exact Euclidean projection, which needs no solver.
EuclideanWeightFinaliser - Moves long-only weights into their bounds by the exact entropic projection, which needs no solver and keeps the ratios of the free weights.
EntropicWeightFinaliser
Moves the weights into their bounds with the solution of a JuMP programme. JuMPWeightFinaliser
JuMPWeightFinaliser- Selects the norm of a weight deviation as the objective of a JuMP weight finaliser.
ErrorWeightFinaliser - Selects the deviation relative to the target weights, $\boldsymbol{x} \oslash (c\, \tilde{\boldsymbol{w}}_{0}) - \boldsymbol{1}$.
RelativeWeightDeviation - Selects the deviation from the target weights, $\boldsymbol{x} - c\, \boldsymbol{w}_{0}$.
AbsoluteWeightDeviation
Nested clusters optimisation
Nested clustered optimisation splits the N assets into C clusters and optimises each cluster as a portfolio of its own. The inner weights go into an N × C matrix. Each column is one cluster, and it holds the weights of one synthetic asset. An asset has a non-zero weight only in the column of its own cluster. Each row of the matrix then holds one non-zero value, and each column holds as many non-zero values as its cluster has assets.
There are two ways to get the returns of the synthetic assets:
- Multiply the
T × Nmatrix of asset returns by theN × Cmatrix of weights. The product is aT × Cmatrix of returns, whereTis the number of observations. - Run a cross-validation prediction for each cluster, which gives one vector of returns per cluster. Put the vectors side by side in a
Y × Cmatrix, whereY ≤ Tbecause the cross-validation can leave out part of the history.
The outer estimator optimises the synthetic assets on that matrix of returns, which gives a C × 1 vector of weights, one per cluster. The weights of the assets are the product of the N × C matrix and that C × 1 vector, an N × 1 vector.
- 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
- Moves the weights into their bounds by a repeated clip and a proportional redistribution of the clipped mass.
IterativeWeightFinaliser - Moves weights into their bounds by the exact Euclidean projection, which needs no solver.
EuclideanWeightFinaliser - Moves long-only weights into their bounds by the exact entropic projection, which needs no solver and keeps the ratios of the free weights.
EntropicWeightFinaliser
Moves the weights into their bounds with the solution of a JuMP programme. JuMPWeightFinaliser
JuMPWeightFinaliser- Selects the norm of a weight deviation as the objective of a JuMP weight finaliser.
ErrorWeightFinaliser - Selects the deviation relative to the target weights, $\boldsymbol{x} \oslash (c\, \tilde{\boldsymbol{w}}_{0}) - \boldsymbol{1}$.
RelativeWeightDeviation - Selects the deviation from the target weights, $\boldsymbol{x} - c\, \boldsymbol{w}_{0}$.
AbsoluteWeightDeviation
The collapse of a time-varying asset panel onto the synthetic assets, which weighs the members that are active at each observation
- Collapses an Asset Panel over the members that are active at each observation, and divides by their weight.
RenormaliseActive - Collapses an Asset Panel over the members that are active at each observation, and reads the weight of an inactive member as cash with a zero feature.
InactiveAsCash
- Cross validation predictor for the outer estimator
Ensemble optimisation
Stacking works like nested clustered optimisation, but it does not split the assets. You give it a list of inner estimators, and each one optimises every asset. Each column of the N × C matrix then holds the weights of one inner estimator, so the matrix has no fixed pattern of zeros. The rest of the procedure is the same.
- 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
- Moves the weights into their bounds by a repeated clip and a proportional redistribution of the clipped mass.
IterativeWeightFinaliser - Moves weights into their bounds by the exact Euclidean projection, which needs no solver.
EuclideanWeightFinaliser - Moves long-only weights into their bounds by the exact entropic projection, which needs no solver and keeps the ratios of the free weights.
EntropicWeightFinaliser
Moves the weights into their bounds with the solution of a JuMP programme. JuMPWeightFinaliser
JuMPWeightFinaliser- Selects the norm of a weight deviation as the objective of a JuMP weight finaliser.
ErrorWeightFinaliser - Selects the deviation relative to the target weights, $\boldsymbol{x} \oslash (c\, \tilde{\boldsymbol{w}}_{0}) - \boldsymbol{1}$.
RelativeWeightDeviation - Selects the deviation from the target weights, $\boldsymbol{x} - c\, \boldsymbol{w}_{0}$.
AbsoluteWeightDeviation
- Cross validation predictor for the outer estimator
Subset resampling optimisation
Subset resampling draws random subsets of the assets, as MultipleRandomised cross-validation does, and optimises each subset with the optimiser you give it. The weight of each asset is its mean weight over all subsets, with a weight of zero in each subset that does not hold it.
SubsetResamplingreturns aSubsetResamplingResult
Subset resampling optimisation features
- Any features supported by the inner estimator.
Subset sizes
- A number of assets, a fraction of the assets, or a callable.
- Sizes each asset subset as a power of the number of assets, the subset size of [4].
PowerSubsetSize
- 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
- Moves the weights into their bounds by a repeated clip and a proportional redistribution of the clipped mass.
IterativeWeightFinaliser - Moves weights into their bounds by the exact Euclidean projection, which needs no solver.
EuclideanWeightFinaliser - Moves long-only weights into their bounds by the exact entropic projection, which needs no solver and keeps the ratios of the free weights.
EntropicWeightFinaliser
Moves the weights into their bounds with the solution of a JuMP programme. JuMPWeightFinaliser
JuMPWeightFinaliser- Selects the norm of a weight deviation as the objective of a JuMP weight finaliser.
ErrorWeightFinaliser - Selects the deviation relative to the target weights, $\boldsymbol{x} \oslash (c\, \tilde{\boldsymbol{w}}_{0}) - \boldsymbol{1}$.
RelativeWeightDeviation - Selects the deviation from the target weights, $\boldsymbol{x} - c\, \boldsymbol{w}_{0}$.
AbsoluteWeightDeviation
Finite allocation optimisation
A finite allocation turns the weights of another optimisation into whole lots of shares, at the latest prices, with a stated amount of cash. Its answer is the allocation closest to those weights that the cash can buy, not an optimum of its own. The lot unit of each asset is one share by default, a fraction of a share for a broker that sells fractions, or a board lot.
Discrete Allocation portfolio optimiser. DiscreteAllocation
DiscreteAllocationWeight finalisers
- Moves the weights into their bounds by a repeated clip and a proportional redistribution of the clipped mass.
IterativeWeightFinaliser - Moves weights into their bounds by the exact Euclidean projection, which needs no solver.
EuclideanWeightFinaliser - Moves long-only weights into their bounds by the exact entropic projection, which needs no solver and keeps the ratios of the free weights.
EntropicWeightFinaliser
Moves the weights into their bounds with the solution of a JuMP programme. JuMPWeightFinaliser
JuMPWeightFinaliser- Selects the norm of a weight deviation as the objective of a JuMP weight finaliser.
ErrorWeightFinaliser - Selects the deviation relative to the target weights, $\boldsymbol{x} \oslash (c\, \tilde{\boldsymbol{w}}_{0}) - \boldsymbol{1}$.
RelativeWeightDeviation - Selects the deviation from the target weights, $\boldsymbol{x} - c\, \boldsymbol{w}_{0}$.
AbsoluteWeightDeviation
- Greedy Allocation portfolio optimiser.
GreedyAllocation - Returns a resolved lot unit unchanged.
lot_unit_constraints,LotUnitEstimator, andLotUnit
Holds the target weights, prices and cash that a finite allocation reads. FiniteAllocationInput
FiniteAllocationInputCollateral algorithms
- Pays for the long side of a finite allocation with the proceeds of its short sales.
ProceedsCollateral - Caps the money that a finite allocation ties up at a collateral amount.
CashCollateral
Unpriced weight algorithms
- Moves the target weight of each Unpriced Asset to the priced assets of its side, in proportion to their target weights.
ProportionalRedistribution - Moves the target weight of each Unpriced Asset to the priced assets of its side, in equal parts.
EvenRedistribution - Moves the target weight of each Unpriced Asset to the assets that
idxnames, in equal parts.AssetRedistribution - Moves the target weight of the Unpriced Assets of the long side with one rule, and of the short side with another.
SideRedistribution
Cross validation
- Prediction on data the fit did not see,
PredictionReturnsResult,PredictionResult,MultiPeriodPredictionResultandPopulationPredictionResult, throughpredict(res::NonFiniteAllocationOptimisationResult, rd::ReturnsResult)andfit_and_predict - Union of the values that the
scorerfield ofNestedClusteredandStackingaccepts: aPredictionScoreror a plain function.PredictionCrossValScorer,NearestQuantilePrediction, andquantile_by_measure - Run cross-validated portfolio optimisation and return predictions over all folds.
cross_val_predict - The weights a fold started from, and, through
fold_held, the weights it held after its last observation, on the fold's own asset names.fold_targetandfold_held - Fit optimisation estimator
opton returns datard, and predict over 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 returns a WalkForwardResult
WalkForwardEstimator returns a WalkForwardResult- Implements index-based walk-forward cross-validation for time series, supporting purging and flexible train/test windowing.
IndexWalkForwardandDateWalkForward - Hindsight split
HindsightSplittrains each fold on its own test row, with the rows up to and including it or with that row alone. An estimator run through it is therefore a hindsight comparator for each row, an estimator fit on the row it is scored on - Online walk-forward
OnlineIndexWalkForward,OnlineDateWalkForwardandOnlineHindsightSplitwrap a scheme inOnline. Each fold then updates one estimator with its new observations in place of a refit, and passes the estimator on to the next fold - Resume
Resumecontinues an online walk-forward from its result over the longer history, andvcatjoins the two results
- Multiple randomised
MultipleRandomisedreturns aMultipleRandomisedResult
A scheme scores each fold under an evaluation convention. SelfFinancingDrift scores the series of a fold on the weights the fund holds, not on the weights the optimiser chose, and the fold then holds a HeldWeightsResult. A walk-forward can also pass those held weights to the next fold, and it does when it drifts and states no source. TargetWeights passes the target weights instead.
- Thread the weights a fold held after its last observation into the fold that follows it.
DriftedWeights - Thread the target weights of a fold into the fold that follows it, whatever the scheme's Weight Drift is.
TargetWeights - Records what a fold actually held, so a reader can recover the weight path of that fold.
HeldWeightsResult
Score every candidate of the grid of gscv on every fold of gscv.cv, and return the winner. search_cross_validation
gscv on every fold of gscv.cv, and return the winner. 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
- One ranking for each value
EachValueinr_scaors_scakeeps each risk measure or each search scorer apart, and the search gives one ranking and one winner for each of them - Combining the measures after the search scorer
PerCandidateinr_scacombines the risk measures once per candidate, after the search scorer reduces the folds or the paths of each measure
- Abstract supertype for estimators that determine the number of random subsets to draw.
NumberSubsetsEstimatorandSubsetSizeEstimator - Abstract supertype for estimators that determine the rolling window size.
WindowSizeEstimator
Covariance forecast evaluation
covariance_forecast_evaluation scores the forecast of a covariance estimator, or of a prior, against the returns realised after it. It steps through a walk-forward. With a scheme that refits, each step refits the estimator, and with an online walk-forward, each step updates it. The evaluation centres the test rows on the location that the estimator forecasts, and it keeps the diagnostics of each step. The summary, the comparison and the re-projection are then functions of 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 computation for one step on bare arrays,
covariance_forecast_step, for a forecast from outside the library
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 functions of 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, one test per loss.
covariance_forecast_compare - The Diebold–Mariano–West comparison of two covariance forecasts, one row per loss.
CovarianceForecastComparisonResult - Score the stored forecasts of an evaluation again, on a new test portfolio.
covariance_forecast_portfolio
The weight of each step in the mean of a calibration ratio.
- Weights each scored step by the degrees of freedom of its ratio under a Gaussian null.
DofStepWeighting - Gives each scored step the same weight, so the mean of a ratio is its plain mean over the steps.
EqualStepWeighting
Log-wealth regret
log_wealth_regret reads two prediction results scored over the same rows. It returns the difference in log terminal wealth between a comparator and a strategy, the difference row by row, and a test that the two have the same expected log growth, WildBootstrapMeanTest by default. The comparator is any prediction result over the rows. It can be the same estimator run causally. It can also be a hindsight comparator, fit on the rows it is scored on and predicted in sample. Through a HindsightSplit the comparator changes from row to row, which gives the dynamic regret, and the result reports the path length of the comparator beside the regret. BudgetedHindsightPath is the best sequence of comparators whose path length stays within a budget. Its fit solves one programme over the whole panel, and its prediction result has one fold per row. Pass it as the comparator to read the regret at a given budget.
- The log-wealth regret of strategy
aagainst comparatorbover one and the same sequence of rows.log_wealth_regretandLogWealthRegretResult - Fits the path of per-row allocations with the largest log wealth whose summed step length is at most
L.BudgetedHindsightPathandBudgetedHindsightPathResult
Pipeline
A Pipeline holds a whole workflow as one estimator. It is an ordered list of steps that run from left to right over a PipelineContext. The preprocessing, the priors and the optimiser then form one estimator, which you can cross-validate or tune as a unit.
- Runs an ordered list of steps as one end-to-end portfolio workflow.
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
The plotting functions draw a portfolio, its history, its risk and the diagnostics of the models behind it. They are in a package extension, which loads when you load StatsPlots. The network plot is in a second extension, which also needs GraphRecipes.
Simple or compound cumulative returns.
- Plot the cumulative returns of a portfolio against time.
plot_portfolio_cumulative_returns - Plot the cumulative contribution of each asset to the portfolio return, one line per asset.
plot_asset_cumulative_returns
Portfolio composition.
- Plot the composition of a portfolio as a bar chart of its asset weights.
plot_composition
Several portfolios.
- Plot the compositions of several portfolios as a stacked bar chart, one bar per portfolio.
plot_stacked_bar_composition - Plot the compositions of several portfolios as a stacked area chart, one band per asset.
plot_stacked_area_composition
Risk contribution.
- Plot the risk contribution of each asset as a bar chart.
plot_risk_contribution - Plot the risk contribution of each factor as a bar chart.
plot_factor_risk_contribution
- Plot the dendrogram of a hierarchical clustering, with one shaded region per cluster.
plot_dendrogram - Plot the similarity matrix of a clustering as a heatmap in the order of the clustering, with a dendrogram on two sides and a box round each cluster.
plot_clusters - Plot the cumulative returns of a portfolio above its drawdown, in two panels that share the time axis.
plot_drawdowns - Plot the maximum drawdown of the portfolio over a rolling window, in percent, against the last date of each window.
plot_rolling_drawdowns - Plot the histogram of the returns of a portfolio, with a vertical line for each of several statistics and an optional fitted Normal density.
plot_histogram - Plot a scatter of two or three measures over a collection of portfolios, coloured by a fourth.
plot_measures - Plot a risk or return measure of the portfolio returns over a rolling window, against the last date of each window.
plot_rolling_measure - Plot a collection of portfolios as a line ordered by risk, coloured by a score, to trace an efficient frontier.
plot_efficient_frontier - Plot the distribution of the weight of each asset over the folds of a path or the members of a population, as one box per asset.
plot_weight_stability - Plot the turnover of a sequence of portfolios, the $L_1$ change of the weights from one portfolio to the next.
plot_turnover - Plot the cumulative returns of a portfolio beside those of one or more benchmarks.
plot_benchmark
Moments and priors
- Plot the expected return of each asset as a bar chart.
plot_mu - Plot the volatility of each asset, the square root of the diagonal of the covariance, as a bar chart.
plot_sigma - Plot a correlation matrix as a heatmap, with no clustering and no dendrogram.
plot_correlation - Plot the coskewness matrix, $N \times N^2$, of a
HighOrderPrioras a heatmap on a diverging colour scale centred at zero.plot_coskewness - Plot the eigenvalues of the cokurtosis matrix, $N^2 \times N^2$, of a
HighOrderPrioras a bar chart sorted from the largest, or the matrix itself as a heatmap.plot_cokurtosis - Plot the eigenvalues of a covariance or correlation matrix as a bar chart, sorted from the largest.
plot_eigenspectrum - Plot a prior result as three panels side by side: the expected returns, the volatilities and the correlation.
plot_prior
Factor models
- Plot the expected return of each factor as a bar chart.
plot_factor_mu - Plot the correlation of the factor returns as a heatmap, through
plot_correlation.plot_factor_sigma - Plot the factor loadings matrix, assets by factors, as a heatmap on a diverging colour scale centred at zero.
plot_factor_loadings
Cross-sectional regression diagnostics
- Plot the weighted cross-sectional coefficient of determination of every cross-sectional fit.
plot_cs_regression_r2 - Plot the adjusted cross-sectional coefficient of determination of every cross-sectional fit.
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 the t-statistic of each factor exceeds a threshold, one bar per factor.
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, with the colour limits
(-1, 1).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 - Several forecasts on one plot, one series per evaluation over the dates they share, through the vector methods of
plot_forecast_cumulative_icandplot_forecast_cumulative_returns
Covariance forecast evaluation
- Plot the rolling calibration of a covariance forecast: the Mahalanobis ratio, the diagonal ratio and the bias statistic over a window of steps, with a reference line at one.
plot_covariance_calibration - Plot the rolling mean of the QLIKE loss of the variance of the test portfolios of a covariance forecast.
plot_covariance_qlike - Plot the rolling rate at which the Mahalanobis statistic of a covariance forecast exceeds the chi-squared quantile of each level, with a dashed line at the target rate of each level.
plot_covariance_exceedance - Several covariance forecasts on one plot, one series per evaluation, through the vector method of each figure
plot_covariance_calibration,plot_covariance_qlike, andplot_covariance_exceedance
Phylogeny
- Plot the network of the assets as a graph, with
GraphRecipes.graphplot.plot_network - Plot the centrality score of each asset as a bar chart, sorted from the largest.
plot_centrality
Cross validation
- Plot the score of each fold or population member as a bar chart.
plot_cv_scores - Plot a walk-forward path as four panels in a 2 × 2 layout: its fold compositions, its cumulative returns, its turnover and the stability of its weights.
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
- Plot one optimisation result as four panels in a 2 × 2 layout: its composition, its cumulative returns, its risk contributions and its drawdown.
plot_portfolio_dashboard - Plot the performance statistics of one or more portfolios as bars, blue at a value of zero or more and red below it.
plot_performance_summary