skfolio.optimization.BenchmarkTracker#

class skfolio.optimization.BenchmarkTracker(risk_measure=Standard Deviation, prior_estimator=None, min_weights=0.0, max_weights=1.0, max_short=None, max_long=None, cardinality=None, group_cardinalities=None, threshold_long=None, threshold_short=None, transaction_costs=0.0, management_fees=0.0, previous_weights=None, groups=None, linear_constraints=None, left_inequality=None, right_inequality=None, l1_coef=0.0, l2_coef=0.0, risk_free_rate=0.0, solver='CLARABEL', solver_params=None, scale_objective=None, scale_constraints=None, save_problem=False, add_objective=None, add_constraints=None, portfolio_params=None, fallback=None, raise_on_failure=True)[source]#

Benchmark Tracker Optimization estimator.

Optimize a portfolio to track a benchmark by minimizing the risk of benchmark-relative (excess) returns.

This estimator minimizes the tracking risk between portfolio returns and a benchmark’s returns by optimizing directly on excess (active) returns, defined as portfolio returns minus benchmark returns.

Tracking risk can be defined using any of the available risk measures. Typical choices include standard deviation (tracking-error volatility), semi-deviation and mean absolute deviation.

Parameters:
risk_measureRiskMeasure, default=RiskMeasure.STANDARD_DEVIATION

RiskMeasure to minimize on excess returns. The default is RiskMeasure.STANDARD_DEVIATION.

prior_estimatorBasePrior, optional

Prior estimator. The prior estimator is used to estimate the ReturnDistribution of excess returns (portfolio returns - benchmark returns). The default (None) is to use EmpiricalPrior.

min_weightsfloat | dict[str, float] | array-like of shape (n_assets, ) | None, default=0.0

Minimum assets weights (weights lower bounds). See MeanRisk for details.

max_weightsfloat | dict[str, float] | array-like of shape (n_assets, ) | None, default=1.0

Maximum assets weights (weights upper bounds). See MeanRisk for details.

max_shortfloat, optional

Maximum short position. See MeanRisk for details.

max_longfloat, optional

Maximum long position. See MeanRisk for details.

cardinalityint, optional

Cardinality constraint to limit the number of invested assets. See MeanRisk for details.

group_cardinalitiesdict[str, int], optional

Cardinality constraints for specific groups of assets. See MeanRisk for details.

threshold_longfloat | dict[str, float] | array-like of shape (n_assets, ), optional

Minimum weight threshold for long positions. See MeanRisk for details.

threshold_shortfloat | dict[str, float] | array-like of shape (n_assets, ), optional

Maximum weight threshold for short positions. See MeanRisk for details.

transaction_costsfloat | dict[str, float] | array-like of shape (n_assets, ), default=0.0

Transaction costs of the assets. See MeanRisk for details.

management_feesfloat | dict[str, float] | array-like of shape (n_assets, ), default=0.0

Management fees of the assets. See MeanRisk for details.

previous_weightsfloat | dict[str, float] | array-like of shape (n_assets, ), optional

Previous weights of the assets. See MeanRisk for details.

l1_coeffloat, default=0.0

L1 regularization coefficient. See MeanRisk for details.

l2_coeffloat, default=0.0

L2 regularization coefficient. See MeanRisk for details.

groupsdict[str, list[str]] or array-like of shape (n_groups, n_assets), optional

The assets groups. See MeanRisk for details.

linear_constraintsarray-like of shape (n_constraints,), optional

Linear constraints. See MeanRisk for details.

left_inequalityarray-like of shape (n_constraints, n_assets), optional

Left inequality matrix. See MeanRisk for details.

right_inequalityarray-like of shape (n_constraints, ), optional

Right inequality vector. See MeanRisk for details.

risk_free_ratefloat, default=0.0

Risk-free interest rate. See MeanRisk for details.

solverstr, default=”CLARABEL”

The solver to use. See MeanRisk for details.

solver_paramsdict, optional

Solver parameters. See MeanRisk for details.

scale_objectivefloat, optional

Scale each objective element by this value. See MeanRisk for details.

scale_constraintsfloat, optional

Scale each constraint element by this value. See MeanRisk for details.

save_problembool, default=False

If this is set to True, the CVXPY Problem is saved in problem_. See MeanRisk for details.

add_objectiveCallable[[cp.Variable], cp.Expression], optional

Add a custom objective to the existing objective expression. See MeanRisk for details.

add_constraintsCallable[[cp.Variable], cp.Expression|list[cp.Expression]], optional

Add a custom constraint or a list of constraints. See MeanRisk for details.

portfolio_paramsdict, optional

Portfolio parameters. See MeanRisk for details.

fallbackBaseOptimization | “previous_weights” | list[BaseOptimization | “previous_weights”], optional

Fallback estimator or list of estimators. See MeanRisk for details.

raise_on_failurebool, default=True

Controls error handling when fitting fails. See MeanRisk for details.

Attributes:
weights_ndarray of shape (n_assets,)

Weights of the assets.

problem_values_dict[str, float]

Expression values retrieved from the CVXPY problem.

prior_estimator_BasePrior

Fitted prior_estimator on excess returns.

problem_: cvxpy.Problem

CVXPY problem used for the optimization. Only when save_problem is set to True.

n_features_in_int

Number of assets seen during fit.

feature_names_in_ndarray of shape (n_features_in_,)

Names of assets seen during fit.

fallback_BaseOptimization | “previous_weights” | None

The fallback estimator instance that produced the final result.

fallback_chain_list[tuple[str, str]] | None

Sequence describing the optimization fallback attempts.

error_str | None

Captured error message when fit fails.

Methods

fit(X, y, **fit_params)

Fit the Return-Based Tracker estimator.

fit_predict(X)

Perform fit on X and returns the predicted Portfolio or Population of Portfolio on X based on the fitted weights.

get_metadata_routing()

Get metadata routing of this object.

get_params([deep])

Get parameters for this estimator.

predict(X)

Predict the Portfolio or a Population of portfolios on X.

score(X[, y])

Prediction score using the Sharpe Ratio.

set_params(**params)

Set the parameters of this estimator.

Notes

It is implemented as a special case of MeanRisk where the input asset returns X and benchmark returns y are first transformed to excess returns X_excess = X - y before optimization. A full-investment constraint (budget = 1.0) is always enforced because:

\[r_t^{excess}(w) = \sum_i w_i(r_{t,i} - r_{b,t}) = r_{p,t} - (\sum_i w_i)r_{b,t}\]

where \(r_{p,t}\) is the portfolio return and \(r_{b,t}\) the benchmark return, coincides with the active (benchmark-relative) return

\[r_{p,t} - r_{b,t}\]

when \(\sum_i w_i = 1\)

References

[1]

“Portfolio Optimization: Theory and Application”, Chapter 13, Daniel P. Palomar (2025)

fit(X, y, **fit_params)[source]#

Fit the Return-Based Tracker estimator.

Parameters:
Xarray-like of shape (n_observations, n_assets)

Price returns of the assets.

yarray-like of shape (n_observations, 1)

Price returns of the benchmark.

**fit_paramsdict

Parameters to pass to the underlying estimators. Only available if enable_metadata_routing=True, which can be set by using sklearn.set_config(enable_metadata_routing=True). See Metadata Routing User Guide for more details.

Returns:
selfBenchmarkTracker

Fitted estimator.

fit_predict(X)#

Perform fit on X and returns the predicted Portfolio or Population of Portfolio on X based on the fitted weights. For factor models, use fit(X, y) then predict(X) separately.

If fitting fails and raise_on_failure=False, this returns a FailedPortfolio.

Parameters:
Xarray-like of shape (n_observations, n_assets)

Price returns of the assets.

Returns:
Portfolio | Population

The predicted Portfolio or Population based on the fitted weights.

get_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)#

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

property needs_previous_weights#

Whether previous_weights must be propagated between folds/rebalances.

Used by cross_val_predict to decide whether to run sequentially and pass the weights from the previous rebalancing to the next. This is True when transaction costs, a maximum turnover, or a fallback depending on previous_weights are present.

predict(X)#

Predict the Portfolio or a Population of portfolios on X.

Optimization estimators can return a 1D or a 2D array of weights. For a 1D array, the prediction is a single Portfolio. For a 2D array, the prediction is a Population of Portfolio.

If name is not provided in the portfolio parameters, the estimator class name is used.

Parameters:
Xarray-like of shape (n_observations, n_assets) | ReturnDistribution

Asset returns or a ReturnDistribution carrying returns and optional sample weights.

Returns:
Portfolio | Population

The predicted Portfolio or Population based on the fitted weights.

score(X, y=None)#

Prediction score using the Sharpe Ratio. If the prediction is a single Portfolio, the score is its Sharpe Ratio. If the prediction is a Population, the score is the mean Sharpe Ratio across portfolios.

Parameters:
Xarray-like of shape (n_observations, n_assets)

Price returns of the assets.

yIgnored

Not used, present here for API consistency by convention.

Returns:
scorefloat

The Sharpe Ratio of the portfolio if the prediction is a single Portfolio or the mean of all the portfolios Sharpe Ratios if the prediction is a Population of Portfolio.

set_params(**params)#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.