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

# Per-Pulse Greeks on Trade and Portfolio

> This notebook demonstrates the per-pulse greek tracking on Trade and Portfolio.

This notebook demonstrates the per-pulse greek tracking on `Trade` and `Portfolio`. We run a delta-hedged short ATM straddle on `COM.BRN` so we can see both code paths in action: option greeks from `OptionValues` and the future fallback (`delta=1`, `gamma=theta=vega=0`).

```python theme={null}
# Pulse reads its data directory from the PDC_PATH environment variable, which has to be set
# before `import pulse` runs (for example `export PDC_PATH=/path/to/prepared/data`).
```

## Imports

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

from pulse import (
    Option,
    Future,
    InstrumentType,
    PeriodID,
    PeriodType,
    Strategy,
    run_sequentially,
    create_local_components,
)
from pulse.charts import plot_equity
```

## Strategy

A minimal delta-hedged short ATM straddle. Each month it opens an ATM call + ATM put (short), then on every pulse it hedges the net delta with a front-month future (opens or rebalances).

```python theme={null}
class DeltaHedgedShortStraddle(Strategy):
    def __init__(
        self,
        underlying_id: str,
        expiry_nearest: int = 1,
        min_dte: int = 30,
        units: int = 1_000,
    ):
        super().__init__(
            name=f"{underlying_id} Delta-Hedged Short ATM Straddle",
            description="Short ATM straddle with daily future delta hedge.",
            underlying_id=underlying_id,
        )
        self._expiry_nearest = expiry_nearest
        self._min_dte = min_dte
        self._units = abs(units)
        self._previous_month = None

    def _enter_straddle(self) -> None:
        underlying = self.underlying_id[0]
        expiration_date = self.resolver.expiry.relative(
            underlying_id=underlying,
            as_of_time=self.last_pulse,
            period_type=PeriodType.MONTH,
            instrument_type=InstrumentType.CALL,
            nth=self._expiry_nearest,
            period_id=PeriodID.ALL,
            min_dte=self._min_dte,
        )[0]
        strike = self.resolver.strike.moneyness.resolve(
            underlying_id=underlying,
            as_of_time=self.last_pulse,
            expiration_date=expiration_date,
            strike_value=1.0,
            instrument_type=InstrumentType.CALL,
        )
        call = Option(
            underlying_id=underlying,
            instrument_type=InstrumentType.CALL,
            strike=strike,
            expiration_date=expiration_date,
        )
        put = Option(
            underlying_id=underlying,
            instrument_type=InstrumentType.PUT,
            strike=strike,
            expiration_date=expiration_date,
        )
        self.broker.create_order(self.pulse_index, instrument=call, quantity=-self._units, tags=["straddle", "call"])
        self.broker.create_order(self.pulse_index, instrument=put, quantity=-self._units, tags=["straddle", "put"])

    def _hedge(self) -> None:
        calls = self.get_trades_by_tags(["call"])
        puts = self.get_trades_by_tags(["put"])
        if not calls or not puts:
            # Options have expired or been closed - close any orphan future hedge
            self.close_trades_by_tags(["hedge"])
            return

        call_trade, put_trade = calls[0], puts[0]
        call_values = self.datafeed.instrument.last(call_trade.instrument, self.last_pulse)
        put_values = self.datafeed.instrument.last(put_trade.instrument, self.last_pulse)
        net_delta = call_values.delta * call_trade.quantity + put_values.delta * put_trade.quantity
        hedge_quantity = -net_delta if net_delta != 0 else 1e-8

        existing = self.get_trades_by_tags(["hedge"])
        if existing:
            existing[0].rebalance(hedge_quantity)
            return

        future_expiration = 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._min_dte,
        )[0]
        future_instr = Future(
            underlying_id=self.underlying_id[0],
            expiration_date=future_expiration,
        )
        self.broker.create_order(
            self.pulse_index,
            instrument=future_instr,
            quantity=hedge_quantity,
            tags=["hedge"],
        )

    def on_update(self) -> None:
        if self._previous_month != self.last_pulse.month:
            self.close_all()
            self._enter_straddle()
            self._previous_month = self.last_pulse.month
        if self.has_open_trades:
            self._hedge()
```

## Run

```python theme={null}
strategy = DeltaHedgedShortStraddle(
    underlying_id="COM.BRN",
    expiry_nearest=1,
    min_dte=7,
    units=1_000,
)
datafeed, resolver = create_local_components()
result = run_sequentially(
    [strategy],
    initial_equity=1_000_000,
    datafeed=datafeed,
    resolver=resolver,
)[0]

n_dates = len(result.strategy.portfolio.datetimes)
print(f"Strategy run completed in {result.execution_time:.2f}s, {n_dates} pulses, {len(result.strategy.trades)} trades.")
```

```text Output theme={null}
Strategy run failed: COM.BRN|p|90.0|2007-11-12 00:00:00 not found in snapshot 2007-11-02 00:00:00 after filtering by expiration date 2007-11-12 00:00:00, strike 90.0 and type p
```

## Equity

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

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

## Portfolio-level greeks per pulse

The portfolio keeps no greek aggregate, so the book's exposure is built from the trades: each trade's `*_contract_history` runs in lock-step with its own `datetimes`, and summing them per pulse gives the net position. Delta should oscillate near zero if the hedge is working; gamma/theta/vega come from the option legs only.

```python theme={null}
from collections import defaultdict

book = {greek: defaultdict(float) for greek in ("delta", "gamma", "theta", "vega")}
for trade in result.strategy.trades:
    for greek in book:
        for ts, value in zip(trade.datetimes, getattr(trade, f"{greek}_contract_history")):
            book[greek][ts] += value
datetimes = sorted(book["delta"])

fig = make_subplots(
    rows=2, cols=2,
    shared_xaxes=True,
    subplot_titles=("Total Delta", "Total Gamma", "Total Theta", "Total Vega"),
    vertical_spacing=0.1,
)
for (row, col), greek in zip(((1, 1), (1, 2), (2, 1), (2, 2)), book):
    fig.add_trace(go.Scatter(x=datetimes, y=[book[greek][ts] for ts in datetimes], name=greek), row=row, col=col)
fig.update_layout(title="Portfolio greeks over time", template="allasso", height=700, showlegend=False)
fig.show()
```

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

## Per-trade greeks (option leg)

Pick the first call leg and plot its per-unit and size-multiplied greek histories. Per-unit delta should sit in `[-1, 0]` for a short call; `delta_contract = delta * units` should track the same shape, scaled by quantity.

```python theme={null}
call_trades = [t for t in result.strategy.trades if t.instrument.instrument_type == InstrumentType.CALL]
trade = call_trades[0]
print(f"Trade: {trade.instrument.id} qty={trade.quantity} pulses={len(trade.datetimes)}")

fig = make_subplots(
    rows=2, cols=1,
    shared_xaxes=True,
    subplot_titles=("Delta (per-unit vs contract)", "Gamma / Theta / Vega (per-unit)"),
    vertical_spacing=0.12,
)
fig.add_trace(go.Scatter(x=trade.datetimes, y=trade.delta_history, name="delta (per-unit)"), row=1, col=1)
fig.add_trace(go.Scatter(x=trade.datetimes, y=trade.delta_contract_history, name="delta_contract", yaxis="y2"), row=1, col=1)
fig.add_trace(go.Scatter(x=trade.datetimes, y=trade.gamma_history, name="gamma"), row=2, col=1)
fig.add_trace(go.Scatter(x=trade.datetimes, y=trade.theta_history, name="theta"), row=2, col=1)
fig.add_trace(go.Scatter(x=trade.datetimes, y=trade.vega_history, name="vega"), row=2, col=1)
fig.update_layout(title=f"Trade greeks: {trade.instrument.instrument_type.value} {trade.instrument.strike}", template="allasso", height=700)
fig.show()
```

```text Output theme={null}
Trade: COM.BRN|c|71.0|2007-09-10 00:00:00 qty=-1000 pulses=6
```

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

## Per-leg greeks across the backtest

Stitch every trade's history together by leg type (call / put / future). The three legs should roughly offset: the call and put are short with opposite-signed deltas, and the future hedge brings the sum near zero each pulse. Gamma/theta/vega come from the option legs only - the future contributes zero by construction.

```python theme={null}
LEG_STYLE = {
    InstrumentType.CALL: ("call", "#1f77b4"),
    InstrumentType.PUT: ("put", "#d62728"),
    InstrumentType.FUTURE: ("future hedge", "#2ca02c"),
}

fig = make_subplots(
    rows=4, cols=1,
    shared_xaxes=True,
    subplot_titles=("Delta (contract)", "Gamma (contract)", "Theta (contract)", "Vega (contract)"),
    vertical_spacing=0.05,
)

seen = set()
for t in result.strategy.trades:
    name, color = LEG_STYLE[t.instrument.instrument_type]
    show = name not in seen
    seen.add(name)
    base = dict(x=t.datetimes, mode="lines", line=dict(color=color), legendgroup=name, name=name)
    fig.add_trace(go.Scatter(y=t.delta_contract_history, showlegend=show, **base), row=1, col=1)
    fig.add_trace(go.Scatter(y=t.gamma_contract_history, showlegend=False, **base), row=2, col=1)
    fig.add_trace(go.Scatter(y=t.theta_contract_history, showlegend=False, **base), row=3, col=1)
    fig.add_trace(go.Scatter(y=t.vega_contract_history, showlegend=False, **base), row=4, col=1)

fig.update_layout(title="Per-leg greeks (size-multiplied)", template="allasso", height=900)
fig.show()
```

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

## Future hedge: quantity and units

Each hedge trade is a future, and futures are not traded in lots here (`is_lots=False`), so `units == quantity`. The plot below shows how the hedge size evolves - it gets rebalanced every pulse to offset the option legs' net delta, and a new future is opened each month when the previous one is closed at the monthly reset.

```python theme={null}
future_trades = [t for t in result.strategy.trades if t.instrument.instrument_type == InstrumentType.FUTURE]
print(f"Future trades: {len(future_trades)}")
print()
for t in future_trades[:3]:
    print(f"  is_lots={t.is_lots}  quantity={t.quantity:.2f}  units={t.units:.2f}  pulses={len(t.datetimes)}")

fig = go.Figure()
for i, t in enumerate(future_trades):
    fig.add_trace(go.Scatter(
        x=t.datetimes,
        y=t.quantity_history,
        mode="lines",
        line=dict(color="#2ca02c"),
        showlegend=(i == 0),
        name="hedge quantity",
        legendgroup="hedge",
    ))
fig.update_layout(title="Future hedge quantity (= units, since is_lots=False)", xaxis_title="date", yaxis_title="contracts", template="allasso", height=400)
fig.show()
```

```text Output theme={null}
Future trades: 3

  is_lots=False  quantity=640.81  units=640.81  pulses=5
  is_lots=False  quantity=0.00  units=0.00  pulses=6
  is_lots=False  quantity=0.00  units=0.00  pulses=9
```

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


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