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

# Base

> systematica.models.base

## `BaseStatArb`

```python theme={null}
BaseStatArb()
```

Base Statistical Arbitrage class.

Method generated by attrs for class BaseStatArb.

### Ancestors

* `abc.ABC`

### Descendants

* `systematica.api.models.arbitrage_index.ArbitrageBaseIndex`
* `systematica.api.models.arbitrage_index.ArbitrageClipIndex`
* `systematica.api.models.arbitrage_index.ArbitrageCumulativeIndex`
* `systematica.api.models.arbitrage_index.ArbitrageProbabilityIndex`
* `systematica.api.models.arbitrage_index.ArbitrageResetIndex`
* `systematica.api.models.arbitrage_index.ArbitrageRollingZscoreIndex`
* `systematica.api.models.meta_model.MetaModel`
* `systematica.api.models.momentum.AverageMomentumFactorCV`
* `systematica.api.models.momentum.RollingAverageMomentumFactor`
* `systematica.api.models.ou_process.RollingOUProcess`
* `systematica.api.models.range_breakout.RangeBreakout`
* `systematica.api.models.spread.RollingSpreadModel`
* `systematica.api.models.spread.RollingZscoreModel`
* `systematica.api.models.volatility.RollingVolatilityFactor`
* `systematica.api.models.volatility.VolatilityFactorCV`
* `systematica.api.models.volume_profile.RollingVolumeProfileFactor`
* `systematica.api.models.volume_profile.VolumeProfileFactorCV`

### Static methods

#### `is_valid`

```python theme={null}
is_valid(
    model_params: Dict[str, Any],
    signal_params: Dict[str, Any],
)
```

Validate model parameters.

This method checks if the model parameters are valid for the statistical arbitrage model.
It should be implemented in subclasses and decorated with `staticmethod` to allow calling it without an instance.
If the model does not require validation, it can be implemented as a no-op method with the `@staticmethod` decorator.

**Examples**:

To implement this method, define it in the subclass and use the `@staticmethod` decorator
like so:

```python theme={null}
>>> @staticmethod
>>> def is_valid(model_params: tp.Kwargs, signal_params: tp.Kwargs):
...     # Implement validation logic here
...     pass
```

**Parameters**:

| Name            | Type        | Default | Description        |
| --------------- | ----------- | ------- | ------------------ |
| `model_params`  | `tp.Kwargs` | `--`    | Model parameters.  |
| `signal_params` | `tp.Kwargs` | `--`    | Signal parameters. |

#### `run_walk_forward`

```python theme={null}
run_walk_forward(
    cls,
    **feature,
) ‑> systematica.walk_forward.base.BaseWalkForward
```

Analyzes model using rolling or cross-validation techniques.

Determine the appropriate `wf` selection class based on model attributes and use\_rolling flag.

**Parameters**:

| Name      | Type        | Default | Description                              |
| --------- | ----------- | ------- | ---------------------------------------- |
| `feature` | `tp.Kwargs` | `--`    | Configuration for a feature calculation. |

**Returns**:

| Type         | Description                                                                                           |
| ------------ | ----------------------------------------------------------------------------------------------------- |
| `BaseReport` | An instance of `BaseWalkForwardRolling` or `BaseWalkForwardCV` depending on the model and parameters. |

#### `run_analyzer`

```python theme={null}
run_analyzer(
    cls,
    validate_model: bool = True,
    **feature,
) ‑> systematica.portfolio.analyzer.PortfolioAnalyzer
```

Executes the portfolio analyzer.

<Note>
  Combines scoring, signal generation, and portfolio simulation into a
  single pipeline for streamlined backtesting.
</Note>

**Parameters**:

| Name             | Type        | Default | Description                                    |
| ---------------- | ----------- | ------- | ---------------------------------------------- |
| `validate_model` | `bool`      | `True`  | Validate model parameters. Defaults to `True`. |
| `feature`        | `tp.Kwargs` | `--`    | Configuration for a feature calculation.       |

**Returns**:

| Type                | Description                                                                |
| ------------------- | -------------------------------------------------------------------------- |
| `PortfolioAnalyzer` | An instance of `PortfolioAnalyzer` containing the results of the backtest. |

#### `run_model`

```python theme={null}
run_model(
    cls,
    **feature,
) ‑> pandas.core.frame.DataFrame
```

Run parameterized scores generation.

<Note>
  The method utilizes parameterization to run scores over various parameter
  combinations. The results can be merged and accessed as a single output
  object.
</Note>

**Parameters**:

| Name      | Type        | Default | Description                              |
| --------- | ----------- | ------- | ---------------------------------------- |
| `feature` | `tp.Kwargs` | `--`    | Configuration for a feature calculation. |

**Returns**:

| Type           | Description                            |
| -------------- | -------------------------------------- |
| `pd.DataFrame` | Scores for each parameter combination. |

#### `run_signals`

```python theme={null}
run_signals(
    cls,
    validate_model: bool = True,
    **feature,
) ‑> pandas.core.frame.DataFrame
```

Run parametrized signals generation.

<Note>
  The method utilizes parameterization to run signal generation over
  various parameter combinations. The results can be merged and accessed
  as a single output object.
</Note>

**Parameters**:

| Name             | Type        | Default | Description                                    |
| ---------------- | ----------- | ------- | ---------------------------------------------- |
| `validate_model` | `bool`      | `True`  | Validate model parameters. Defaults to `True`. |
| `feature`        | `tp.Kwargs` | `--`    | Configuration for a feature calculation.       |

**Returns**:

| Type           | Description                             |
| -------------- | --------------------------------------- |
| `pd.DataFrame` | Signals for each parameter combination. |

#### `run_pipeline`

```python theme={null}
run_pipeline(
    cls,
    validate_model: bool = True,
    to_numpy: bool = False,
    **feature,
) ‑> vectorbtpro.portfolio.base.Portfolio | collections.OrderedDict | pandas.core.frame.DataFrame | numpy.ndarray
```

Executes the portfolio pipeline. Method is parametrizable.

<Note>
  Combines scoring, signal generation, and portfolio simulation into a
  single pipeline for streamlined backtesting.
</Note>

**Parameters**:

| Name             | Type        | Default | Description                                                                        |
| ---------------- | ----------- | ------- | ---------------------------------------------------------------------------------- |
| `validate_model` | `bool`      | `True`  | Validate model parameters. Defaults to `True`.                                     |
| `to_numpy`       | `bool`      | `False` | If `True`, returns a `np.ndarray`. Default is `False`, returning a `pd.DataFrame`. |
| `feature`        | `tp.Kwargs` | `--`    | Configuration for a feature calculation.                                           |

**Returns**:

| Type                                                | Description                                |
| --------------------------------------------------- | ------------------------------------------ |
| `vbt.PF \| OrderedDict \| pd.DataFrame \| tp.Array` | Backtested portfolio or requested metrics. |

#### `run_expression`

```python theme={null}
run_expression(
    cls,
    feature_expression: systematica.generic.base.FeatureExpression = None,
    runner_kwargs: Dict[str, Any] = None,
    validate_model: bool = True,
    to_numpy: bool = False,
    **feature,
) ‑> vectorbtpro.portfolio.base.Portfolio | collections.OrderedDict | pandas.core.frame.DataFrame | numpy.ndarray
```

Build an indicator class from an indicator expression.

Builds a new indicator class based on a Python expression string.

See `vbt.IF.from_expr` for more information.

**Parameters**:

| Name                 | Type                | Default | Description                                                                                                           |
| -------------------- | ------------------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| `feature_expression` | `FeatureExpression` | `to`    | `None` Instance of `FeatureExpression`. If `None`, take `cls.get_expression` method as reference. Defaults to `None`. |
| `runner_kwargs`      | `tp.Kwargs`         | `--`    | Additional key-word arguments used in `vbt.Data.run`. Defaults to `None`.                                             |
| `validate_model`     | `bool`              | `True`  | Check if model parameters are valid. Defaults to `True`.                                                              |
| `to_numpy`           | `bool`              | `False` | If `True`, returns a `np.ndarray`. Default is `False`, returning a `pd.DataFrame`.                                    |
| `feature`            | `tp.Kwargs`         | `--`    | Configuration for a feature calculation.                                                                              |

**Returns**:

| Type                                                | Description                                |
| --------------------------------------------------- | ------------------------------------------ |
| `vbt.PF \| OrderedDict \| pd.DataFrame \| tp.Array` | Backtested portfolio or requested metrics. |

**Raises**:

| Type         | Description                                                               |
| ------------ | ------------------------------------------------------------------------- |
| `ValueError` | If both `feature_expression` and `cls.get_feature_expression` are `None`. |

#### `run_optuna_study`

```python theme={null}
run_optuna_study(
    objective: systematica.tuners.base.BaseOptunaObjective,
    feature: systematica.generic.base.Feature,
    search_space: Dict[str, Any],
    callbacks: Iterable = None,
) ‑> optuna.study.study.Study
```

Run hyperparameter optimization using `optuna` for a signal-based trading
strategy.

<Note>
  * Optuna is used for hyperparameter tuning and efficiently finds the
    best parameters.
  * The study prunes trials with poor results to accelerate the search
    process.
</Note>

**References**:

* [Optuna Documentation](https://optuna.org/)
* [Pruning Trials](https://optuna.readthedocs.io/en/stable/tutorial/pruning.html)

**Parameters**:

| Name           | Type                  | Default | Description                                                                                                                                                                   |
| -------------- | --------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Objective`    | `BaseOptunaObjective` | `--`    | Optuna custom objective object.                                                                                                                                               |
| `feature`      | `Feature`             | `--`    | The feature configuration.                                                                                                                                                    |
| `search_space` | `dict`                | `--`    | The hyperparameter search space.                                                                                                                                              |
| `callbacks`    | `tp.Iterable`         | `None`  | List of callback functions that are invoked at the end of each trial. Each function must accept two parameters with the following types in this order: Study and FrozenTrial. |

**Returns**:

| Type           | Description                                              |
| -------------- | -------------------------------------------------------- |
| `optuna.Study` | The Optuna study object containing optimization results. |

### Methods

#### `get_signals`

```python theme={null}
get_signals(
    self,
    validate_model: bool = True,
    **feature,
) ‑> systematica.signals.base.Signals
```

Generate trading signals based on scores.

**Parameters**:

| Name             | Type        | Default | Description                                    |
| ---------------- | ----------- | ------- | ---------------------------------------------- |
| `validate_model` | `bool`      | `True`  | Validate model parameters. Defaults to `True`. |
| `feature`        | `tp.Kwargs` | `--`    | Configuration for a feature calculation.       |

**Returns**:

| Type      | Description        |
| --------- | ------------------ |
| `Signals` | Generated signals. |
