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

# Simulation

> systematica.portfolio.simulation

## `run_from_signals`

```python theme={null}
run_from_signals(
    data: pandas.core.frame.DataFrame | vectorbtpro.data.base.Data,
    signals: systematica.signals.base.Signals,
    *,
    metrics: str | List[str] = None,
    metrics_kwargs: Dict[str, Any] = None,
    use_rolling: bool = False,
    to_numpy: bool = False,
    **portfolio_config,
) ‑> vectorbtpro.portfolio.base.Portfolio | collections.OrderedDict | pandas.core.frame.DataFrame | numpy.ndarray
```

Simulate a single trading strategy.

**Parameters**:

| Name               | Type        | Default | Description                                                                                                                                 |
| ------------------ | ----------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `data`             | `vbt.Data`  | `--`    | Historical market data.                                                                                                                     |
| `signals`          | `Signals`   | `--`    | Generated trading signals.                                                                                                                  |
| `metrics`          | `str`       | `None`  | Metrics to evaluate the portfolio, by default `None`.                                                                                       |
| `use_rolling`      | `bool`      | `False` | Use rolling metrics. See metrics config. Defauts to `False`.                                                                                |
| `metrics_kwargs`   | `tp.Kwargs` | `None`  | Additional arguments for metric config. Parameters such as `window` of `minp` for rolling metrics should be specificed. Defaults to `None`. |
| `validate_metrics` | `bool`      | `True`  | Check if metric is valid in the config. Might slow-down code if set to True. Defaults to `True`.                                            |
| `to_numpy`         | `bool`      | `False` | If `True`, returns a numpy ndarray. Defaults to `False`, which means returns a pandas SeriesFrame.                                          |
| `portfolio_config` | `tp.Kwargs` | `--`    | Additional arguments for portfolio simulation.                                                                                              |

**Returns**:

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

## `run_from_signals_nb`

```python theme={null}
run_from_signals_nb(
    open: numpy.ndarray,
    high: numpy.ndarray,
    low: numpy.ndarray,
    close: numpy.ndarray,
    signals: systematica.signals.base.Signals,
    size: int = 50,
    sl_stop: float = nan,
    tsl_stop: float = nan,
    tp_stop: float = nan,
) ‑> vectorbtpro.portfolio.enums.SimulationOutput
```

Simulate strategy using Numba.

**Parameters**:

| Name       | Type      | Default  | Description                                                            |
| ---------- | --------- | -------- | ---------------------------------------------------------------------- |
| `close`    | `Array1d` | `--`     | Array of closing prices.                                               |
| `signals`  | `Signals` | `--`     | Generated trading signals.                                             |
| `size`     | `int`     | `50`     | Size of each order, default is `50`.                                   |
| `sl_stop`  | `float`   | `np.nan` | Stop-loss level, default is `np.nan` (no stop-loss).                   |
| `tsl_stop` | `float`   | `np.nan` | Trailing stop-loss level, default is `np.nan` (no trailing stop-loss). |
| `tp_stop`  | `float`   | `np.nan` | Take-profit level, default is `np.nan` (no take-profit).               |

**Returns**:

| Type                                                                       | Description          |
| -------------------------------------------------------------------------- | -------------------- |
| `SimulationOutput`                                                         | Simulated portfolio. |
| `<Note>`                                                                   |                      |
| `The output of this function is an instance of the type SimulationOutput,` |                      |
| `which can be used to construct a new Portfolio instance for analysis:`    |                      |
| `</Note>`                                                                  |                      |

**Examples**:

```python theme={null}
>>> pf = vbt.Portfolio(
...     data.symbol_wrapper.regroup(group_by=True),  
...     sim_out,  
...     open=data.open,  
...     high=data.high,
...     low=data.low,
...     close=data.close,
...     cash_sharing=True,
...     init_cash=100  
... )
>>> pf.total_return
# 0.19
```

## `run_from_optimize_func`

```python theme={null}
run_from_optimize_func(
    data: vectorbtpro.data.base.Data,
    returns: numpy.ndarray,
    signals: systematica.signals.base.Signals,
    optimize_func: Callable,
    *,
    config: Dict[str, Any] = None,
) ‑> vectorbtpro.portfolio.pfopt.base.PortfolioOptimizer
```

Sets up and returns a portfolio optimizer instance, using custom sampling
and optimization functions.

**Parameters**:

| Name            | Type          | Default | Description                                                                                                                                            |
| --------------- | ------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data`          | `vbt.Data`    | `--`    | Historical market data.                                                                                                                                |
| `returns`       | `tp.Array`    | `--`    | Array of returns to be used for optimization.                                                                                                          |
| `signals`       | `Signals`     | `--`    | Generated trading signals.                                                                                                                             |
| `optimize_func` | `tp.Callable` | `--`    | Custom optimization function that takes the returns and signals as input. This function should return a dictionary of optimized parameters or metrics. |
| `config`        | `tp.Kwargs`   | `None`  | Dictionary with optimization parameters. Defaults to `None`.                                                                                           |

**Returns**:

| Type                     | Description                                                    |
| ------------------------ | -------------------------------------------------------------- |
| `vbt.PortfolioOptimizer` | Configured portfolio optimizer instance ready for backtesting. |

**Examples**:

```python theme={null}
>>> strategy = ...
>>> portfolio_optimizer = strategy.optimizer(
...     ...,
...     config={'obj': 'Sharpe', 'every': 'M'}
... )
>>> portfolio = portfolio_optimizer.simulate()
```
