> ## Documentation Index
> Fetch the complete documentation index at: https://systematica.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Metrics

> systematica.portfolio.metrics

## Variables

* `run_from_portfolio_metric: systematica.portfolio.metrics.PortfolioMetric`: Initiated portfolio metric class with default metric config.

## `check_metrics`

```python theme={null}
check_metrics(
    metrics: str | List[str],
)
```

Validate metrics.

**Parameters**:

| Name      | Type  | Default | Description                           |
| --------- | ----- | ------- | ------------------------------------- |
| `metrics` | `str` | `--`    | \| tp.List\[str] Performance metrics. |

**Raises**:

| Type         | Description                                           |
| ------------ | ----------------------------------------------------- |
| `TypeError`  | If metrics is not a string or list.                   |
| `ValueError` | If metric has not been configured and is not tunable. |
| `ValueError` | If mixing tunable and non-tunable metrics.            |

## `get_total_returns_nb`

```python theme={null}
get_total_returns_nb(
    close: numpy.ndarray,
    sim_out: vectorbtpro.portfolio.enums.SimulationOutput,
)
```

Calculate the total returns.

**Parameters**:

| Name      | Type                | Default | Description                                 |
| --------- | ------------------- | ------- | ------------------------------------------- |
| `close`   | `tp.Array2d`        | `--`    | Array of close prices.                      |
| `sim_out` | `SimulationOutputT` | `--`    | Simulation output containing order records. |

**Returns**:

| Type    | Description    |
| ------- | -------------- |
| `float` | Total returns. |

## `get_expectancy_nb`

```python theme={null}
get_expectancy_nb(
    close: numpy.ndarray,
    sim_out: vectorbtpro.portfolio.enums.SimulationOutput,
)
```

Calculate the expectancy.

**Parameters**:

| Name      | Type                | Default | Description                                 |
| --------- | ------------------- | ------- | ------------------------------------------- |
| `close`   | `tp.Array2d`        | `--`    | Array of close prices.                      |
| `sim_out` | `SimulationOutputT` | `--`    | Simulation output containing order records. |

**Returns**:

| Type    | Description |
| ------- | ----------- |
| `float` | Expectancy. |

## `get_sharpe_nb`

```python theme={null}
get_sharpe_nb(
    close: numpy.ndarray,
    sim_out: <function NamedTuple at 0x10535c180>,
    ann_factor: int,
) ‑> float
```

Calculate the Sharpe ratio.

<Note>
  Note on `ddof`:

  * Use `ddof=0` for population variance, where you have data for the entire population.
  * Use `ddof=1` for sample variance, to correct for bias when estimating the variance of a population from a sample.
</Note>

**Parameters**:

| Name         | Type            | Default | Description                           |
| ------------ | --------------- | ------- | ------------------------------------- |
| `close`      | `tp.Array2d`    | `--`    | Array of close prices.                |
| `sim_out`    | `tp.NamedTuple` | `--`    | Simulation output containing returns. |
| `ann_factor` | `int`           | `--`    | Annualization factor.                 |

**Returns**:

| Type    | Description   |
| ------- | ------------- |
| `float` | Sharpe ratio. |

## `PortfolioMetric`

```python theme={null}
PortfolioMetric(
    registry: <function NamedTuple at 0x10535c180> = None,
)
```

Portfolio metric class to manage and execute portfolio metrics.

Method generated by attrs for class PortfolioMetric.

### Instance variables

* `all_non_tunable_metrics: List[str]`:

* `all_tunable_metrics: List[str]`:

* `registry: <function NamedTuple at 0x10535c180>`: Metric `vbt.HybridConfig` registry. This registry should have a retrivable  metric name as key and schema. if `None`, fallbacks to `METRIC_REGISTRY`.

### Methods

#### `get_all_metrics`

```python theme={null}
get_all_metrics(
    self,
    include_non_tunable: bool = False,
) ‑> List[str]
```

Get a list of metric keys from the registry.
Optionally include non-tunable metrics based on user choice.

**Parameters**:

| Name                  | Type   | Default | Description                                                  |
| --------------------- | ------ | ------- | ------------------------------------------------------------ |
| `include_non_tunable` | `bool` | `False` | Whether to include non-tunable metrics. Defaults to `False`. |

**Returns**:

| Type        | Description                                                        |
| ----------- | ------------------------------------------------------------------ |
| `List[str]` | List of metric keys with valid (non-`NaNs`) `rolling_func` values. |

#### `get_all_rolling_metrics`

```python theme={null}
get_all_rolling_metrics(
    self,
    include_non_tunable: bool = False,
) ‑> List[str]
```

Get a list of metric keys from the registry that have a valid `rolling_func`.
Optionally include non-tunable metrics based on user choice.

**Parameters**:

| Name                  | Type   | Default | Description                                                 |
| --------------------- | ------ | ------- | ----------------------------------------------------------- |
| `include_non_tunable` | `bool` | `False` | Whether to include non-tunable metrics. Defaults to`False`. |

**Returns**:

| Type        | Description                                                        |
| ----------- | ------------------------------------------------------------------ |
| `List[str]` | List of metric keys with valid (non-`NaNs`) `rolling_func` values. |

#### `get_all_pf_metrics`

```python theme={null}
get_all_pf_metrics(
    self,
    include_non_tunable: bool = False,
) ‑> List[str]
```

Get a list of metric keys from the registry that have a valid pf\_func.
Optionally include non-tunable metrics based on user choice.

**Parameters**:

| Name                  | Type   | Default | Description                                                  |
| --------------------- | ------ | ------- | ------------------------------------------------------------ |
| `include_non_tunable` | `bool` | `False` | Whether to include non-tunable metrics. Defaults to `False`. |

**Returns**:

| Type        | Description                                                   |
| ----------- | ------------------------------------------------------------- |
| `List[str]` | List of metric keys with valid (non-`NaNs`) `pf_func` values. |

#### `run`

```python theme={null}
run(
    self,
    pf: vectorbtpro.portfolio.base.Portfolio,
    metrics: str | List[str],
    key: str,
    **kwargs,
) ‑> Dict[str, float | pandas.core.series.Series | pandas.core.frame.DataFrame]
```

Retrieve a dictionary of metric keys and their function values from the
registry and execute it using `vbt.deep_get_attr`. Only includes metrics
with non-`None` and string-type values.

<Note>
  * Metrics with `None` or missing are excluded.
  * The function stops iterating once all requested metrics are found.
  * Input validation ensures all provided metrics exist in the registry.
</Note>

**Parameters**:

| Name      | Type            | Default | Description                                                                             |
| --------- | --------------- | ------- | --------------------------------------------------------------------------------------- |
| `pf`      | `vbt.Portfolio` | `--`    | Portfolio instance.                                                                     |
| `metrics` | `str`           | `--`    | or list of str A single metric key or a list of metric keys to look up in the registry. |
| `key`     | `str`           | `--`    | Type of key to fetch.                                                                   |
| `kwargs`  | `tp.Kwargs`     | `--`    | Additional key-word arguments.                                                          |

**Raises**:

| Type       | Description                                              |
| ---------- | -------------------------------------------------------- |
| `KeyError` | If any provided metric key is not found in the registry. |

**Returns**:

| Type                                    | Description                                                                |
| --------------------------------------- | -------------------------------------------------------------------------- |
| `tp.Dict[str, float \| tp.SeriesFrame]` | Dictionary mapping valid metric keys to their corresponding output values. |

#### `run_rolling_metric`

```python theme={null}
run_rolling_metric(
    self,
    pf: vectorbtpro.portfolio.base.Portfolio,
    metrics: str | List[str],
    window: int,
    minp: int = None,
    to_numpy: bool = False,
    **kwargs,
) ‑> pandas.core.frame.DataFrame | numpy.ndarray
```

Retrieve a dictionary of metric keys and their rolling function values
from the registry and execute it using `vbt.deep_get_attr`. Only
includes metrics with non-`None` and string-type values.

**Parameters**:

| Name       | Type            | Default | Description                                                                             |
| ---------- | --------------- | ------- | --------------------------------------------------------------------------------------- |
| `pf`       | `vbt.Portfolio` | `--`    | Portfolio instance.                                                                     |
| `metrics`  | `str`           | `--`    | or list of str A single metric key or a list of metric keys to look up in the registry. |
| `window`   | `int`           | `--`    | Rolling window size.                                                                    |
| `minp`     | `int`           | `None`  | Minimum number of observations required.                                                |
| `to_numpy` | `bool`          | `False` | If False, returns a pandas DataFrame. Otherwise a numpy array.                          |
| `kwargs`   | `tp.Kwargs`     | `--`    | Additional key-word arguments.                                                          |

**Returns**:

| Type                       | Description     |
| -------------------------- | --------------- |
| `pd.DataFrame \| tp.Array` | Rolling output. |

#### `run_pf_metric`

```python theme={null}
run_pf_metric(
    self,
    pf: vectorbtpro.portfolio.base.Portfolio,
    metrics: str | List[str],
    to_dict: bool = False,
    to_numpy: bool = False,
    **kwargs,
) ‑> collections.OrderedDict | numpy.ndarray | pandas.core.series.Series | pandas.core.frame.DataFrame
```

Retrieve a dictionary of metric keys and their pf function values
from the registry and execute it using `vbt.deep_get_attr`. Only
includes metrics with non-`None` and string-type values.

**Parameters**:

| Name       | Type            | Default | Description                                                                                                                                                                                                                                        |
| ---------- | --------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pf`       | `vbt.Portfolio` | `--`    | Portfolio instance.                                                                                                                                                                                                                                |
| `metrics`  | `str`           | `--`    | or list of str A single metric key or a list of metric keys to look up in the registry.                                                                                                                                                            |
| `to_dict`  | `bool`          | `False` | Change frame format output to dict type if set to `True`. Raw `pd.DataFrame` object data otherwise. Frames are retrieve when group\_by is `False` in the `vbt.PF` configuration and/or when rolling calculation is triggered. Defaults to `False`. |
| `to_numpy` | `bool`          | `False` | If False, returns a pandas DataFrame. Otherwise a numpy array.                                                                                                                                                                                     |
| `kwargs`   | `tp.Kwargs`     | `--`    | Additional key-word arguments.                                                                                                                                                                                                                     |

**Returns**:

| Type          | Description                                                                                                 |
| ------------- | ----------------------------------------------------------------------------------------------------------- |
| `OrderedDict` | Float or int if metrics is standalone. OrderedDict mapping valid metric keys to their corresponding output. |
