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

# Optuna Tuner

> systematica.portfolio.tuners.optuna_tuner

## `OptunaTuner`

```python theme={null}
OptunaTuner(
    pruner: optuna.pruners._base.BasePruner = <optuna.pruners._successive_halving.SuccessiveHalvingPruner object>,
    sampler: optuna.samplers._base.BaseSampler = <optuna.samplers._tpe.sampler.TPESampler object>,
    direction: str | List[str] = 'maximize',
    create_study_kwargs: Dict[str, Any] = _Nothing.NOTHING,
    n_trials: int = 100,
    n_completed_trials: int = None,
    n_jobs: int = -1,
    gc_after_trial: bool = False,
    optimize_kwargs: Dict[str, Any] = _Nothing.NOTHING,
    verbose: bool = True,
    tracker: systematica.portfolio.trackers.base.BaseTracker = None,
    metrics: str | List[str] = 'sharpe_ratio',
    metric_registry_kwargs: Dict[str, Any] = _Nothing.NOTHING,
    cross_validate: bool = False,
    reduce_func: Callable = CPUDispatcher(<function nanmedian_nb>),
    use_rolling: bool = False,
)
```

Method generated by attrs for class OptunaTuner.

### Static methods

#### `get_all_metrics`

```python theme={null}
get_all_metrics(
    use_rolling: 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                                                                                                                  |
| ------------- | ------ | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `use_rolling` | `bool` | `False` | Flag to use rolling method via `BaseRollingReport`. Note that both rolling and cv models can be passed. Defaults to `False`. |

**Returns**:

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

### Instance variables

* `target_names: List[str]`: Normalize metric names.

* `create_study_kwargs: Dict[str, Any]`: Additional optuna study parameters.

* `cross_validate: bool`: Whether to use cross-validation analytics through `run_report`, wrapping `BaseReportCV` or `BaseRollingReport` instead of using `run_pipeline` alone. If True, optimize using cross validation. Otherwise, uses data history  as a whole. Defaults to False.

* `direction: str | List[str]`: Optimization direction for Optuna (default: 'maximize'). If list, direction is modified to "directions" internally.

* `gc_after_trial: bool`: Flag to determine whether to automatically run garbage collection after  each trial. Set to `True` to run the garbage collection, `False` otherwise. It runs a full collection by internally calling `gc.collect`. If you see an increase in memory consumption over several trials, try setting this flag to `True`.

* `metric_registry_kwargs: Dict[str, Any]`: Additional arguments for metric registry. Parameters such as `window` of `minp` for rolling metrics should be specified at this level.

* `metrics: str | List[str]`: Performance metrics to compute (default: 'sharpe\_ratio').

* `n_completed_trials: int`: Number of trials to complete before stopping (default: None).

* `n_jobs: int`: Parallel jobs for Optuna (default: -1).

* `n_trials: int`: Number of optimization trials for Optuna (default: 100).

* `optimize_kwargs: Dict[str, Any]`: Additional arguments for Optuna optimization.

* `pruner: optuna.pruners._base.BasePruner`: Pruner. Defaults to Asynchronous Successive Halving Algorithm.

* `reduce_func: Callable`: Reduce function when using cross\_validate. If None, defaults to  `vbt.nb.nanmedian_nb`. Defaults to None.

* `sampler: optuna.samplers._base.BaseSampler`: Sampler. Defaults to TPE (Tree-structured Parzen Estimator) algorithm.

* `tracker: systematica.portfolio.trackers.base.BaseTracker`: Log and monitor the Optuna hyperparameter using tracker integration.

* `use_rolling: bool`: Flag to use rolling method via `BaseRollingReport`. Note that  both rolling and cv models can be passed. Defaults to False.

* `verbose: bool`: Enable verbose output (default: True).

### Methods

#### `check_direction`

```python theme={null}
check_direction(
    self,
    attribute: str,
    value: str | list[str],
)
```

Validate optimization directions.

**Parameters**:

| Name        | Type              | Default | Description                    |
| ----------- | ----------------- | ------- | ------------------------------ |
| `attribute` | `attrs.Attribute` | `--`    | The attribute being validated. |
| `value`     | `BaseStatArb`     | `--`    | The model instance.            |

**Raises**:

| Type         | Description                                   |
| ------------ | --------------------------------------------- |
| `ValueError` | If direction is not "maximize" or "minimize". |
| `TypeError`  | If direction is not a string or a list        |

#### `check_metrics`

```python theme={null}
check_metrics(
    self,
    attribute: str,
    value: str | list[str],
)
```

Validate metrics

**Parameters**:

| Name        | Type              | Default | Description                    |
| ----------- | ----------------- | ------- | ------------------------------ |
| `attribute` | `attrs.Attribute` | `--`    | The attribute being validated. |
| `value`     | `BaseStatArb`     | `--`    | The model instance.            |

**Raises**:

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

#### `create_objective`

```python theme={null}
create_objective(
    self,
    feature_config: FeatureConfig,
) ‑> Callable
```

Creates an optimized objective function for Optuna by separating fixed
and tunable parameters once.

**Parameters**:

| Name             | Type            | Default | Description             |
| ---------------- | --------------- | ------- | ----------------------- |
| `feature_config` | `FeatureConfig` | `--`    | Feature configurations. |

**Returns**:

| Type          | Description                                            |
| ------------- | ------------------------------------------------------ |
| `tp.Callable` | A callable objective function for Optuna optimization. |

#### `run_feature`

```python theme={null}
run_feature(
    self,
    feature_config: FeatureConfig,
) ‑> optuna.study.study.Study
```

Run feature config.

**Parameters**:

| Name             | Type            | Default | Description            |
| ---------------- | --------------- | ------- | ---------------------- |
| `feature_config` | `FeatureConfig` | `--`    | feature configuration. |

**Returns**:

| Type           | Description   |
| -------------- | ------------- |
| `optuna.Study` | Optuna study. |

#### `run`

```python theme={null}
run(
    self,
    objective: Callable,
) ‑> optuna.study.study.Study
```

Run optuna study or tracker.

**Parameters**:

| Name        | Type          | Default | Description         |
| ----------- | ------------- | ------- | ------------------- |
| `objective` | `tp.Callable` | `--`    | Objective function. |

**Returns**:

| Type                   | Description   |
| ---------------------- | ------------- |
| `study : optuna.Study` | Optuna Study. |

#### `run_tracker`

```python theme={null}
run_tracker(
    self,
    objective: Callable,
) ‑> optuna.study.study.Study
```

Run tracker.

**Parameters**:

| Name        | Type          | Default | Description         |
| ----------- | ------------- | ------- | ------------------- |
| `objective` | `tp.Callable` | `--`    | Objective function. |

**Returns**:

| Type                   | Description   |
| ---------------------- | ------------- |
| `study : optuna.Study` | Optuna Study. |

#### `run_optuna`

```python theme={null}
run_optuna(
    self,
    objective: Callable,
) ‑> optuna.study.study.Study
```

Run optuna.

**Parameters**:

| Name        | Type          | Default | Description         |
| ----------- | ------------- | ------- | ------------------- |
| `objective` | `tp.Callable` | `--`    | Objective function. |

**Returns**:

| Type                   | Description   |
| ---------------------- | ------------- |
| `study : optuna.Study` | Optuna Study. |
