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

# Delta-Hedged Short Strangle

> This tutorial demonstrates a short strangle strategy with two layers of management:

This tutorial demonstrates a **short strangle** strategy with two layers of management:

1. **DTE-based rolling** - the strangle (short call + short put) is rolled whenever the current options fall below `min_dte` days to expiry
2. **Daily delta hedging** - the net options delta is neutralized each day using a front-month futures contract

The goal is to isolate **theta (time decay)** as the primary P\&L driver while removing directional exposure.

## Imports

We need the standard Pulse building blocks plus `InstrumentType.FUTURE` for the delta hedge leg.

```python theme={null}
from pulse import (
    Instrument,
    Option,
    Future,
    InstrumentType,
    PeriodID,
    PeriodType,
    Strategy,
    create_local_datafeed,
    run_sequentially,
)
import pulse.charts as pcharts
from typing import Tuple
import plotly.io as pio

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

## Strategy Design

The `DeltaHedgedShortStrangle` strategy has four helper methods and a simple main loop:

### Helpers

| Method | Purpose |
| - | - |
| `_resolve_strangle_instruments()` | Resolves the call and put `Instrument` objects for the current cycle using the configured delta and expiry |
| `_get_instrument_delta(instrument)` | Returns the live delta from the datafeed at the current pulse |
| `_get_instrument_dte(instrument)` | Returns the live DTE from the datafeed at the current pulse |
| `_calculate_hedge_quantity(call, put)` | Sums the portfolio delta of the short strangle and returns the futures lots needed to flatten it |

### Roll trigger - `_should_roll()`

Returns `True` when:

* No strangle is open yet, **or**
* The DTE of the current options (read live from the datafeed) has fallen below `min_dte`

### Roll - `_roll_strangle()`

1. Closes the existing strangle **and** hedge atomically so the books go flat
2. Resolves fresh call and put instruments via `_resolve_strangle_instruments()`
3. Sells both legs with `is_lots=True` - `lots` is in contract lots, multiplied by `contract_size` internally
4. Calls `_enter_hedge()` to open the initial futures position for this cycle

### Hedge entry - `_enter_hedge(call, put)`

Resolves the futures expiry to match the **option DTE** (not a fixed offset), ensuring the hedge tracks the same underlying forward contract. Opens the initial futures position via `broker.create_order`.

### Hedge rebalance - `_rebalance_hedge()`

On every non-roll day, calls `_calculate_hedge_quantity()` on the current strangle legs and calls `Trade.rebalance(quantity)` on the open hedge trade - adjusting the quantity in-place without generating a new trade entry.

### Lots vs. Units

| Mode | `is_lots` | What the quantity means |
| - | - | - |
| Units (raw) | `False` (default) | Exact number of contracts in the exchange's minimum unit |
| Lots | `True` | Number of lots; multiplied by the instrument's `contract_size` internally |

```python theme={null}
class DeltaHedgedShortStrangle(Strategy):
    def __init__(
        self,
        underlying_id: str,
        forward_expiry: int = 1,
        call_delta: float = 0.20,
        put_delta: float = 0.20,
        min_dte: int = 30,
        lots: float = 10.0,
    ):
        super().__init__(
            name=(
                f"Delta-Hedged Short Strangle "
                f"({call_delta*100:.0f}d Call / {put_delta*100:.0f}d Put)"
            ),
            description=(
                "Sells a strangle when DTE < min_dte and neutralises delta daily with futures."
            ),
            underlying_id=underlying_id,
        )
        self._forward_expiry = forward_expiry
        self._call_delta = call_delta
        self._put_delta = put_delta
        self._min_dte = min_dte
        self._lots = lots

    def _resolve_strangle_instruments(self) -> Tuple[Instrument, Instrument]:
        """Resolve call and put instruments for the current strangle cycle."""
        expiration_date = self.resolver.expiry.relative(
            underlying_id=self.underlying_id[0],
            as_of_time=self.last_pulse,
            period_type=PeriodType.MONTH,
            instrument_type=InstrumentType.CALL,
            nth=self._forward_expiry,
            period_id=PeriodID.ALL,
            min_dte=self._min_dte,
        )[0]

        call_strike = self.resolver.strike.delta.resolve(
            underlying_id=self.underlying_id[0],
            as_of_time=self.last_pulse,
            expiration_date=expiration_date,
            instrument_type=InstrumentType.CALL,
            strike_value=self._call_delta,
        )
        put_strike = self.resolver.strike.delta.resolve(
            underlying_id=self.underlying_id[0],
            as_of_time=self.last_pulse,
            expiration_date=expiration_date,
            instrument_type=InstrumentType.PUT,
            strike_value=self._put_delta,
        )
        return (
            Option(
                underlying_id=self.underlying_id[0],
                instrument_type=InstrumentType.CALL,
                expiration_date=expiration_date,
                strike=call_strike,
            ),
            Option(
                underlying_id=self.underlying_id[0],
                instrument_type=InstrumentType.PUT,
                expiration_date=expiration_date,
                strike=put_strike,
            ),
        )

    def _get_instrument_delta(self, instrument: Instrument) -> float:
        """Live delta of an instrument at the current pulse."""
        return self.datafeed.instrument.last(instrument, self.last_pulse).delta

    def _get_instrument_dte(self, instrument: Instrument) -> float:
        """Days to expiry of an instrument at the current pulse."""
        return self.datafeed.instrument.last(instrument, self.last_pulse).dte

    def _calculate_hedge_quantity(
        self, call: Instrument, put: Instrument
    ) -> float:
        """Net futures lots needed to flatten portfolio delta.

        The strangle is short ``lots`` of each leg, so each leg contributes
        ``delta * (-lots)`` to the portfolio delta.  The hedge must cancel that.
        """
        portfolio_delta = (
            self._get_instrument_delta(call) * (-self._lots)
            + self._get_instrument_delta(put) * (-self._lots)
        )
        hedge_quantity = -portfolio_delta
        return hedge_quantity if hedge_quantity != 0 else 1e-6

    def _should_roll(self) -> bool:
        strangle_trades = self.get_trades_by_tags(["strangle"])
        if not strangle_trades:
            return True
        return self._get_instrument_dte(strangle_trades[0].instrument) < self._min_dte

    def _roll_strangle(self) -> None:
        # Close strangle and hedge atomically so the books go flat
        self.close_trades_by_tags(["strangle"])
        self.close_trades_by_tags(["hedge"])

        call, put = self._resolve_strangle_instruments()

        # Sell both legs - is_lots=True so quantity is in contract lots
        self.broker.create_order(
            self.pulse_index, call, -self._lots, tags=["strangle"], is_lots=True
        )
        self.broker.create_order(
            self.pulse_index, put, -self._lots, tags=["strangle"], is_lots=True
        )

        # Enter the initial delta hedge for this cycle
        self._enter_hedge(call, put)

    def _enter_hedge(self, call: Instrument, put: Instrument) -> None:
        """Open the first futures hedge for a new strangle cycle.

        The futures expiry is resolved to match the options DTE so the hedge
        tracks the same underlying forward.
        """
        hedge_quantity = self._calculate_hedge_quantity(call, put)

        futures_expiry = self.resolver.expiry.relative(
            underlying_id=self.underlying_id[0],
            as_of_time=self.last_pulse,
            period_type=PeriodType.MONTH,
            instrument_type=InstrumentType.FUTURE,
            nth=1,
            period_id=PeriodID.ALL,
            min_dte=self._get_instrument_dte(call),
        )[0]

        self.broker.create_order(
            self.pulse_index,
            Future(
                underlying_id=self.underlying_id[0],
                expiration_date=futures_expiry,
            ),
            hedge_quantity,
            tags=["hedge"],
            is_lots=True,
        )

    def _rebalance_hedge(self) -> None:
        """Rebalance the existing futures trade in-place to the new target quantity."""
        strangle_trades = self.get_trades_by_tags(["strangle"])
        hedge_trades = self.get_trades_by_tags(["hedge"])
        if not strangle_trades or not hedge_trades:
            return

        call_instrument = strangle_trades[0].instrument
        put_instrument = strangle_trades[1].instrument
        hedge_quantity = self._calculate_hedge_quantity(call_instrument, put_instrument)
        hedge_trades[0].rebalance(hedge_quantity)

    def on_update(self) -> None:
        if self._should_roll():
            self._roll_strangle()
        else:
            self._rebalance_hedge()
```

## Running the Backtest

We initialise the strategy on **Brent Crude (COM.BRN)** with:

| Parameter | Value | Meaning |
| - | - | - |
| `forward_expiry` | 1 | use the 1st eligible monthly expiry |
| `call_delta` | 0.20 | sell the 20-delta call |
| `put_delta` | 0.20 | sell the 20-delta put |
| `min_dte` | 30 | roll when DTE falls below 30 days |
| `lots` | 10 | 10 contract lots per leg (`is_lots=True`) |

`run_sequentially` wires up the datafeed, resolver, broker, and portfolio, then drives the strategy day-by-day through the full history.

```python theme={null}
strategy = DeltaHedgedShortStrangle(
    underlying_id="COM.BRN",
    forward_expiry=1,
    call_delta=0.20,
    put_delta=0.20,
    min_dte=30,
    lots=10,
)

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

print(f"Strategy completed in {result.execution_time:.2f}s")
```

```text Output theme={null}
Strategy completed in 3.90s
```

## Performance Metrics

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

```text Output theme={null}
Strategy Metrics:
Start Date: 				2015-02-02 00:00:00
End Date: 				2026-06-02 00:00:00
Duration: 				4139 days, 0:00:00
***********************************************************
Total Return (%): 			20.72
CAGR (%): 				1.67
***********************************************************
Start Equity ($): 			1000000.00
End Equity ($): 			1207173.54
Diff ($): 				207173.54
***********************************************************
Annualized Sharpe Ratio: 		0.37
Calmar Ratio: 				0.00
Annualized Sortino Ratio: 		0.44
***********************************************************
Daily Mean Return (%): 			0.01
Daily Volatility annualized (%): 	0.28
Best Daily Return (%): 			1.73
Best Day Date: 				2020-04-22 00:00:00
Worst Daily Return (%): 		-4.16
Worst Day Date: 			2021-11-26 00:00:00
***********************************************************
Monthly Mean Return (%): 		0.15
Monthly Volatility annualized (%): 	4.37
Best Monthly Return (%): 		3.59
Best Month Date: 			2021-12
Worst Monthly Return (%): 		-5.38
Worst Month Date: 			2022-03
MTD Return (%): 			0.23
3-Month Return (%): 			4.17
Positive Months (%): 			67.65
Average Up Month (%): 			0.73
Average Down Month (%): 		-1.08
***********************************************************
6-Month Return (%): 			-1.19
Year-to-Date Return (%): 		-1.19
1-Year Return (%): 			1.54
Yearly Mean Return (%): 		1.76
Yearly Volatility annualized (%): 	2.70
… (32 more lines)
```

## Equity Curve

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

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

## Inspecting Trades

Every completed trade is stored in `strategy.trades`. Each trade records its instrument, quantity, open/close prices, and final P\&L.

```python theme={null}
# Show the last 10 closed trades
strategy.trades[-10:]
```

```text Output theme={null}
[<Trade entry: 2026-02-25 00:00:00; exit: 2026-03-30 00:00:00; Instrument: <Future: COM.BRN, Type: InstrumentType.FUTURE, Strike: None, Expiration: 2026-04-30 00:00:00>; Quantity: 7.6098690843906525; PnL: 15752.429004688707; Cummulative PnL: 134106.7197239916>,
 <Trade entry: 2026-03-30 00:00:00; exit: 2026-04-27 00:00:00; Instrument: <Option: COM.BRN, Type: InstrumentType.CALL, Strike: 158.0, Expiration: 2026-05-26 00:00:00>; Quantity: -10; PnL: 2370.8075376794022; Cummulative PnL: 30888.51878719616>,
 <Trade entry: 2026-03-30 00:00:00; exit: 2026-04-27 00:00:00; Instrument: <Option: COM.BRN, Type: InstrumentType.PUT, Strike: 82.0, Expiration: 2026-05-26 00:00:00>; Quantity: -10; PnL: 5377.435843640264; Cummulative PnL: 33155.646244778116>,
 <Trade entry: 2026-03-30 00:00:00; exit: 2026-04-27 00:00:00; Instrument: <Future: COM.BRN, Type: InstrumentType.FUTURE, Strike: None, Expiration: 2026-05-29 00:00:00>; Quantity: -0.5753231826943761; PnL: -1472.8273476976042; Cummulative PnL: -27244.166554545733>,
 <Trade entry: 2026-04-27 00:00:00; exit: 2026-05-27 00:00:00; Instrument: <Option: COM.BRN, Type: InstrumentType.CALL, Strike: 132.0, Expiration: 2026-06-25 00:00:00>; Quantity: -10; PnL: 3786.2131135037735; Cummulative PnL: 23043.986620373034>,
 <Trade entry: 2026-04-27 00:00:00; exit: 2026-05-27 00:00:00; Instrument: <Option: COM.BRN, Type: InstrumentType.PUT, Strike: 83.0, Expiration: 2026-06-25 00:00:00>; Quantity: -10; PnL: -3641.004827454566; Cummulative PnL: 8924.096096342777>,
 <Trade entry: 2026-04-27 00:00:00; exit: 2026-05-27 00:00:00; Instrument: <Future: COM.BRN, Type: InstrumentType.FUTURE, Strike: None, Expiration: 2026-06-30 00:00:00>; Quantity: -0.630536367207668; PnL: 2786.9707430578937; Cummulative PnL: -20277.9194942373>,
 <Trade entry: 2026-05-27 00:00:00; exit: None; Instrument: <Option: COM.BRN, Type: InstrumentType.CALL, Strike: 116.0, Expiration: 2026-07-28 00:00:00>; Quantity: -10; PnL: -865.1432818023964; Cummulative PnL: -4897.703500166753>,
 <Trade entry: 2026-05-27 00:00:00; exit: None; Instrument: <Option: COM.BRN, Type: InstrumentType.PUT, Strike: 78.0, Expiration: 2026-07-28 00:00:00>; Quantity: -10; PnL: 2936.4677091375847; Cummulative PnL: 11534.371491772717>,
 <Trade entry: 2026-05-27 00:00:00; exit: None; Instrument: <Future: COM.BRN, Type: InstrumentType.FUTURE, Strike: None, Expiration: 2026-07-31 00:00:00>; Quantity: 0.9653320415026201; PnL: 728.0656410824074; Cummulative PnL: -289.0908655004414>]
```

## Comparing Hedged vs. Unhedged

To see how much the delta hedge matters, we can run both variants side-by-side.

The unhedged version is identical except `_delta_hedge` is never called - achieved simply by subclassing and overriding `on_update`.

```python theme={null}
class UnhedgedShortStrangle(DeltaHedgedShortStrangle):
    """Strangle-only variant - no futures delta hedge."""

    def on_update(self) -> None:
        if self._should_roll():
            self._roll_strangle()


hedged = DeltaHedgedShortStrangle(
    underlying_id="COM.BRN",
    forward_expiry=1,
    call_delta=0.20,
    put_delta=0.20,
    min_dte=30,
    lots=10,
)

unhedged = UnhedgedShortStrangle(
    underlying_id="COM.BRN",
    forward_expiry=1,
    call_delta=0.20,
    put_delta=0.20,
    min_dte=30,
    lots=10,
)
unhedged.name = "Unhedged Short Strangle (20d Call / 20d Put)"

results = run_sequentially(
    [hedged, unhedged],
    initial_equity=1_000_000,
)

for r in results:
    print(f"{r.strategy.name}: OK")
```

```text Output theme={null}
Delta-Hedged Short Strangle (20d Call / 20d Put): OK
Unhedged Short Strangle (20d Call / 20d Put): OK
```

```python theme={null}
import plotly.graph_objects as go

fig = go.Figure()

for r in results:
    fig.add_trace(
        go.Scatter(
            x=r.strategy.portfolio.datetimes,
            y=r.strategy.portfolio.equity_history,
            mode="lines",
            name=r.strategy.name,
        )
    )

fig.update_layout(
    title="Hedged vs Unhedged Short Strangle - Equity Curves",
    xaxis_title="Date",
    yaxis_title="Equity ($)",
    legend_title="Strategy",
    template="allasso",
)
fig
```

![Chart output 2](https://mintcdn.com/allasso/5PMuHlzYzX1FYPYw/images/pulse/notebooks/delta-hedged-strangle-2.png?fit=max\&auto=format\&n=5PMuHlzYzX1FYPYw\&q=85\&s=c4617170fa4db013ee87d6a47ef7a954)

## Inspecting the Hedge

We can visualise how the delta hedge tracked the strangle's net delta across the first strangle cycle.
The three trades of the first cycle are call (index 0), put (index 1), and hedge (index 2).

```python theme={null}
import numpy as np
from plotly.subplots import make_subplots

datafeed = create_local_datafeed()

call_trade = strategy.trades[0]
put_trade  = strategy.trades[1]
hedge_trade = strategy.trades[2]

close_datetime = call_trade.close_datetime
# `history` takes a row count, one row per snapshot at or before `as_of_time`.
pulse_count = len(call_trade.datetimes)

call_history = datafeed.instrument.history(
    call_trade.instrument, as_of_time=close_datetime, count=pulse_count
)
put_history = datafeed.instrument.history(
    put_trade.instrument, as_of_time=close_datetime, count=pulse_count
)

call_delta_contract = np.array(call_history.delta) * call_trade.quantity
put_delta_contract  = np.array(put_history.delta)  * put_trade.quantity

fig = make_subplots(
    rows=2, cols=1,
    shared_xaxes=True,
    vertical_spacing=0.1,
    subplot_titles=("Portfolio Delta vs Hedge Quantity", "Absolute PnL"),
)

fig.add_trace(go.Scatter(x=call_history.as_of_time, y=call_delta_contract,
                          mode="lines+markers", name="Call Delta (contract)"), row=1, col=1)
fig.add_trace(go.Scatter(x=put_history.as_of_time,  y=put_delta_contract,
                          mode="lines+markers", name="Put Delta (contract)"),  row=1, col=1)
fig.add_trace(go.Scatter(x=hedge_trade.datetimes,    y=hedge_trade.quantity_history,
                          mode="lines+markers", name="Hedge Quantity"),         row=1, col=1)

fig.add_trace(go.Scatter(x=call_trade.datetimes,  y=call_trade.abs_pnl_history,
                          mode="lines+markers", name="Call PnL"),  row=2, col=1)
fig.add_trace(go.Scatter(x=put_trade.datetimes,   y=put_trade.abs_pnl_history,
                          mode="lines+markers", name="Put PnL"),   row=2, col=1)
fig.add_trace(go.Scatter(x=hedge_trade.datetimes, y=hedge_trade.abs_pnl_history,
                          mode="lines+markers", name="Hedge PnL"), row=2, col=1)

fig.update_layout(
    title="Strangle Delta Hedging: First Cycle",
    legend_title="Legend",
    template="allasso",
    height=800,
)
fig.update_yaxes(title_text="Delta / Quantity", row=1, col=1)
fig.update_yaxes(title_text="Absolute PnL ($)", row=2, col=1)
fig.show()
```

![Chart output 3](https://mintcdn.com/allasso/5PMuHlzYzX1FYPYw/images/pulse/notebooks/delta-hedged-strangle-3.png?fit=max\&auto=format\&n=5PMuHlzYzX1FYPYw\&q=85\&s=cabec2acaccad679e47f61ebf47f0ec5)


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