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.
See also
- Parameters:
- risk_measureRiskMeasure, default=RiskMeasure.STANDARD_DEVIATION
RiskMeasureto minimize on excess returns. The default isRiskMeasure.STANDARD_DEVIATION.- prior_estimatorBasePrior, optional
Prior estimator. The prior estimator is used to estimate the
ReturnDistributionof excess returns (portfolio returns - benchmark returns). The default (None) is to useEmpiricalPrior.- min_weightsfloat | dict[str, float] | array-like of shape (n_assets, ) | None, default=0.0
Minimum assets weights (weights lower bounds). See
MeanRiskfor details.- max_weightsfloat | dict[str, float] | array-like of shape (n_assets, ) | None, default=1.0
Maximum assets weights (weights upper bounds). See
MeanRiskfor details.- max_shortfloat, optional
Maximum short position. See
MeanRiskfor details.- max_longfloat, optional
Maximum long position. See
MeanRiskfor details.- cardinalityint, optional
Cardinality constraint to limit the number of invested assets. See
MeanRiskfor details.- group_cardinalitiesdict[str, int], optional
Cardinality constraints for specific groups of assets. See
MeanRiskfor details.- threshold_longfloat | dict[str, float] | array-like of shape (n_assets, ), optional
Minimum weight threshold for long positions. See
MeanRiskfor details.- threshold_shortfloat | dict[str, float] | array-like of shape (n_assets, ), optional
Maximum weight threshold for short positions. See
MeanRiskfor details.- transaction_costsfloat | dict[str, float] | array-like of shape (n_assets, ), default=0.0
Transaction costs of the assets. See
MeanRiskfor details.- management_feesfloat | dict[str, float] | array-like of shape (n_assets, ), default=0.0
Management fees of the assets. See
MeanRiskfor details.- previous_weightsfloat | dict[str, float] | array-like of shape (n_assets, ), optional
Previous weights of the assets. See
MeanRiskfor details.- l1_coeffloat, default=0.0
L1 regularization coefficient. See
MeanRiskfor details.- l2_coeffloat, default=0.0
L2 regularization coefficient. See
MeanRiskfor details.- groupsdict[str, list[str]] or array-like of shape (n_groups, n_assets), optional
The assets groups. See
MeanRiskfor details.- linear_constraintsarray-like of shape (n_constraints,), optional
Linear constraints. See
MeanRiskfor details.- left_inequalityarray-like of shape (n_constraints, n_assets), optional
Left inequality matrix. See
MeanRiskfor details.- right_inequalityarray-like of shape (n_constraints, ), optional
Right inequality vector. See
MeanRiskfor details.- risk_free_ratefloat, default=0.0
Risk-free interest rate. See
MeanRiskfor details.- solverstr, default=”CLARABEL”
The solver to use. See
MeanRiskfor details.- solver_paramsdict, optional
Solver parameters. See
MeanRiskfor details.- scale_objectivefloat, optional
Scale each objective element by this value. See
MeanRiskfor details.- scale_constraintsfloat, optional
Scale each constraint element by this value. See
MeanRiskfor details.- save_problembool, default=False
If this is set to True, the CVXPY Problem is saved in
problem_. SeeMeanRiskfor details.- add_objectiveCallable[[cp.Variable], cp.Expression], optional
Add a custom objective to the existing objective expression. See
MeanRiskfor details.- add_constraintsCallable[[cp.Variable], cp.Expression|list[cp.Expression]], optional
Add a custom constraint or a list of constraints. See
MeanRiskfor details.- portfolio_paramsdict, optional
Portfolio parameters. See
MeanRiskfor details.- fallbackBaseOptimization | “previous_weights” | list[BaseOptimization | “previous_weights”], optional
Fallback estimator or list of estimators. See
MeanRiskfor details.- raise_on_failurebool, default=True
Controls error handling when fitting fails. See
MeanRiskfor 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_estimatoron excess returns.- problem_: cvxpy.Problem
CVXPY problem used for the optimization. Only when
save_problemis set toTrue.- 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
fitfails.
Methods
fit(X, y, **fit_params)Fit the Return-Based Tracker estimator.
fit_predict(X)Perform
fitonXand returns the predictedPortfolioorPopulationofPortfolioonXbased on the fittedweights.Get metadata routing of this object.
get_params([deep])Get parameters for this estimator.
predict(X)Predict the
Portfolioor aPopulationof portfolios onX.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
MeanRiskwhere the input asset returnsXand benchmark returnsyare first transformed to excess returnsX_excess = X - ybefore 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 usingsklearn.set_config(enable_metadata_routing=True). See Metadata Routing User Guide for more details.
- Returns:
- selfBenchmarkTracker
Fitted estimator.
- fit_predict(X)#
Perform
fitonXand returns the predictedPortfolioorPopulationofPortfolioonXbased on the fittedweights. For factor models, usefit(X, y)thenpredict(X)separately.If fitting fails and
raise_on_failure=False, this returns aFailedPortfolio.- Parameters:
- Xarray-like of shape (n_observations, n_assets)
Price returns of the assets.
- Returns:
- Portfolio | Population
The predicted
PortfolioorPopulationbased on the fittedweights.
- get_metadata_routing()#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
- routingMetadataRequest
A
MetadataRequestencapsulating 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_weightsmust be propagated between folds/rebalances.Used by
cross_val_predictto decide whether to run sequentially and pass the weights from the previous rebalancing to the next. This isTruewhen transaction costs, a maximum turnover, or a fallback depending onprevious_weightsare present.
- predict(X)#
Predict the
Portfolioor aPopulationof portfolios onX.Optimization estimators can return a 1D or a 2D array of
weights. For a 1D array, the prediction is a singlePortfolio. For a 2D array, the prediction is aPopulationofPortfolio.If
nameis 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
ReturnDistributioncarrying returns and optional sample weights.
- Returns:
- Portfolio | Population
The predicted
PortfolioorPopulationbased on the fittedweights.
- 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 aPopulation, 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
Portfolioor the mean of all the portfolios Sharpe Ratios if the prediction is aPopulationofPortfolio.
- 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.