API Reference#

This is the class and function reference of skfolio. Please refer to the full user guide for further details, as the class and function raw specifications may not be enough to give full guidelines on their uses.

skfolio.measures: Measures#

Module that includes all Measures functions used across skfolio.

Base Class#

measures.BaseMeasure

Base Enum of measures.

Classes#

measures.PerfMeasure

Enumeration of performance measures.

measures.RiskMeasure

Enumeration of risk measures.

measures.ExtraRiskMeasure

Enumeration of other risk measures not used in convex optimization.

measures.RatioMeasure

Enumeration of ratio measures.

Functions#

measures.mean(returns[, sample_weight])

Compute the mean.

measures.get_cumulative_returns(returns[, ...])

Compute the cumulative returns from a series of returns.

measures.get_drawdowns(returns[, compounded])

Compute the drawdowns' series from the returns.

measures.variance(returns[, biased, ...])

Compute the variance (second moment).

measures.semi_variance(returns[, ...])

Compute the semi-variance (second lower partial moment).

measures.standard_deviation(returns[, ...])

Compute the standard-deviation (square root of the second moment).

measures.semi_deviation(returns[, ...])

Compute the semi-deviation (square root of the second lower partial moment).

measures.third_central_moment(returns[, ...])

Compute the third central moment.

measures.fourth_central_moment(returns[, ...])

Compute the Fourth central moment.

measures.fourth_lower_partial_moment(returns)

Compute the fourth lower partial moment.

measures.skew(returns[, sample_weight])

Compute the Skew.

measures.kurtosis(returns[, sample_weight])

Compute the Kurtosis.

measures.cvar(returns[, beta, sample_weight])

Compute the historical CVaR (conditional value at risk).

measures.mean_absolute_deviation(returns[, ...])

Compute the mean absolute deviation (MAD).

measures.value_at_risk(returns[, beta, ...])

Compute the historical value at risk (VaR).

measures.worst_realization(returns)

Compute the worst realization (worst return).

measures.first_lower_partial_moment(returns)

Compute the first lower partial moment.

measures.entropic_risk_measure(returns[, ...])

Compute the entropic risk measure.

measures.evar(returns[, beta])

Compute the EVaR (entropic value at risk) and its associated risk aversion.

measures.drawdown_at_risk(drawdowns[, beta])

Compute the Drawdown at risk.

measures.cdar(drawdowns[, beta])

Compute the historical CDaR (conditional drawdown at risk).

measures.max_drawdown(drawdowns)

Compute the maximum drawdown.

measures.average_drawdown(drawdowns)

Compute the average drawdown.

measures.edar(drawdowns[, beta])

Compute the EDaR (entropic drawdown at risk).

measures.ulcer_index(drawdowns)

Compute the Ulcer index.

measures.gini_mean_difference(returns)

Compute the Gini mean difference (GMD).

measures.owa_gmd_weights(n_observations)

Compute the OWA weights used for the Gini mean difference (GMD) computation.

measures.effective_number_assets(weights)

Compute the effective number of assets, defined as the inverse of the Herfindahl index.

measures.correlation(X[, sample_weight])

Compute the correlation matrix.

skfolio.portfolio: Portfolio#

Portfolio module. Portfolio and MultiPeriodPortfolio objects are returned by the predict method of Optimization estimators. They must be consistent with the convex optimization problems, meaning that Portfolio is the dot product of the assets weights with the assets returns and MultiPeriodPortfolio is a list of Portfolio.

Base Class#

portfolio.BasePortfolio

Base Portfolio class for all portfolios in skfolio.

Classes#

portfolio.Portfolio

Portfolio class.

portfolio.FailedPortfolio

Portfolio object returned when an optimization step fails.

portfolio.MultiPeriodPortfolio

Multi-Period Portfolio class.

skfolio.population: Population#

Population module.

Classes#

population.Population

Population Class.

skfolio.containers: Containers#

Containers module.

Classes#

containers.AssetPanel

Container for aligned cross-sectional asset data.

containers.AssetPanelView

Observation-sliced view into an AssetPanel.

Field Base Class#

containers.BaseField

Base class for fields stored in an AssetPanel.

containers.Field2D

Numeric 2D field with axes (observations, assets).

containers.Field3D

Numeric 3D field with axes (observations, assets, third_axis).

containers.FieldCategorical

Integer-coded categorical 2D field.

Enum#

containers.InactivePolicy

Validation policy for values outside an AssetPanel active universe.

Functions#

containers.concat(panels, *[, ...])

Concatenate panels along the observation axis.

skfolio.base: Base Estimators#

Base classes for all estimators and various utility functions.

Classes#

base.BaseAssetPanelTransformer

Base class for estimators that transform asset panel data.

base.BaseComposition

Handles parameter management for ensemble estimators.

skfolio.optimization.base: Base Optimization Estimator#

Optimization module.

Classes#

optimization.BaseOptimization

Base class for all portfolio optimizations in skfolio.

skfolio.optimization.naive: Naive Optimization Estimators#

Naive Optimization module.

Classes#

optimization.EqualWeighted

Equally Weighted estimator.

optimization.InverseVolatility

Inverse Volatility estimator.

optimization.Random

Random weight estimator.

skfolio.optimization.convex: Convex Optimization Estimators#

Convex Optimization module.

Enum#

optimization.ObjectiveFunction

Enumeration of objective functions.

Classes#

optimization.ConvexOptimization

Base class for all convex optimization estimators in skfolio.

optimization.MeanRisk

Mean-Risk Optimization estimator.

optimization.BenchmarkTracker

Benchmark Tracker Optimization estimator.

optimization.RiskBudgeting

Risk Budgeting Optimization estimator.

optimization.MaximumDiversification

Maximum Diversification Optimization estimator.

optimization.DistributionallyRobustCVaR

Distributionally Robust CVaR.

skfolio.optimization.cluster: Clustering Optimization Estimators#

Cluster Optimization module.

Classes#

optimization.BaseHierarchicalOptimization

Base Hierarchical Clustering Optimization estimator.

optimization.HierarchicalRiskParity

Hierarchical Risk Parity estimator.

optimization.HierarchicalEqualRiskContribution

Hierarchical Equal Risk Contribution estimator.

optimization.SchurComplementary

Schur Complementary Allocation estimator.

optimization.NestedClustersOptimization

Nested Clusters Optimization estimator.

skfolio.optimization.ensemble: Ensemble Optimization Estimators#

Ensemble Optimization module.

Classes#

optimization.StackingOptimization

Stack of optimizations with a final optimization.

skfolio.prior: Prior Estimators#

Prior module.

Model Dataclass#

prior.ReturnDistribution

Return distribution estimated by a prior estimator.

prior.FactorModel

Factor model decomposition of asset returns.

prior.CovarianceSqrt

Matrix square root decomposition of a covariance matrix.

Base Class#

prior.BasePrior

Base class for all prior estimators in skfolio.

Classes#

prior.EmpiricalPrior

Empirical Prior estimator.

prior.BlackLitterman

Black & Litterman estimator.

prior.TimeSeriesFactorModel

Time-series factor model estimator.

prior.CharacteristicsFactorModel

Characteristics-based cross-sectional factor model.

prior.SyntheticData

Synthetic Data Estimator.

prior.EntropyPooling

Entropy Pooling estimator.

prior.OpinionPooling

Opinion Pooling estimator.

Loading Matrix Classes for Factor Models#

prior.BaseLoadingMatrix

Base class for all Loading Matrix estimators.

prior.LoadingMatrixRegression

Loading Matrix Regression estimator.

Factor Model Components#

Descriptors that map AssetPanel columns to factor characteristics.

Descriptor Base Classes#

descriptor.BaseDescriptor

Base class for all descriptor transformers.

Descriptors#

descriptor.AccrualsCashFlow

Cash-flow statement accruals descriptor.

descriptor.AnalystDispersionToPrice

Analyst forecast dispersion to price descriptor.

descriptor.AssetTurnover

Asset turnover descriptor.

descriptor.AssetsGrowthRate

Asset growth rate descriptor.

descriptor.BookLeverage

Book leverage descriptor.

descriptor.BookToPrice

Book-to-price ratio descriptor.

descriptor.CapexToAssetsChangeInIntensity

Lagged change in capex-to-assets intensity.

descriptor.CashFlowToAssets

Cash flow to assets descriptor.

descriptor.CashFlowToPrice

Cash-flow-to-price ratio descriptor.

descriptor.ChangeInIntensity

Lagged change in a field-to-scale ratio.

descriptor.ChangeToScale

Lagged change normalized by a positive scale.

descriptor.DaysToCover

Exponentially weighted days-to-cover descriptor.

descriptor.DebtToAssets

Debt-to-assets ratio descriptor.

descriptor.DividendToPrice

Dividend-to-price ratio descriptor.

descriptor.EWAmihudIlliquidity

Exponentially weighted Amihud illiquidity descriptor.

descriptor.EWDownsideBeta

Exponentially weighted downside beta descriptor.

descriptor.EWDownsideVolatility

Exponentially weighted downside return volatility descriptor.

descriptor.EWMacroSensitivity

EWMA macro sensitivity after removing market exposure.

descriptor.EWMarketBeta

Exponentially weighted market beta descriptor.

descriptor.EWMomentum

Exponentially weighted momentum descriptor.

descriptor.EWResidualDownsideVolatility

Exponentially weighted downside CAPM residual volatility descriptor.

descriptor.EWResidualVolatility

Exponentially weighted CAPM residual volatility descriptor.

descriptor.EWShareTurnover

Exponentially weighted share turnover descriptor.

descriptor.EWVolatility

Exponentially weighted volatility descriptor.

descriptor.EarningsChangeToPrice

Lagged earnings change divided by current market capitalization.

descriptor.EarningsToPrice

Earnings-to-price ratio descriptor.

descriptor.EbitdaToEnterpriseValue

EBITDA-to-enterprise-value ratio descriptor.

descriptor.ForwardDividendToPrice

Forward dividend-to-price ratio descriptor.

descriptor.ForwardEarningsToPrice

Forward earnings-to-price ratio descriptor.

descriptor.GrossMargin

Gross margin descriptor.

descriptor.GrossProfitability

Gross profitability descriptor.

descriptor.GrowthRate

Period-over-period growth rate descriptor.

descriptor.IssuanceGrowthRate

Issuance growth rate descriptor.

descriptor.LogMarketCap

Log market capitalization descriptor.

descriptor.MarketLeverage

Market leverage descriptor.

descriptor.MaxReturn

Maximum return over a trailing window.

descriptor.Passthrough

Passthrough descriptor for an AssetPanel field.

descriptor.ReturnOnAssets

Return on assets (ROA) descriptor.

descriptor.ReturnOnEquity

Return on equity (ROE) descriptor.

descriptor.Reversal

Fixed-window short-term reversal descriptor.

descriptor.RollingMomentum

Fixed-window momentum descriptor.

descriptor.SalesGrowthRate

Sales growth rate descriptor.

descriptor.SalesToEnterpriseValue

Sales to enterprise value descriptor.

descriptor.SalesToPrice

Sales-to-price ratio descriptor.

descriptor.ShareholderYield

Shareholder yield descriptor.

descriptor.ShortInterest

Short interest descriptor.

Factor exposure transformers.

Factor Exposure Estimators#

factor_exposure.BaseFactorExposure

Base class for factor exposure estimators.

factor_exposure.DerivedFactor

Factor exposure derived from another factor's computed exposure.

factor_exposure.FixedWeightedFactor

Factor exposure as a fixed weighted combination of descriptors.

factor_exposure.GlobalFactor

Constant factor exposure equal to one for every asset.

factor_exposure.OneHotCategoricalFactors

One-hot factor exposures from a categorical field.

Alpha models for factor-model score construction.

Alpha Estimators#

alpha.BaseAlpha

Base class for all Alpha estimators in skfolio.

alpha.EWSharpeOptimalAlpha

Exponentially weighted least-squares Sharpe-optimal alpha estimator.

alpha.FixedWeightedAlpha

Fixed-weighted descriptor alpha estimator.

alpha.PredictorAlpha

Predictor alpha estimator using a user-provided regressor.

Alpha Evaluation#

alpha.AlphaForecastComparison

Side-by-side comparison of alpha forecast evaluations.

alpha.AlphaForecastEvaluation

Out-of-sample alpha forecast evaluation.

Functions#

alpha.alpha_forecast_evaluation(estimator, X, *)

Evaluate alpha forecast quality.

Enum#

alpha.ForecastUnit

Unit of the intermediate alpha forecast.

utils.stats.CSWeighting

Cross-sectional weighting.

utils.stats.CorrelationMethod

Correlation method.

Factor-based volatility and return attribution.

Attribution#

attribution.Attribution

Factor attribution result.

attribution.AssetBreakdown

Per-asset attribution breakdown.

attribution.AssetByFactorContribution

Asset-by-factor contribution breakdown.

attribution.BaseBreakdown

Base class for attribution breakdowns.

attribution.Component

Portfolio attribution component.

attribution.FactorBreakdown

Per-factor attribution breakdown.

attribution.FamilyBreakdown

Family-level attribution breakdown.

Attribution Functions#

attribution.predicted_factor_attribution(...)

Compute predicted (ex-ante) factor volatility and return attribution.

attribution.realized_factor_attribution(*, ...)

Compute realized (ex-post) factor volatility and return attribution.

attribution.rolling_realized_factor_attribution(*, ...)

Compute rolling realized (ex-post) factor volatility and return attribution.

skfolio.moments.expected_returns: Expected Returns Estimators#

Expected returns module.

Base Class#

moments.BaseMu

Base class for all expected returns estimators in skfolio.

Classes#

moments.EmpiricalMu

Empirical Expected Returns (Mu) estimator.

moments.EWMu

Exponentially Weighted Expected Returns (Mu) estimator.

moments.ShrunkMu

Shrinkage Expected Returns (Mu) estimator.

moments.EquilibriumMu

Equilibrium Expected Returns (Mu) estimator.

moments.ShrunkMuMethods

Shrinkage methods for the ShrunkMu estimator.

skfolio.moments.variance: Variance Estimators#

Variance module.

Base Class#

moments.BaseVariance

Base class for all variance estimators in skfolio.

Classes#

moments.EmpiricalVariance

Empirical Variance estimator.

moments.EWVariance

Exponentially Weighted Variance estimator.

moments.RegimeAdjustedEWVariance

Exponentially weighted variance estimator with regime adjustment via the Short-Term Volatility Update (STVU) [R1cff04c74aab-1].

skfolio.moments.covariance: Covariance Estimators#

Covariance module.

Base Class#

moments.BaseCovariance

Base class for all covariance estimators in skfolio.

Enum#

moments.RegimeAdjustmentMethod

Transformation used to map the STVU statistic to the volatility multiplier.

moments.RegimeAdjustmentTarget

Target dimension used to calibrate the short-term volatility update (STVU).

Classes#

moments.EmpiricalCovariance

Empirical Covariance estimator.

moments.EWCovariance

Exponentially Weighted Covariance estimator with NaN-aware pairwise updates.

moments.GerberCovariance

Gerber Covariance estimator.

moments.DenoiseCovariance

Covariance Denoising estimator.

moments.DetoneCovariance

Covariance Detoning estimator.

moments.LedoitWolf

LedoitWolf Covariance Estimator.

moments.OAS

Oracle Approximating Shrinkage Estimator as proposed in [Re9a22b087643-1].

moments.ShrunkCovariance

Covariance estimator with shrinkage.

moments.GraphicalLassoCV

Sparse inverse covariance with cross-validated choice of the l1 penalty.

moments.ImpliedCovariance

Implied Covariance estimator.

moments.RegimeAdjustedEWCovariance

Exponentially weighted covariance estimator with regime adjustment via the Short-Term Volatility Update (STVU) [R9fdb90a74052-1].

skfolio.distance: Distance Estimators#

Distance Estimators.

Base Class#

distance.BaseDistance

Base class for all distance estimators in skfolio.

Classes#

distance.PearsonDistance

Pearson Distance estimator.

distance.KendallDistance

Kendall Distance estimator.

distance.SpearmanDistance

Spearman Distance estimator.

distance.CovarianceDistance

Covariance Distance estimator.

distance.DistanceCorrelation

Distance Correlation estimator.

distance.MutualInformation

Mutual Information estimator.

skfolio.cluster: Cluster Estimators#

Hierarchical Clustering estimators.

Classes#

cluster.HierarchicalClustering

Hierarchical Clustering.

cluster.LinkageMethod

Methods for calculating the distance between clusters in the linkage matrix.

skfolio.uncertainty_set: Uncertainty set Estimators#

Uncertainty Set module.

Model Dataclass#

uncertainty_set.UncertaintySet

Norm-ball uncertainty set.

uncertainty_set.CompactCovarianceUncertaintySet

Compact representation of a quadratic covariance uncertainty penalty.

Base Classes#

uncertainty_set.BaseMuUncertaintySet

Base class for all Mu Uncertainty Set estimators in skfolio.

uncertainty_set.BaseCovarianceUncertaintySet

Base class for all Covariance Uncertainty Set estimators in skfolio.

Classes#

uncertainty_set.EmpiricalMuUncertaintySet

Empirical Mu Uncertainty Set.

uncertainty_set.EmpiricalCovarianceUncertaintySet

Empirical Covariance Uncertainty set.

uncertainty_set.BootstrapMuUncertaintySet

Bootstrap Mu Uncertainty set.

uncertainty_set.BootstrapCovarianceUncertaintySet

Bootstrap Covariance Uncertainty set.

uncertainty_set.OrthogonalMuUncertaintySet

Expected return uncertainty set estimator for directions outside the factor span.

uncertainty_set.OrthogonalCovarianceUncertaintySet

Covariance uncertainty set estimator for directions outside the factor span.

skfolio.pre_selection: Pre-selection Transformers#

Pre Selection module.

Classes#

pre_selection.DropCorrelated

Transformer for dropping highly correlated assets.

pre_selection.DropZeroVariance

Transformer for dropping assets with near-zero variance.

pre_selection.SelectKExtremes

Transformer for selecting the k best or worst assets.

pre_selection.SelectNonDominated

Transformer for selecting non dominated assets.

pre_selection.SelectComplete

Transformer to select assets with complete data across the entire observation period.

pre_selection.SelectNonExpiring

Transformer to select assets that do not expire within a specified lookahead period after the end of the observation period.

skfolio.linear_model: Cross-sectional linear models#

Linear model module.

Base Class#

linear_model.BaseCSLinearModel

Base class for all cross-sectional linear model estimators.

Classes#

linear_model.CSLinearRegression

Cross-sectional weighted least squares regression.

linear_model.CSLinearRegressorWrapper

Cross-sectional regression based on a scikit-learn regressor.

skfolio.model_selection: Model Selection#

Model selection module.

Base Classes#

model_selection.BaseCombinatorialCV

Base class for all combinatorial cross-validators.

Classes#

model_selection.WalkForward

Walk Forward Cross-Validator.

model_selection.CombinatorialPurgedCV

Combinatorial Purged Cross-Validation.

model_selection.MultipleRandomizedCV

Multiple Randomized Cross-Validation.

model_selection.OnlineGridSearch

Online exhaustive hyperparameter search over a parameter grid.

model_selection.OnlineRandomizedSearch

Online randomized search on hyperparameters.

model_selection.CovarianceForecastEvaluation

Out-of-sample covariance forecast evaluation.

model_selection.CovarianceForecastComparison

Side-by-side comparison of covariance forecast evaluations.

Functions#

model_selection.cross_val_predict(estimator, X)

Generate cross-validated Portfolios estimates.

model_selection.online_predict(estimator, X)

Generate out-of-sample portfolios using online learning.

model_selection.online_score(estimator, X[, ...])

Score an online estimator using walk-forward evaluation.

model_selection.online_covariance_forecast_evaluation(...)

Evaluate out-of-sample covariance forecast quality.

model_selection.covariance_forecast_evaluation(...)

Evaluate out-of-sample covariance forecast quality using walk-forward cross-validation.

model_selection.optimal_folds_number(...[, ...])

Find the optimal number of folds (total folds and test folds) for a target training size and a target number of test paths.

skfolio.metrics: Metrics#

Metrics module.

Functions#

metrics.make_scorer(score_func[, ...])

Make a scorer from a measure, a portfolio score function, or a non-predictor estimator score function.

metrics.diagonal_calibration_loss(estimator, ...)

Diagonal calibration loss.

metrics.diagonal_calibration_ratio(...[, y])

Diagonal calibration ratio based on marginal variances.

metrics.exceedance_rate(squared_distances, ...)

Exceedance rate for chi-squared calibration statistics.

metrics.mahalanobis_calibration_loss(...[, y])

Mahalanobis calibration loss.

metrics.mahalanobis_calibration_ratio(...[, y])

Mahalanobis calibration ratio.

metrics.portfolio_variance_calibration_loss(...)

Portfolio variance calibration loss.

metrics.portfolio_variance_calibration_ratio(...)

Portfolio variance calibration ratio.

metrics.portfolio_variance_qlike_loss(...[, ...])

QLIKE loss for a projected portfolio variance forecast [R7dedfcdc36e0-1].

metrics.qlike_loss(returns, forecast_variance)

QLIKE loss for univariate variance forecasts.

skfolio.datasets: Datasets#

Functions#

datasets.load_sp500_dataset()

Load the prices of 20 assets from the S&P 500 Index.

datasets.load_sp500_index()

Load the prices of the S&P 500 Index.

datasets.load_factors_dataset()

Load the prices of 5 factor ETFs.

datasets.load_ftse100_dataset([data_home, ...])

Load the prices of 64 assets from the FTSE 100 Index composition.

datasets.load_nasdaq_dataset([data_home, ...])

Load the prices of 1455 assets from the NASDAQ Composite Index.

datasets.load_sp500_implied_vol_dataset([...])

Load the 3 months ATM implied volatility of the 20 assets from the SP500 dataset.

datasets.make_synthetic_characteristics([...])

Generate a synthetic characteristics AssetPanel.

skfolio.preprocessing: Preprocessing#

Preprocessing module.

Base Class#

preprocessing.BaseCSTransformer

Base class for all cross-sectional transformers in skfolio.

Classes#

preprocessing.CSGaussianRankScaler

Cross-sectional rank Gaussianization.

preprocessing.CSPercentileRankScaler

Cross-sectional percentile rank.

preprocessing.CSStandardScaler

Cross-sectional standardization.

preprocessing.CSTanhShrinker

Cross-sectional tanh outlier shrinker.

preprocessing.CSWinsorizer

Cross-sectional winsorization.

Functions#

preprocessing.prices_to_returns(X[, y, ...])

Transform a DataFrame of prices to linear or logarithmic returns.

skfolio.utils.tools: Tools#

Classes#

tools.AutoEnum

Base Enum class used in skfolio.

tools.cached_property_slots

Cached property decorator for slots.

Functions#

tools.apply_window_size(X, window_size)

Return the last window_size observations from the array X.

tools.args_names(func)

Returns the argument names of a function.

tools.bisection(x)

Generator to bisect a list of arrays.

tools.cache_method(cache_name)

Decorator that caches class method results into a class dictionary.

tools.check_estimator(estimator, default, ...)

Check the estimator type and return its cloned version if provided, otherwise return the default estimator.

tools.deduplicate_names(names)

Rename duplicated names by appending "_{duplicate_nb}" at the end.

tools.default_asset_names(n_assets)

Default asset names are ["x0", "x1", ..., "x(n_assets - 1)"].

tools.fit_and_predict(estimator, X, y, ...)

Fit the estimator and predict values for a given dataset split.

tools.fit_single_estimator(estimator, X, y, ...)

Fit (or partial-fit) an estimator on a subset of the data.

tools.format_measure(x[, percent])

Format a measure number into a user-friendly string.

tools.get_feature_names(X)

Get feature names from X.

tools.half_life_to_decay_factor(half_life)

Convert half-life to exponential decay factor.

tools.input_to_array(items, n_assets, ...[, ...])

Convert a collection of items (array-like or dictionary) into a numpy array and verify its shape.

tools.optimal_rounding_decimals(x)

Return the optimal rounding decimal number for a user-friendly formatting.

tools.safe_indexing(X, indices[, axis])

Return rows, items or columns of X using indices.

tools.safe_split(X[, y, indices, axis])

Create subset of dataset.

tools.validate_input_list(items, n_assets, ...)

Convert a list of items (asset indices or asset names) into a list of validated asset indices.

skfolio.utils.stats: Stats#

Enum#

stats.NBinsMethod

Enumeration of the Number of Bins Methods.

Functions#

stats.assert_is_distance(x)

Raises an error if the matrix is not a distance matrix.

stats.assert_is_square(x)

Raises an error if the matrix is not square.

stats.assert_is_symmetric(x, *[, rtol, atol])

Raises an error if the matrix is not symmetric.

stats.combination_by_index(idx, n, k)

Retrieve the k-combination at a given lexicographic position without enumerating all combinations.

stats.commutation_matrix(x)

Compute the commutation matrix.

stats.compute_optimal_n_clusters(distance, ...)

Compute the optimal number of clusters based on Two-Order Difference to Gap Statistic [Re0e718a4c413-1].

stats.corr_to_cov(corr, std)

Convert a correlation matrix to a covariance matrix given its standard-deviation vector.

stats.cov_nearest(cov[, higham, ...])

Compute the nearest covariance matrix that is positive definite and with a cholesky decomposition that can be computed.

stats.cov_to_corr(cov)

Convert a covariance matrix to a correlation matrix.

stats.cs_pearson_correlation(a, b[, ...])

Weighted cross-sectional Pearson correlation.

stats.cs_rank(a[, axis])

Cross-sectional rank along an axis.

stats.cs_spearman_correlation(a, b[, axis, ...])

Cross-sectional Spearman rank correlation.

stats.inverse_multiply(a, b)

Multiply the inverse of matrix a by matrix b.

stats.inverse_volatility_weights(covariance)

Inverse-volatility portfolio weights from a covariance matrix.

stats.safe_cholesky(covariance[, ...])

Compute a Cholesky factor \(L\) from covariance \(\Sigma\).

stats.is_cholesky_dec(x)

Returns True if Cholesky decomposition can be computed.

stats.minimize_relative_weight_deviation(...)

Apply weight constraints to an initial array of weights by minimizing the relative weight deviation of the final weights from the initial weights.

stats.multiply_by_inverse(a, b)

Multiply matrix a by the inverse of matrix b.

stats.n_bins_freedman(x)

Compute the optimal histogram bin size using the Freedman-Diaconis rule [R8d5b646da1d1-1].

stats.n_bins_knuth(x)

Compute the optimal histogram bin size using Knuth's rule [R8c3fe88ee915-1].

stats.rand_weights(n[, zeros, seed])

Produces n random weights that sum to one from a uniform distribution (non-uniform distribution over a simplex).

stats.rand_weights_dirichlet(n)

Produces n random weights that sum to one from a Dirichlet distribution (uniform distribution over a simplex).

stats.sample_unique_subsets(n, k, n_subsets)

Generate unique k-element subsets from a universe of size n using combinatorial unranking.

stats.squared_mahalanobis_dist(X, covariance)

Squared Mahalanobis distance via Cholesky decomposition.

stats.squared_standardized_euclidean_dist(...)

Squared standardized Euclidean distance.

stats.symmetric_step_up_matrix(n1, n2)

Compute the Symmetric step-up matrix M such that M @ np.ones(n2) = np.ones(n1).

stats.symmetrize(matrix[, where])

In-place symmetrization: \(M \leftarrow (M + M^T) / 2\).

skfolio.distribution: Distribution Estimators#

Distribution module.

Base Class#

distribution.BaseDistribution

Base Distribution Estimator.

Enum#

distribution.SelectionCriterion

Enum representing the selection criteria.

skfolio.distribution.univariate: Univariate Distribution Estimators#

Univariate Distribution module.

Base Class#

distribution.BaseUnivariateDist

Base Univariate Distribution Estimator.

Classes#

distribution.Gaussian

Gaussian Distribution Estimation.

distribution.StudentT

Student's t Distribution Estimation.

distribution.JohnsonSU

Johnson SU Distribution Estimation.

distribution.NormalInverseGaussian

Normal Inverse Gaussian Distribution Estimation.

Functions#

distribution.select_univariate_dist(X[, ...])

Select the optimal univariate distribution estimator based on an information criterion.

skfolio.distribution.multivariate: Multivariate Distribution Estimators#

Multivariate Distribution module.

Base Class#

distribution.BaseMultivariateDist

Base class for Multivariate Distribution Estimators.

Classes#

distribution.VineCopula

Regular Vine Copula Estimator.

Enum#

distribution.DependenceMethod

Enumeration of methods to measure bivariate dependence.

skfolio.distribution.copula: Bivariate Copula Estimators#

Copula module.

Base Class#

distribution.BaseBivariateCopula

Base class for Bivariate Copula Estimators.

Classes#

distribution.GaussianCopula

Bivariate Gaussian Copula Estimation.

distribution.StudentTCopula

Bivariate Student's t Copula Estimation.

distribution.ClaytonCopula

Bivariate Clayton Copula Estimation.

distribution.GumbelCopula

Bivariate Gumbel Copula Estimation.

distribution.JoeCopula

Bivariate Joe Copula Estimation.

distribution.IndependentCopula

Bivariate Independent Copula (also called the product copula).

Functions#

distribution.compute_pseudo_observations(X)

Compute pseudo-observations by ranking each column of the data and scaling the ranks.

distribution.empirical_tail_concentration(X, ...)

Compute empirical tail concentration for the two variables in X.

distribution.plot_tail_concentration(...[, ...])

Plot the empirical tail concentration curves.

distribution.select_bivariate_copula(X[, ...])

Select the best bivariate copula from a list of candidates using an information criterion.

Enum#

distribution.CopulaRotation

Enum representing the rotation (in degrees) to apply to a bivariate copula.