<a id="skfolio-portfolio-failedportfolio"></a>

# skfolio.portfolio.FailedPortfolio

<a id="skfolio.portfolio.FailedPortfolio"></a>

### *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, annualization_factor=None, fitness_measures=None, compounded=False, weight_drift=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, \*\*kwargs)

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.

In a sequential evaluation, a failed period contributes no returns and no
holdings. The last successful holdings are kept unchanged and supplied as
`previous_weights` to the next fit.

* **Parameters:**
  **X** *array-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_error** *str, 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.

  **name** *str, optional*
  : Name of the portfolio. The default (`None`) is to use the object id.

  **tag** *str, optional*
  : Tag given to the portfolio. Tags are used to manipulate groups of
    Portfolios from a `Population`.

  **fallback_chain** *list[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.
    <br/>
    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_weights** *float | dict[str, float] | array-like of shape (n_assets, ), optional*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **transaction_costs** *float | dict[str, float] | array-like of shape (n_assets, ), optional*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **management_fees** *float | dict[str, float] | array-like of shape (n_assets, ), optional*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **risk_free_rate** *float, default=0.0*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **annualization_factor** *float, default=252.0*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **fitness_measures** *list[measures], optional*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **compounded** *bool, default=False*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **weight_drift** *bool, default=False*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **sample_weight** *ndarray of shape (n_observations, ), optional*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **min_acceptable_return** *float | None, optional*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **value_at_risk_beta** *float, default=0.95*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **entropic_risk_measure_theta** *float, default=1.0*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **entropic_risk_measure_beta** *float, default=0.95*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **cvar_beta** *float, default=0.95*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **evar_beta** *float, default=0.95*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **drawdown_at_risk_beta** *float, default=0.95*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **cdar_beta** *float, default=0.95*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.

  **edar_beta** *float, default=0.95*
  : Accepted for API compatibility with `Portfolio` but not used by
    `FailedPortfolio`.
* **Attributes:**
  **X**

  [`annualization_factor`](#skfolio.portfolio.FailedPortfolio.annualization_factor)
  : Portfolio annualization factor.

  [`annualized_factor`](#skfolio.portfolio.FailedPortfolio.annualized_factor)
  : Deprecated alias for `annualization_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`](#skfolio.portfolio.FailedPortfolio.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`](#skfolio.portfolio.FailedPortfolio.cumulative_returns_df)
  : Portfolio cumulative returns Series.

  **cvar**

  **cvar_beta**

  **cvar_ratio**

  [`diversification`](#skfolio.portfolio.FailedPortfolio.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`](#skfolio.portfolio.FailedPortfolio.drawdowns_df)
  : Portfolio drawdowns Series.

  **edar**

  **edar_beta**

  **edar_ratio**

  [`effective_number_assets`](#skfolio.portfolio.FailedPortfolio.effective_number_assets)
  : Computes the effective number of assets, defined as the inverse of the Herfindahl index.

  **ending_weights**

  [`ending_weights_dict`](#skfolio.portfolio.FailedPortfolio.ending_weights_dict)
  : Dict mapping asset name to ending weight; includes zeros.

  **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`](#skfolio.portfolio.FailedPortfolio.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`](#skfolio.portfolio.FailedPortfolio.measures_df)
  : DataFrame of all measures.

  **min_acceptable_return**

  **n_assets**

  [`n_observations`](#skfolio.portfolio.FailedPortfolio.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`](#skfolio.portfolio.FailedPortfolio.previous_weights_dict)
  : Dict mapping asset name to previous weight; includes zeros.

  **returns**

  [`returns_df`](#skfolio.portfolio.FailedPortfolio.returns_df)
  : Portfolio returns DataFrame.

  **risk_free_rate**

  [`sample_weight`](#skfolio.portfolio.FailedPortfolio.sample_weight)
  : Observations sample weights.

  **semi_deviation**

  **semi_variance**

  **sharpe_ratio**

  **skew**

  **sortino_ratio**

  [`sric`](#skfolio.portfolio.FailedPortfolio.sric)
  : Sharpe Ratio Information Criterion (SRIC).

  **standard_deviation**

  **tag**

  **total_cost**

  **total_fee**

  **transaction_costs**

  [`turnover`](#skfolio.portfolio.FailedPortfolio.turnover)
  : Total absolute weight traded at the start of the period.

  **ulcer_index**

  **ulcer_index_ratio**

  **value_at_risk**

  **value_at_risk_beta**

  **value_at_risk_ratio**

  **variance**

  **weight_drift**

  **weights**

  [`weights_dict`](#skfolio.portfolio.FailedPortfolio.weights_dict)
  : Dict mapping asset name to weight; includes zeros.

  [`weights_per_observation`](#skfolio.portfolio.FailedPortfolio.weights_per_observation)
  : DataFrame of asset weights at the start of each observation.

  **worst_realization**

  **worst_realization_ratio**

### Methods

| [`clear`](#skfolio.portfolio.FailedPortfolio.clear)()                                           | Clear all measures, fitness, cumulative returns and drawdowns in slots.                                            |
|----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|
| [`contribution`](#skfolio.portfolio.FailedPortfolio.contribution)(measure[, spacing, to_df])           | Compute the contribution of each asset to a given measure.                                                         |
| [`copy`](#skfolio.portfolio.FailedPortfolio.copy)()                                            | Copy the Portfolio attributes without its measures values.                                                         |
| [`dominates`](#skfolio.portfolio.FailedPortfolio.dominates)(other[, idx])                           | Portfolio domination.                                                                                              |
| [`expected_returns_from_assets`](#skfolio.portfolio.FailedPortfolio.expected_returns_from_assets)(...)                 | Compute the portfolio expected return from expected asset returns, weights, management costs and transaction fees. |
| [`get_measure`](#skfolio.portfolio.FailedPortfolio.get_measure)(measure)                              | Returns the value of a given measure.                                                                              |
| [`get_weight`](#skfolio.portfolio.FailedPortfolio.get_weight)(asset)                                 | Get the weight of a given asset.                                                                                   |
| [`plot_composition`](#skfolio.portfolio.FailedPortfolio.plot_composition)()                                | Plot the Portfolio composition.                                                                                    |
| [`plot_contribution`](#skfolio.portfolio.FailedPortfolio.plot_contribution)(measure[, spacing])             | Plot the contribution of each asset to a given measure.                                                            |
| [`plot_cumulative_returns`](#skfolio.portfolio.FailedPortfolio.plot_cumulative_returns)([log_scale, idx])         | Plot the Portfolio cumulative returns.                                                                             |
| [`plot_drawdowns`](#skfolio.portfolio.FailedPortfolio.plot_drawdowns)([idx])                             | Plot the Portfolio drawdowns.                                                                                      |
| [`plot_returns`](#skfolio.portfolio.FailedPortfolio.plot_returns)([idx])                               | Plot the Portfolio returns.                                                                                        |
| [`plot_returns_distribution`](#skfolio.portfolio.FailedPortfolio.plot_returns_distribution)([percentile_cutoff])    | Plot the Portfolio returns distribution using Gaussian KDE.                                                        |
| [`plot_rolling_measure`](#skfolio.portfolio.FailedPortfolio.plot_rolling_measure)([measure, window])           | Plot the measure over a rolling window.                                                                            |
| [`predicted_attribution`](#skfolio.portfolio.FailedPortfolio.predicted_attribution)(factor_model[, ...])        | Ex-ante (predicted) factor risk and performance attribution.                                                       |
| [`realized_attribution`](#skfolio.portfolio.FailedPortfolio.realized_attribution)(factor_model[, ...])         | Realized (ex-post) factor risk and performance attribution.                                                        |
| [`rolling_measure`](#skfolio.portfolio.FailedPortfolio.rolling_measure)([measure, window])                | Compute the measure over a rolling window.                                                                         |
| [`rolling_realized_attribution`](#skfolio.portfolio.FailedPortfolio.rolling_realized_attribution)(factor_model[, ...]) | Rolling realized (ex-post) factor risk and performance attribution.                                                |
| [`summary`](#skfolio.portfolio.FailedPortfolio.summary)([formatted])                              | Portfolio summary of all its measures.                                                                             |
| [`variance_from_assets`](#skfolio.portfolio.FailedPortfolio.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.

<a id="skfolio.portfolio.FailedPortfolio.annualization_factor"></a>

#### *property* annualization_factor

Portfolio annualization factor.

<a id="skfolio.portfolio.FailedPortfolio.annualized_factor"></a>

#### *property* annualized_factor

Deprecated alias for `annualization_factor`.

<a id="skfolio.portfolio.FailedPortfolio.clear"></a>

#### clear()

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

<a id="skfolio.portfolio.FailedPortfolio.composition"></a>

#### *property* composition

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

<a id="skfolio.portfolio.FailedPortfolio.contribution"></a>

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

Compute the contribution of each asset to a given measure.

With `weight_drift=True`, the contributions are finite-difference sensitivities
to the target weights. Because drifted returns are nonlinear in the target
weights, the contributions are not guaranteed to sum exactly to the measure.

* **Parameters:**
  **measure** *Measure*
  : The measure used for the contribution computation.

  **spacing** *float, optional*
  : Spacing “h” of the finite difference:
    $contribution(wi)= \frac{measure(wi-h) - measure(wi+h)}{2h}$

  **to_df** *bool, 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:**
  **values** *numpy array of shape (n_assets,) or DataFrame*
  : The measure contribution of each asset.

<a id="skfolio.portfolio.FailedPortfolio.copy"></a>

#### copy()

Copy the Portfolio attributes without its measures values.

<a id="skfolio.portfolio.FailedPortfolio.cumulative_returns"></a>

#### 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).

<a id="skfolio.portfolio.FailedPortfolio.cumulative_returns_df"></a>

#### *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).

<a id="skfolio.portfolio.FailedPortfolio.diversification"></a>

#### *property* diversification

Weighted average of volatility divided by the portfolio volatility.

<a id="skfolio.portfolio.FailedPortfolio.dominates"></a>

#### 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:**
  **other** *BasePortfolio*
  : The other portfolio.

  **idx** *slice | array, optional*
  : Indexes or slice indicating on which objectives the domination is performed.
    The default (`None`) is to use all objectives.
* **Returns:**
  **value** *bool*
  : Returns True if the Portfolio dominates the other one.

<a id="skfolio.portfolio.FailedPortfolio.drawdowns"></a>

#### drawdowns

Portfolio drawdowns array.

<a id="skfolio.portfolio.FailedPortfolio.drawdowns_df"></a>

#### *property* drawdowns_df

Portfolio drawdowns Series.

<a id="skfolio.portfolio.FailedPortfolio.effective_number_assets"></a>

#### *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:**
  **value** *float*
  : Effective number of assets.

### References

* <a id='r5e81914d8cb5-1'>**[1]**</a> “Banking and Financial Institutions Law in a Nutshell”. Lovett, William Anthony (1988)

<a id="skfolio.portfolio.FailedPortfolio.ending_weights_dict"></a>

#### *property* ending_weights_dict

Dict mapping asset name to ending weight; includes zeros.

<a id="skfolio.portfolio.FailedPortfolio.expected_returns_from_assets"></a>

#### expected_returns_from_assets(assets_expected_returns)

Compute the portfolio expected return from expected asset returns,
weights, management costs and transaction fees.

* **Parameters:**
  **assets_expected_returns** *ndarray of shape (n_assets,)*
  : The vector of expected asset returns.
* **Returns:**
  **value** *float*
  : The portfolio expected return.

<a id="skfolio.portfolio.FailedPortfolio.fitness"></a>

#### fitness

Portfolio fitness.

<a id="skfolio.portfolio.FailedPortfolio.fitness_measures"></a>

#### *property* fitness_measures

Portfolio fitness measures.

<a id="skfolio.portfolio.FailedPortfolio.get_measure"></a>

#### get_measure(measure)

Returns the value of a given measure.

* **Parameters:**
  **measure** *PerfMeasure | RiskMeasure | ExtraRiskMeasure | RatioMeasure*
  : The input measure.
* **Returns:**
  **value** *float*
  : The measure value.

<a id="skfolio.portfolio.FailedPortfolio.get_weight"></a>

#### get_weight(asset)

Get the weight of a given asset.

* **Parameters:**
  **asset** *str*
  : Name of the asset.
* **Returns:**
  **weight** *float*
  : Weight of the asset.

<a id="skfolio.portfolio.FailedPortfolio.measures_df"></a>

#### *property* measures_df

DataFrame of all measures.

<a id="skfolio.portfolio.FailedPortfolio.n_observations"></a>

#### *property* n_observations

Number of observations.

<a id="skfolio.portfolio.FailedPortfolio.nonzero_assets"></a>

#### nonzero_assets

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

<a id="skfolio.portfolio.FailedPortfolio.nonzero_assets_index"></a>

#### nonzero_assets_index

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

<a id="skfolio.portfolio.FailedPortfolio.plot_composition"></a>

#### plot_composition()

Plot the Portfolio composition.

* **Returns:**
  **plot** *Figure*
  : Returns the plot Figure object.

<a id="skfolio.portfolio.FailedPortfolio.plot_contribution"></a>

#### plot_contribution(measure, spacing=None)

Plot the contribution of each asset to a given measure.

* **Parameters:**
  **measure** *Measure*
  : The measure used for the contribution computation.

  **spacing** *float, optional*
  : Spacing “h” of the finite difference:
    $contribution(wi)= \frac{measure(wi-h) - measure(wi+h)}{2h}$
* **Returns:**
  **plot** *Figure*
  : The plotly Figure of assets contribution to the measure.

<a id="skfolio.portfolio.FailedPortfolio.plot_cumulative_returns"></a>

#### 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_scale** *bool, 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.

  **idx** *slice | array, optional*
  : Indexes or slice of the observations to plot.
    The default (`None`) is to plot all observations.
* **Returns:**
  **plot** *Figure*
  : Returns the plot Figure object.

<a id="skfolio.portfolio.FailedPortfolio.plot_drawdowns"></a>

#### plot_drawdowns(idx=None)

Plot the Portfolio drawdowns.

* **Parameters:**
  **idx** *slice | array, optional*
  : Indexes or slice of the observations to plot.
    The default (`None`) is to plot all observations.
* **Returns:**
  **plot** *Figure*
  : Returns the plot Figure object.

<a id="skfolio.portfolio.FailedPortfolio.plot_returns"></a>

#### plot_returns(idx=None)

Plot the Portfolio returns.

* **Parameters:**
  **idx** *slice | array, optional*
  : Indexes or slice of the observations to plot.
    The default (`None`) is to plot all observations.
* **Returns:**
  **plot** *Figure*
  : Returns the plot Figure object

<a id="skfolio.portfolio.FailedPortfolio.plot_returns_distribution"></a>

#### plot_returns_distribution(percentile_cutoff=None)

Plot the Portfolio returns distribution using Gaussian KDE.

* **Parameters:**
  **percentile_cutoff** *float, 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:**
  **plot** *Figure*
  : Returns the plot Figure object

<a id="skfolio.portfolio.FailedPortfolio.plot_rolling_measure"></a>

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

Plot the measure over a rolling window.

* **Parameters:**
  **measure** *Measure, default = RatioMeasure.SHARPE_RATIO*
  : The measure.

  **window** *int, default=30*
  : The window size.
* **Returns:**
  **plot** *Figure*
  : Returns the plot Figure object

<a id="skfolio.portfolio.FailedPortfolio.predicted_attribution"></a>

#### predicted_attribution(factor_model, compute_asset_breakdowns=True)

Ex-ante (predicted) factor risk and performance attribution.

Decomposes the portfolio’s predicted risk and expected return into contributions
from individual factors and an idiosyncratic component using the factor model’s
latest forecast estimates (`loading_matrix`, `factor_covariance`,
`idio_covariance`, `factor_mu`, `idio_mu`).

The annualization scaling uses `self.annualization_factor`.

Predicted attribution uses only these latest forecast estimates, so no
observation alignment is required. The `factor_model` may therefore cover a
different observation window than the portfolio.

The portfolio may hold a subset of the assets covered by the factor model and
weights are zero-filled for missing assets.

See [`predicted_factor_attribution`](https://skfolio.org/generated/skfolio.attribution.predicted_factor_attribution.html.md#skfolio.attribution.predicted_factor_attribution)
for the full mathematical description.

* **Parameters:**
  **factor_model** *FactorModel*
  : Factor model whose latest forecast estimates are used. Every asset in
    `self.assets` must appear in `factor_model.asset_names`.

  **compute_asset_breakdowns** *bool, default=True*
  : If `True`, compute per-asset systematic/idiosyncratic decomposition. Set to
    `False` for faster computation when only portfolio-level results are needed.
* **Returns:**
  **attribution** *Attribution*
  : Component-level, factor-level, and optionally asset-level attribution
    results.
* **Raises:**
  ValueError
  : If the portfolio is a failed portfolio or if it holds assets not covered by
    the factor model.

<a id="skfolio.portfolio.FailedPortfolio.previous_weights_dict"></a>

#### *property* previous_weights_dict

Dict mapping asset name to previous weight; includes zeros.

<a id="skfolio.portfolio.FailedPortfolio.realized_attribution"></a>

#### realized_attribution(factor_model, compute_asset_breakdowns=True, compute_uncertainty=True)

Realized (ex-post) factor risk and performance attribution.

Decomposes the portfolio’s realized risk and return into contributions from
individual factors and an idiosyncratic component using actual historical factor
returns, exposures, and residuals.

The annualization scaling uses `self.annualization_factor`.

Realized attribution uses the target weights when `weight_drift=False` and the
weights held during each observation when `weight_drift=True`.

Realized attribution is computed on the overlapping observation window between
the portfolio and the factor model. Portfolio observations outside the factor
model window, commonly caused by factor-model warmup or exposure lag, are
excluded. Missing portfolio observations inside the overlapping window raise
`ValueError`. Time-varying exposures follow the as-of indexing convention
described in
[`realized_factor_attribution`](https://skfolio.org/generated/skfolio.attribution.realized_factor_attribution.html.md#skfolio.attribution.realized_factor_attribution):
when `exposure_lag > 0`, exposures known at observation
$t-\ell$ are aligned with returns at observation $t$.

The portfolio may hold a subset of the assets covered by the factor model and
weights are zero-filled for missing assets.

See [`realized_factor_attribution`](https://skfolio.org/generated/skfolio.attribution.realized_factor_attribution.html.md#skfolio.attribution.realized_factor_attribution)
for the full mathematical description.

* **Parameters:**
  **factor_model** *FactorModel*
  : Factor model containing time-varying fields (`factor_returns`, `exposures`,
    `idio_returns`) that overlap with the portfolio’s observation period. Every
    asset in `self.assets` must appear in `factor_model.asset_names`.

  **compute_asset_breakdowns** *bool, default=True*
  : If `True`, compute per-asset systematic/idiosyncratic attribution. Set to
    `False` for faster computation when only portfolio-level results are needed.

  **compute_uncertainty** *bool, default=True*
  : If `True`, compute attribution uncertainty (standard errors on the factor
    and idiosyncratic mean-return split).
* **Returns:**
  **attribution** *Attribution*
  : Component-level, factor-level, and optionally asset-level attribution
    results.
* **Raises:**
  ValueError
  : If the portfolio is a failed portfolio, if it holds assets not covered by
    the factor model, if no portfolio observations overlap with the factor model
    or if portfolio observations are missing inside the overlapping window.

<a id="skfolio.portfolio.FailedPortfolio.returns_df"></a>

#### *property* returns_df

Portfolio returns DataFrame.

<a id="skfolio.portfolio.FailedPortfolio.rolling_measure"></a>

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

Compute the measure over a rolling window.

* **Parameters:**
  **measure** *Measure, default=RatioMeasure.SHARPE_RATIO*
  : The measure. The default measure is the Sharpe Ratio.

  **window** *int, default=30*
  : The window size. The default value is `30` observations.
* **Returns:**
  **series** *pandas Series*
  : The rolling measure Series.

<a id="skfolio.portfolio.FailedPortfolio.rolling_realized_attribution"></a>

#### rolling_realized_attribution(factor_model, window_size=60, step=21, compute_asset_breakdowns=True, compute_asset_factor_contribs=False, compute_uncertainty=True)

Rolling realized (ex-post) factor risk and performance attribution.

Computes [`realized_factor_attribution`](https://skfolio.org/generated/skfolio.attribution.realized_factor_attribution.html.md#skfolio.attribution.realized_factor_attribution)
over rolling windows, returning an [`Attribution`](https://skfolio.org/generated/skfolio.attribution.Attribution.html.md#skfolio.attribution.Attribution)
where all numeric fields carry an additional leading dimension for the number
of windows.

Rolling realized attribution is computed on the overlapping observation window
between the portfolio and the factor model. Portfolio observations outside the
factor model window, commonly caused by factor-model warmup or exposure lag, are
excluded. Missing portfolio observations inside the overlapping window raise
`ValueError`. Time-varying exposures follow the as-of indexing convention
described in
[`rolling_realized_factor_attribution`](https://skfolio.org/generated/skfolio.attribution.rolling_realized_factor_attribution.html.md#skfolio.attribution.rolling_realized_factor_attribution).

Each rolling window uses the target weights when `weight_drift=False` and the
weights held during its observations when `weight_drift=True`.

The portfolio may hold a subset of the assets covered by the factor model and
weights are zero-filled for missing assets.

See [`rolling_realized_factor_attribution`](https://skfolio.org/generated/skfolio.attribution.rolling_realized_factor_attribution.html.md#skfolio.attribution.rolling_realized_factor_attribution)
for the full mathematical description.

* **Parameters:**
  **factor_model** *FactorModel*
  : Factor model containing time-varying fields that overlap with the
    portfolio’s observation period.

  **window_size** *int, default=60*
  : Number of effective return periods in each rolling window.

  **step** *int, default=21*
  : Number of observations to advance between consecutive windows. The default
    of 21 produces approximately monthly output for daily data.

  **compute_asset_breakdowns** *bool, default=True*
  : If `True`, compute per-asset attribution for each window.

  **compute_asset_factor_contribs** *bool, default=False*
  : If `True`, compute asset-factor matrix for each window.

  **compute_uncertainty** *bool, default=True*
  : If `True`, compute per-window attribution uncertainty.
* **Returns:**
  **attribution** *Attribution*
  : Rolling attribution results.
* **Raises:**
  ValueError
  : If the portfolio is a failed portfolio, if it holds assets not covered by
    the factor model, if no portfolio observations overlap with the factor model
    or if `window_size` exceeds the number of overlapping observations.

<a id="skfolio.portfolio.FailedPortfolio.sample_weight"></a>

#### *property* sample_weight

Observations sample weights.

<a id="skfolio.portfolio.FailedPortfolio.sric"></a>

#### *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]](#r9dee37131fea-1).

### References

* <a id='r9dee37131fea-1'>**[1]**</a> “Noise Fit, Estimation Error and a Sharpe Information Criterion”, Dirk Paulsen (2019)

<a id="skfolio.portfolio.FailedPortfolio.summary"></a>

#### summary(formatted=True)

Portfolio summary of all its measures.

* **Parameters:**
  **formatted** *bool, default=True*
  : If this is set to True, the measures are formatted into rounded string
    with units.
* **Returns:**
  **summary** *series*
  : Portfolio summary.

<a id="skfolio.portfolio.FailedPortfolio.turnover"></a>

#### *property* turnover

Total absolute weight traded at the start of the period.

In a sequential evaluation, `previous_weights` come from the last successful
Portfolio. With `weight_drift=False`, target turnover compares successive
target allocations. With `weight_drift=True`, executed turnover compares the
previous period’s ending weights with the new target allocation. When
`previous_weights` is None, it defaults to zero. Turnover includes the full
absolute weight of positions in assets absent from `X`.

<a id="skfolio.portfolio.FailedPortfolio.variance_from_assets"></a>

#### variance_from_assets(assets_covariance)

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

* **Parameters:**
  **assets_covariance** *ndarray of shape (n_assets,n_assets)*
  : The matrix of assets covariance expectation.
* **Returns:**
  **value** *float*
  : The Portfolio variance from the assets covariance.

<a id="skfolio.portfolio.FailedPortfolio.weights_dict"></a>

#### *property* weights_dict

Dict mapping asset name to weight; includes zeros.

<a id="skfolio.portfolio.FailedPortfolio.weights_per_observation"></a>

#### *property* weights_per_observation

DataFrame of asset weights at the start of each observation.

With `weight_drift=False`, every row contains the target `weights`. With
`weight_drift=True`, each row incorporates the effect of preceding asset
returns. `ending_weights` contains the weights immediately after the final
observation.

