skfolio.model_selection.cross_val_predict#
- skfolio.model_selection.cross_val_predict(estimator, X, y=None, cv=None, n_jobs=None, method='predict', verbose=0, params=None, pre_dispatch='2*n_jobs', column_indices=None, portfolio_params=None, entry_rebalancing_params=None)[source]#
Generate cross-validated portfolios.
The data is split according to the
cvparameter. The optimization estimator is fitted on the training set and portfolios are predicted on the corresponding test set.For single-path cross-validation such as
KFoldorWalkForward, the output is aMultiPeriodPortfoliowhere eachPortfoliocorresponds to a train/test split (kportfolios forKFold).For multi-path cross-validation such as
CombinatorialPurgedCVorMultipleRandomizedCV, the output is aPopulationof multipleMultiPeriodPortfolioobjects (each test produces a collection of paths rather than a single path).When a list of
(name, estimator)pairs is provided, all estimators are evaluated on the same splits and their portfolios are returned together in aPopulation.If the final estimator in the pipeline (or the estimator itself) declares
needs_previous_weights=True, this function automatically propagatesprevious_weightsfrom one fold to the next for sequential CV strategies (e.g.,WalkForwardorMultipleRandomizedCV).- Parameters:
- estimatorBaseEstimator | Pipeline | sequence of (str, estimator)
Portfolio optimization estimator or pipeline whose last step is an optimization estimator. To evaluate several estimators, pass a sequence of
(name, estimator)pairs with unique string names.- Xarray-like of shape (n_observations, n_assets)
Price returns of the assets.
- yarray-like of shape (n_observations, n_targets), optional
Target data (optional). For example, the price returns of the factors.
- cvint | cross-validation generator, optional
Determines the cross-validation splitting strategy. Possible inputs for cv are:
None, to use the default 5-fold cross validation,
int, to specify the number of folds in a
(Stratified)KFold,CV splitter,An iterable that generates (train, test) splits as arrays of indices.
- n_jobsint, optional
The number of jobs to run in parallel.
Nonemeans 1 unless in ajoblib.parallel_backendcontext. -1 means using all processors. Named estimators share one worker pool. Folds that depend on previous holdings run sequentially within each path.- methodstr
Invokes the passed method name of the passed estimator.
- verboseint, default=0
The verbosity level.
- paramsdict, optional
Parameters to pass to the underlying estimator’s
fitand the CV splitter.- pre_dispatchint or str, default=’2*n_jobs’
Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:
None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs
An int, giving the exact number of total jobs that are spawned
A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
- column_indicesndarray, optional
Indices of the
Xcolumns to cross-validate on.- portfolio_paramsdict, optional
Portfolio parameters for the evaluation.
Parameters shared by
PortfolioandMultiPeriodPortfolio(compounded,risk_free_rate,annualization_factor,fitness_measuresand the risk measure parameters) are applied to the returnedMultiPeriodPortfolioand to eachPortfolioit contains. A value passed here takes precedence over the optimizer’sportfolio_params. When omitted here, it is inherited from the optimizer’sportfolio_params. When omitted from both,risk_free_ratefalls back to the optimizer’srisk_free_rateparameter when it has one. These parameters only affect how the portfolios are measured, not the optimization.weight_driftapplies to eachPortfolioof the path. Withweight_drift=True, the weights held within each test window drift with the asset returns, and the path runs sequentially: theending_weightsof each portfolio are passed asprevious_weightsto the next fit. A value passed here overrides the optimizer’sportfolio_params.Optimization parameters such as
transaction_costs,management_feesandprevious_weightsare not accepted here. Set them on the optimization estimator.name,tag,sample_weightandcheck_observations_orderapply to the returnedMultiPeriodPortfolioonly.For named estimators, these settings apply to every estimator.
nameandtagare set from the estimator names and cannot be overridden here.- entry_rebalancing_paramsdict, optional
Optimization estimator parameters applied only while constructing the first portfolio of each sequential path. This is useful when the strategy starts with no existing position, while later portfolios represent regular rebalancing from the previously predicted weights. For example, the entry rebalancing can relax
max_turnoveror use lowertransaction_coststo avoid a slow ramp from cash caused by recurring rebalancing constraints. The first portfolio is included in the result. The regular estimator parameters are used for all subsequent optimizations. When provided,cross_val_predictevaluates a sequential strategy path and propagatesprevious_weightsbetween portfolios. This is only supported for sequential CV strategies such asWalkForward,TimeSeriesSplitandMultipleRandomizedCV. For named estimators, these settings apply to every estimator.
- Returns:
- predictionsMultiPeriodPortfolio | Population
A
MultiPeriodPortfoliofor single-path CV, or aPopulationfor multi-path CV. Named estimators always return aPopulation, with oneMultiPeriodPortfolioper estimator and path, ordered by estimator then path. Estimator names setnameandtag.
Notes
With a sequential CV, each portfolio’s
ending_weightsare passed asprevious_weightsto the next fit when the estimator needs them. Otherwise, fits remain independent and previous weights are assigned to the predicted portfolios afterward for turnover and cost calculations. Ending weights equal the targetweightswhenweight_drift=Falseand the weights after the last observation whenweight_drift=True. Failed and empty portfolios are skipped when propagating holdings. With a non-sequential CV, drift is applied inside each test fold and nothing is propagated.Examples
Evaluate an inverse-volatility portfolio with walk-forward cross-validation:
>>> from skfolio.datasets import load_sp500_dataset >>> from skfolio.model_selection import WalkForward, cross_val_predict >>> from skfolio.optimization import EqualWeighted, InverseVolatility >>> from skfolio.preprocessing import prices_to_returns
>>> prices = load_sp500_dataset() >>> X = prices_to_returns(prices)
>>> cv = WalkForward(train_size=252, test_size=63) >>> mpp = cross_val_predict(InverseVolatility(), X, cv=cv) # MultiPeriodPortfolio
To compare estimators on the same splits, pass a list of named estimators:
>>> estimators = [ ... ("equal_weighted", EqualWeighted()), ... ("inverse_volatility", InverseVolatility()), ... ] >>> population = cross_val_predict(estimators, X, cv=cv) >>> [mpp.name for mpp in population] ['equal_weighted', 'inverse_volatility']