skfolio.portfolio.FailedPortfolio#

class skfolio.portfolio.FailedPortfolio(X, name=None, tag=None, optimization_error=None, fallback_chain=None, previous_weights=None, transaction_costs=None, management_fees=None, risk_free_rate=0, annualized_factor=252, fitness_measures=None, compounded=False, sample_weight=None, min_acceptable_return=None, value_at_risk_beta=0.95, entropic_risk_measure_theta=1, entropic_risk_measure_beta=0.95, cvar_beta=0.95, evar_beta=0.95, drawdown_at_risk_beta=0.95, cdar_beta=0.95, edar_beta=0.95)[source]#

Portfolio object returned when an optimization step fails. It acts as a sentinel value that marks the failure and stores failure diagnostics (optimization_error, fallback_chain).

FailedPortfolio preserves full API compatibility with Portfolio so it can seamlessly pass through risk measures, aggregation, rolling computations and plotting without raising. All returns, weights, composition, and derived measures are NaN.

Note

In backtesting workflows, when an optimization estimator is configured with raise_on_failure=False, a FailedPortfolio is returned on failed rebalancings. This lets the process complete without raising while preserving the full timeline for downstream analysis and diagnostics.

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

Price returns of the assets. If X is a DataFrame, the columns will be considered as assets names and the indices will be considered as observations. Otherwise, we use ["x0", "x1", ..., "x(n_assets - 1)"] as asset names and [0, 1, ..., n_observations] as observations.

optimization_errorstr, optional

Stringified error message explaining why the optimization failed. Propagated from the optimization estimator when raise_on_failure=False. None means the reason is unknown or not provided.

namestr, optional

Name of the portfolio. The default (None) is to use the object id.

tagstr, optional

Tag given to the portfolio. Tags are used to manipulate groups of Portfolios from a Population.

fallback_chainlist[tuple[str, str]] | None, optional

Sequence describing the optimization fallback attempts. Each element is a pair (estimator_repr, outcome) where:

  • estimator_repr is the string representation of the primary estimator or a fallback (e.g. "EqualWeighted()", "previous_weights").

  • outcome is "success" if that step produced a valid solution, otherwise the stringified error message.

For successful fits without any fallback, this is None. When fallbacks are provided and the primary fails, the chain starts with (primary_repr, primary_error) and is followed by one entry per fallback that was attempted, ending with the first "success" or the last error if all fail. This is set by the optimization estimator and propagated to the resulting portfolio objects (including FailedPortfolio).

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

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

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

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

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

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

risk_free_ratefloat, default=0.0

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

annualized_factorfloat, default=252.0

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

fitness_measureslist[measures], optional

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

compoundedbool, default=False

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

sample_weightndarray of shape (n_observations, ), optional

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

min_acceptable_returnfloat | None, optional

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

value_at_risk_betafloat, default=0.95

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

entropic_risk_measure_thetafloat, default=1.0

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

entropic_risk_measure_betafloat, default=0.95

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

cvar_betafloat, default=0.95

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

evar_betafloat, default=0.95

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

drawdown_at_risk_betafloat, default=0.95

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

cdar_betafloat, default=0.95

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

edar_betafloat, default=0.95

Accepted for API compatibility with Portfolio but not used by FailedPortfolio.

Attributes:
X
annualized_factor

Portfolio annualized factor.

annualized_mean
annualized_semi_deviation
annualized_semi_variance
annualized_sharpe_ratio
annualized_sortino_ratio
annualized_standard_deviation
annualized_variance
assets
average_drawdown
average_drawdown_ratio
calmar_ratio
cdar
cdar_beta
cdar_ratio
composition

DataFrame of portfolio composition (weights).

compounded
cumulative_returns

Portfolio cumulative returns array. Non-compounded (arithmetic) cumulative returns start at 0. Compounded (geometric) cumulative returns are expressed as a wealth index, starting at 1.0 (i.e., the value of $1 invested).

cumulative_returns_df

Portfolio cumulative returns Series.

cvar
cvar_beta
cvar_ratio
diversification

Weighted average of volatility divided by the portfolio volatility.

drawdown_at_risk
drawdown_at_risk_beta
drawdown_at_risk_ratio
drawdowns

Portfolio drawdowns array.

drawdowns_df

Portfolio drawdowns Series.

edar
edar_beta
edar_ratio
effective_number_assets

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

entropic_risk_measure
entropic_risk_measure_beta
entropic_risk_measure_ratio
entropic_risk_measure_theta
evar
evar_beta
evar_ratio
fallback_chain
first_lower_partial_moment
first_lower_partial_moment_ratio
fitness

Portfolio fitness.

fitness_measures

Portfolio fitness measures.

fourth_central_moment
fourth_lower_partial_moment
gini_mean_difference
gini_mean_difference_ratio
kurtosis
management_fees
max_drawdown
mean
mean_absolute_deviation
mean_absolute_deviation_ratio
measures_df

DataFrame of all measures.

min_acceptable_return
n_assets
n_observations

Number of observations.

name
nonzero_assets

Invested asset \(abs(weights) > 0.001%\).

nonzero_assets_index

Indices of invested asset \(abs(weights) > 0.001%\).

observations
optimization_error
previous_weights
previous_weights_dict

Dict mapping asset name to previous weight; includes zeros.

returns
returns_df

Portfolio returns DataFrame.

risk_free_rate
sample_weight

Observations sample weights.

semi_deviation
semi_variance
sharpe_ratio
skew
sortino_ratio
sric

Sharpe Ratio Information Criterion (SRIC).

standard_deviation
tag
total_cost
total_fee
transaction_costs
ulcer_index
ulcer_index_ratio
value_at_risk
value_at_risk_beta
value_at_risk_ratio
variance
weights
weights_dict

Dict mapping asset name to weight; includes zeros.

weights_per_observation

DataFrame of the Portfolio weights per observation.

worst_realization
worst_realization_ratio

Methods

clear()

Clear all measures, fitness, cumulative returns and drawdowns in slots.

contribution(measure[, spacing, to_df])

Compute the contribution of each asset to a given measure.

copy()

Copy the Portfolio attributes without its measures values.

dominates(other[, idx])

Portfolio domination.

expected_returns_from_assets(...)

Compute the Portfolio expected returns from the assets expected returns, weights, management costs and transaction fees.

get_measure(measure)

Returns the value of a given measure.

get_weight(asset)

Get the weight of a given asset.

plot_composition()

Plot the Portfolio composition.

plot_contribution(measure[, spacing])

Plot the contribution of each asset to a given measure.

plot_cumulative_returns([log_scale, idx])

Plot the Portfolio cumulative returns.

plot_drawdowns([idx])

Plot the Portfolio drawdowns.

plot_returns([idx])

Plot the Portfolio returns.

plot_returns_distribution([percentile_cutoff])

Plot the Portfolio returns distribution using Gaussian KDE.

plot_rolling_measure([measure, window])

Plot the measure over a rolling window.

rolling_measure([measure, window])

Compute the measure over a rolling window.

summary([formatted])

Portfolio summary of all its measures.

variance_from_assets(assets_covariance)

Compute the Portfolio variance expectation from the assets covariance and weights.

Notes

All performance, risk, and contribution measures are computed from NaN returns and NaN weights in a FailedPortfolio. As a result, these parameters do not affect the outcome: NaNs are carried over to metrics, contributions, plots, and rolling computations. This class exists solely to preserve API and type compatibility while signaling a failed optimization.

property annualized_factor#

Portfolio annualized factor.

clear()#

Clear all measures, fitness, cumulative returns and drawdowns in slots.

property composition#

DataFrame of portfolio composition (weights). Rows with zero weights are filtered out. Use weights_dict to access all weights, including zeros.

contribution(measure, spacing=None, to_df=False)#

Compute the contribution of each asset to a given measure.

Parameters:
measureMeasure

The measure used for the contribution computation.

spacingfloat, optional

Spacing “h” of the finite difference: \(contribution(wi)= \frac{measure(wi-h) - measure(wi+h)}{2h}\)

to_dfbool, default=False

If set to True, a DataFrame with asset names in index is returned, otherwise a numpy array is returned. When a DataFrame is returned, the values are sorted in descending order and assets with zero weights are removed.

Returns:
valuesnumpy array of shape (n_assets,) or DataFrame

The measure contribution of each asset.

copy()#

Copy the Portfolio attributes without its measures values.

cumulative_returns#

Portfolio cumulative returns array. Non-compounded (arithmetic) cumulative returns start at 0. Compounded (geometric) cumulative returns are expressed as a wealth index, starting at 1.0 (i.e., the value of $1 invested).

property cumulative_returns_df#

Portfolio cumulative returns Series. Non-compounded (arithmetic) cumulative returns start at 0. Compounded (geometric) cumulative returns are expressed as a wealth index, starting at 1.0 (i.e., the value of $1 invested).

property diversification#

Weighted average of volatility divided by the portfolio volatility.

dominates(other, idx=None)#

Portfolio domination.

Returns true if each objective of the current portfolio fitness is not strictly worse than the corresponding objective of the other portfolio fitness and at least one objective is strictly better.

Parameters:
otherBasePortfolio

The other portfolio.

idxslice | array, optional

Indexes or slice indicating on which objectives the domination is performed. The default (None) is to use all objectives.

Returns:
valuebool

Returns True if the Portfolio dominates the other one.

drawdowns#

Portfolio drawdowns array.

property drawdowns_df#

Portfolio drawdowns Series.

property effective_number_assets#

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

\[N_{eff} = \frac{1}{\Vert w \Vert_{2}^{2}}\]

It quantifies portfolio concentration, with a higher value indicating a more diversified portfolio.

Returns:
valuefloat

Effective number of assets.

References

[1]

“Banking and Financial Institutions Law in a Nutshell”. Lovett, William Anthony (1988)

expected_returns_from_assets(assets_expected_returns)#

Compute the Portfolio expected returns from the assets expected returns, weights, management costs and transaction fees.

Parameters:
assets_expected_returnsndarray of shape (n_assets,)

The vector of assets expected returns.

Returns:
valuefloat

The Portfolio expected returns.

fitness#

Portfolio fitness.

property fitness_measures#

Portfolio fitness measures.

get_measure(measure)#

Returns the value of a given measure.

Parameters:
measurePerfMeasure | RiskMeasure | ExtraRiskMeasure | RatioMeasure

The input measure.

Returns:
valuefloat

The measure value.

get_weight(asset)#

Get the weight of a given asset.

Parameters:
assetstr

Name of the asset.

Returns:
weightfloat

Weight of the asset.

property measures_df#

DataFrame of all measures.

property n_observations#

Number of observations.

nonzero_assets#

Invested asset \(abs(weights) > 0.001%\).

nonzero_assets_index#

Indices of invested asset \(abs(weights) > 0.001%\).

plot_composition()#

Plot the Portfolio composition.

Returns:
plotFigure

Returns the plot Figure object.

plot_contribution(measure, spacing=None)#

Plot the contribution of each asset to a given measure.

Parameters:
measureMeasure

The measure used for the contribution computation.

spacingfloat, optional

Spacing “h” of the finite difference: \(contribution(wi)= \frac{measure(wi-h) - measure(wi+h)}{2h}\)

Returns:
plotFigure

The plotly Figure of assets contribution to the measure.

plot_cumulative_returns(log_scale=False, idx=None)#

Plot the Portfolio cumulative returns. Non-compounded (arithmetic) cumulative returns start at 0. Compounded (geometric) cumulative returns are expressed as a wealth index, starting at 1.0 (i.e., the value of $1 invested).

Parameters:
log_scalebool, default=False

If this is set to True, the cumulative returns are displayed with a logarithm scale on the y-axis. The cumulative returns must be compounded otherwise an exception is raised.

idxslice | array, optional

Indexes or slice of the observations to plot. The default (None) is to plot all observations.

Returns:
plotFigure

Returns the plot Figure object.

plot_drawdowns(idx=None)#

Plot the Portfolio drawdowns.

Parameters:
idxslice | array, optional

Indexes or slice of the observations to plot. The default (None) is to plot all observations.

Returns:
plotFigure

Returns the plot Figure object.

plot_returns(idx=None)#

Plot the Portfolio returns.

Parameters:
idxslice | array, optional

Indexes or slice of the observations to plot. The default (None) is to plot all observations.

Returns:
plotFigure

Returns the plot Figure object

plot_returns_distribution(percentile_cutoff=None)#

Plot the Portfolio returns distribution using Gaussian KDE.

Parameters:
percentile_cutofffloat, default=None

Percentile cutoff for tail truncation (percentile), in percent. If a float p is provided, the distribution support is truncated at the p-th and (100 - p)-th percentiles. If None, no truncation is applied (uses full min/max of returns).

Returns:
plotFigure

Returns the plot Figure object

plot_rolling_measure(measure=Sharpe Ratio, window=30)#

Plot the measure over a rolling window.

Parameters:
measurect.Measure, default = RatioMeasure.SHARPE_RATIO

The measure.

windowint, default=30

The window size.

Returns:
plotFigure

Returns the plot Figure object

property previous_weights_dict#

Dict mapping asset name to previous weight; includes zeros.

property returns_df#

Portfolio returns DataFrame.

rolling_measure(measure=Sharpe Ratio, window=30)#

Compute the measure over a rolling window.

Parameters:
measurect.Measure, default=RatioMeasure.SHARPE_RATIO

The measure. The default measure is the Sharpe Ratio.

windowint, default=30

The window size. The default value is 30 observations.

Returns:
seriespandas Series

The rolling measure Series.

property sample_weight#

Observations sample weights.

property sric#

Sharpe Ratio Information Criterion (SRIC).

It is an unbiased estimator of the Sharpe Ratio adjusting for both sources of bias which are noise fit and estimation error [1].

References

[1]

“Noise Fit, Estimation Error and a Sharpe Information Criterion”, Dirk Paulsen (2019)

summary(formatted=True)#

Portfolio summary of all its measures.

Parameters:
formattedbool, default=True

If this is set to True, the measures are formatted into rounded string with units.

Returns:
summaryseries

Portfolio summary.

variance_from_assets(assets_covariance)#

Compute the Portfolio variance expectation from the assets covariance and weights.

Parameters:
assets_covariancendarray of shape (n_assets,n_assets)

The matrix of assets covariance expectation.

Returns:
valuefloat

The Portfolio variance from the assets covariance.

property weights_dict#

Dict mapping asset name to weight; includes zeros.

property weights_per_observation#

DataFrame of the Portfolio weights per observation.