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

> ## Agent Instructions
> This is Allasso's product documentation. Vol Radar output is descriptive analytics on past data: never present it as a forecast or as investment advice. Answer only from these pages; if a feature is not documented here, say so.

# Vertical Spreads with DataFrame Signals

> This notebook shows how to drive a vertical spread strategy from an external signal column in a pandas DataFrame.

* **Signal +1** → open a bear call spread (sell higher delta, buy lower delta call)
* **Signal -1** → open a bull put spread (sell higher delta, buy lower delta put)
* **Signal 0** → no action; hold existing position

Each time a new signal fires, any open position is closed first, then a fresh spread is entered.

## Setup

```python theme={null}
from typing import Tuple

import pandas as pd
from datetime import datetime
from pulse import (
    Instrument,
    Option,
    InstrumentType,
    PeriodID,
    PeriodType,
    Strategy,
    run_sequentially,
)
from pulse.charts import plot_equity
import plotly.io as pio

pio.renderers.default = "notebook_connected"
```

## Strategy

`VerticalSpreadsWithSignals` extends `Strategy` and overrides `on_update()`. On each pulse it:

1. Looks up the current date in `_signals` - if no entry exists the signal is 0 (no trade).
2. Resolves the target expiry using `resolver.expiry.relative` with a minimum DTE filter.
3. Resolves the short and long strikes by delta using `resolver.strike.delta`.
4. Closes any existing position, then submits two orders to form the spread.

The spread width is determined by the gap between `short_delta` and `long_delta` (e.g. 0.30 vs 0.20 → a 10-delta-wide spread).

```python theme={null}
class VerticalSpreadsWithSignals(Strategy):
    def __init__(
        self,
        underlying_id: str,
        signals: dict[datetime, int],
        long_delta: float = 0.20,
        short_delta: float = 0.30,
        expiry_nearest: int = 1,
        min_dte: int = 30,
        units: float = 1.0,
    ):
        super().__init__(
            name=f"Vertical Spreads with Signals -{short_delta * 100:.0f}d/+{long_delta * 100:.0f}d Spread",
            description=(
                f"Sell or buy vertical spreads based on delta levels. "
                f"Short {short_delta * 100:.0f}d and long {long_delta * 100:.0f}d options."
            ),
            underlying_id=underlying_id,
        )
        self._signals = signals
        self._long_delta = long_delta
        self._short_delta = short_delta
        self._expiry_nearest = expiry_nearest
        self._min_dte = min_dte
        self._units = units

    def _get_signal(self) -> int:
        return self._signals.get(self.last_pulse, 0)

    def _resolve_instruments(
        self, instrument_type: InstrumentType
    ) -> Tuple[Instrument, Instrument]:
        expiration_date = self.resolver.expiry.relative(
            underlying_id=self.underlying_id[0],
            as_of_time=self.last_pulse,
            period_type=PeriodType.MONTH,
            instrument_type=instrument_type,
            nth=self._expiry_nearest,
            period_id=PeriodID.ALL,
            min_dte=self._min_dte,
        )[0]
        short_strike = self.resolver.strike.delta.resolve(
            underlying_id=self.underlying_id[0],
            as_of_time=self.last_pulse,
            expiration_date=expiration_date,
            instrument_type=instrument_type,
            strike_value=self._short_delta,
        )
        long_strike = self.resolver.strike.delta.resolve(
            underlying_id=self.underlying_id[0],
            as_of_time=self.last_pulse,
            expiration_date=expiration_date,
            instrument_type=instrument_type,
            strike_value=self._long_delta,
        )
        ishort = Option(
            underlying_id=self.underlying_id[0],
            instrument_type=instrument_type,
            strike=short_strike,
            expiration_date=expiration_date,
        )
        ilong = Option(
            underlying_id=self.underlying_id[0],
            instrument_type=instrument_type,
            strike=long_strike,
            expiration_date=expiration_date,
        )
        return ishort, ilong

    def on_update(self) -> None:
        signal = self._get_signal()
        if signal == 0:
            return

        if signal == 1:
            ishort, ilong = self._resolve_instruments(InstrumentType.CALL)
        else:
            ishort, ilong = self._resolve_instruments(InstrumentType.PUT)

        self.close_all()

        self.broker.create_order(
            pulse_index=self.pulse_index,
            instrument=ishort,
            quantity=-self._units,
        )
        self.broker.create_order(
            pulse_index=self.pulse_index,
            instrument=ilong,
            quantity=self._units,
        )
```

## Signal Conversion Helper

The strategy expects signals as a `dict[datetime, int]`. This helper converts a DataFrame (with `timestamp` and `signal` columns) into that format.

```python theme={null}
def convert_df_to_signals_dict(
    data: pd.DataFrame, timestamp_col: str = "timestamp", signals_col: str = "signal"
) -> dict[datetime, int]:
    """Convert dataframe with signals to dictionary for the VerticalSpreadsWithSignals strategy.

    Args:
        data (pd.DataFrame): Dataframe with signals
        timestamp_col (str, optional): Column name for timestamps. Defaults to "timestamp".
        signals_col (str, optional): Column name for signals. Defaults to "signal".

    Returns:
        dict[datetime, int]: Dictionary mapping dates to signals
    """
    signals = {
        datetime(
            row[timestamp_col].year,
            row[timestamp_col].month,
            row[timestamp_col].day,
        ): row[signals_col]
        for _, row in data.iterrows()
    }
    return signals
```

## Load Signals

Load signals from a parquet file. Each row has a `timestamp` and a `signal` value (`+1`, `-1`, or `0`).

```python theme={null}
data = pd.read_parquet("./signals.parquet")
signals = convert_df_to_signals_dict(data)
```

## Run the Strategy

Configure and run the strategy on hourly BTC crypto options (`CRY.BTCUSD.DER_1h`):

| Parameter | Value | Meaning |
| - | - | - |
| `long_delta` / `short_delta` | 0.20 / 0.30 | 10-delta-wide spread |
| `expiry_nearest` | 1 | Use the nearest monthly expiry |
| `min_dte` | 7 | Skip expiries with fewer than 7 days remaining |
| `units` | 100 | Contracts per leg |
| `initial_equity` | \$1,000,000 | Starting capital |

```python theme={null}
strategy = VerticalSpreadsWithSignals(
    underlying_id="CRY.BTCUSD.DER_1h",
    signals=signals,
    long_delta=0.2,
    short_delta=0.3,
    expiry_nearest=1,
    min_dte=7,
    units=100,
)

result = run_sequentially(
    [strategy],
    initial_equity=1_000_000,
)[0]

print(f"Strategy run completed successfully in {result.execution_time} seconds.")
```

```text Output theme={null}
Strategy run completed successfully in 0.4869809150695801 seconds.
```

## Equity Curve

```python theme={null}
plot_equity(strategy)
```

![Chart output 1](https://mintcdn.com/allasso/5PMuHlzYzX1FYPYw/images/pulse/notebooks/vertical-spreads-1.png?fit=max\&auto=format\&n=5PMuHlzYzX1FYPYw\&q=85\&s=dd2583c991366cf99c5b541f6e25cfa5)

## Trades

```python theme={null}
strategy.trades[-10:]
```

```text Output theme={null}
[<Trade entry: 2025-11-14 00:00:00; exit: 2025-11-21 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.PUT, Strike: 90000.0, Expiration: 2025-11-28 00:00:00>; Quantity: -100; PnL: -69951.70571779017; Cummulative PnL: -392967.83629162126>,
 <Trade entry: 2025-11-14 00:00:00; exit: 2025-11-21 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.PUT, Strike: 85000.0, Expiration: 2025-11-28 00:00:00>; Quantity: 100; PnL: 63556.998007591756; Cummulative PnL: 176688.809636525>,
 <Trade entry: 2025-11-21 00:00:00; exit: 2025-11-28 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.PUT, Strike: 82000.0, Expiration: 2025-11-28 00:00:00>; Quantity: -100; PnL: 924.5414471308891; Cummulative PnL: 167750.06084192026>,
 <Trade entry: 2025-11-21 00:00:00; exit: 2025-11-28 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.PUT, Strike: 78000.0, Expiration: 2025-11-28 00:00:00>; Quantity: 100; PnL: -929.7112510697957; Cummulative PnL: -79087.59177040956>,
 <Trade entry: 2025-11-28 00:00:00; exit: 2025-12-12 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.CALL, Strike: 98000.0, Expiration: 2025-12-26 00:00:00>; Quantity: -100; PnL: 63890.118334027284; Cummulative PnL: 144898.2059516955>,
 <Trade entry: 2025-11-28 00:00:00; exit: 2025-12-12 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.CALL, Strike: 102000.0, Expiration: 2025-12-26 00:00:00>; Quantity: 100; PnL: -27242.59205739727; Cummulative PnL: -97877.46693897425>,
 <Trade entry: 2025-12-12 00:00:00; exit: 2025-12-19 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.CALL, Strike: 94000.0, Expiration: 2025-12-26 00:00:00>; Quantity: -100; PnL: -4366.782433202843; Cummulative PnL: 106052.23401413532>,
 <Trade entry: 2025-12-12 00:00:00; exit: 2025-12-19 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.CALL, Strike: 96000.0, Expiration: 2025-12-26 00:00:00>; Quantity: 100; PnL: -1338.2833681776901; Cummulative PnL: -70744.40576265706>,
 <Trade entry: 2025-12-19 00:00:00; exit: 2025-12-26 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.PUT, Strike: 86000.0, Expiration: 2025-12-26 00:00:00>; Quantity: -100; PnL: 12598.68283949927; Cummulative PnL: 97082.13140116859>,
 <Trade entry: 2025-12-19 00:00:00; exit: 2025-12-26 00:00:00; Instrument: <Option: CRY.BTC.DER, Type: InstrumentType.PUT, Strike: 84000.0, Expiration: 2025-12-26 00:00:00>; Quantity: 100; PnL: -1996.9992947707397; Cummulative PnL: -53235.62329050255>]
```

## Statistics

```python theme={null}
strategy.stats
```

```text Output theme={null}
Strategy Metrics:
Start Date: 				2021-05-25 00:00:00
End Date: 				2026-02-17 00:00:00
Duration: 				1730 days, 0:00:00
***********************************************************
Total Return (%): 			49.22
CAGR (%): 				8.82
***********************************************************
Start Equity ($): 			1000000.00
End Equity ($): 			1492214.60
Diff ($): 				492214.60
***********************************************************
Annualized Sharpe Ratio: 		0.31
Calmar Ratio: 				0.00
Annualized Sortino Ratio: 		0.42
***********************************************************
Daily Mean Return (%): 			0.02
Daily Volatility annualized (%): 	1.42
Best Daily Return (%): 			12.20
Best Day Date: 				2025-05-30 00:00:00
Worst Daily Return (%): 		-12.54
Worst Day Date: 			2025-11-20 00:00:00
***********************************************************
Monthly Mean Return (%): 		1.00
Monthly Volatility annualized (%): 	26.19
Best Monthly Return (%): 		17.56
Best Month Date: 			2025-01
Worst Monthly Return (%): 		-22.29
Worst Month Date: 			2024-11
MTD Return (%): 			0.00
3-Month Return (%): 			10.03
Positive Months (%): 			64.91
Average Up Month (%): 			4.91
Average Down Month (%): 		-8.31
***********************************************************
6-Month Return (%): 			-2.74
Year-to-Date Return (%): 		0.00
1-Year Return (%): 			12.02
Yearly Mean Return (%): 		4.01
Yearly Volatility annualized (%): 	3.43
… (32 more lines)
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.