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

# Fees: Short Put Strategy

> This notebook demonstrates the per-pulse batched fees feature.

We run a short-put strategy twice - once **without fees** (the default) and once with a **percentage-of-notional** fee - then visualise:

1. Per-pulse fees over time (bar chart)
2. Cumulative fees over time (line chart)
3. Equity curves with and without fees (overlay)

Setup: `pulse` must be importable and `PDC_PATH` must point at the prepared market data before `import pulse` runs.

## Imports

```python theme={null}
from pulse import Strategy, run_sequentially, DataFeed, InstrumentType
from pulse.charts import (
    plot_cumulative_fees,
    plot_equity,
    plot_fee_impact_on_equity,
    plot_pulse_fees_history,
)
from pulse.core.fees import FeeCalculator, FeeEvent, PercentageFeeCalculator
```

## Strategy

Reuses the `NakedOption` short-put strategy from tests/functional/test\_short\_put\_strategy.py. On every pulse where no trade is open it enters a front-month option at the configured delta, by resolving the front-month expiry/strike via `self.resolver` and calling `self.buy(...)`.

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


class NakedOption(Strategy):
    def __init__(
        self,
        underlying_id: str,
        side: Literal["long", "short"],
        option_type: Literal["call", "put"],
        delta: float,
        expiry_nearest: int,
        min_dte: int,
        quantity: int = 2,
        is_lots: bool = False,
    ):
        super().__init__(
            underlying_id=underlying_id,
            name=f"{side.capitalize()} {option_type.capitalize()} {delta} Delta {underlying_id}",
            description=f"Naked {side} {option_type} option strategy with {delta} delta on {underlying_id}",
        )
        self.delta = delta
        self.expiry_nearest = expiry_nearest
        self.min_dte = min_dte
        self.option_type: Literal["call", "put"] = option_type
        self.quantity = quantity
        self.is_lots = is_lots

    def on_update(self):
        if not self.has_open_trades:
            instrument_type = InstrumentType.from_object(self.option_type)
            expiration_date = self.resolver.expiry.relative(
                underlying_id=self.underlying_id[0],
                as_of_time=self.last_pulse,
                period_type="month",
                instrument_type=instrument_type,
                nth=1,
                min_dte=1,
            )[0]
            strike = self.resolver.strike.delta.resolve(
                underlying_id=self.underlying_id[0],
                as_of_time=self.last_pulse,
                instrument_type=instrument_type,
                strike_value=self.delta,
                expiration_date=expiration_date,
            )
            self.buy(
                underlying_id=self.underlying_id[0],
                instrument_type=instrument_type,
                expiration_date=expiration_date,
                strike=strike,
                quantity=self.quantity,
                is_lots=self.is_lots,
            )
```

## Configuration

Tweak these values to see how the fee rate affects equity. `FEE_RATE` is applied to **notional** (`|quantity_units| * |price|`) on every entry / rebalance / exit event.

```python theme={null}
UNDERLYING_ID = "CRY.BTCUSD.DER_1h"
INITIAL_EQUITY = 1_000_000
FEE_RATE = 0.01  # 1% of notional per transaction event
```

## Run without fees (baseline)

With no `fee_calculator` argument, `run_sequentially` defaults to `NoFeeCalculator()` and `portfolio.total_fees` stays at zero.

```python theme={null}
strategy_no_fees = NakedOption(
    underlying_id=UNDERLYING_ID,
    side="short",
    option_type="put",
    delta=0.25,
    expiry_nearest=1,
    min_dte=10,
    quantity=-2,
)

result_no_fees = run_sequentially(
    [strategy_no_fees],
    initial_equity=INITIAL_EQUITY,
)[0]

print(f"Baseline run completed in {result_no_fees.execution_time:.2f}s")
```

```text Output theme={null}
Baseline run completed in 2.25s
```

## Run with `PercentageFeeCalculator`

Pass a fee calculator via the new `fee_calculator` kwarg. The portfolio now records every entry / rebalance / exit as a `FeeEvent`, drains them in a single batched `FeeCalculator.calculate(events, datafeed)` call per pulse, and deducts the total from equity at the end of the pulse.

```python theme={null}
strategy_with_fees = NakedOption(
    underlying_id=UNDERLYING_ID,
    side="short",
    option_type="put",
    delta=0.25,
    expiry_nearest=1,
    min_dte=10,
    quantity=-2,
)

result_with_fees = run_sequentially(
    [strategy_with_fees],
    initial_equity=INITIAL_EQUITY,
    fee_calculator=PercentageFeeCalculator(rate=FEE_RATE),
)[0]

print(f"Fees run completed in {result_with_fees.execution_time:.2f}s")
```

```text Output theme={null}
Fees run completed in 2.12s
```

## Summary

```python theme={null}
pf_no_fees = result_no_fees.strategy.portfolio
pf_with_fees = result_with_fees.strategy.portfolio

fee_drag = pf_no_fees.current_equity - pf_with_fees.current_equity
print(f"Total fees charged:        {pf_with_fees.total_fees:>14,.2f}")
print(f"Final equity (no fees):    {pf_no_fees.current_equity:>14,.2f}")
print(f"Final equity (with fees):  {pf_with_fees.current_equity:>14,.2f}")
print(f"Fee drag on final equity:  {fee_drag:>14,.2f}")
```

```text Output theme={null}
Total fees charged:              2,800.69
Final equity (no fees):        962,576.32
Final equity (with fees):      959,775.62
Fee drag on final equity:        2,800.69
```

## Fee stats from `Stats`

The summary above pokes at `portfolio.total_fees` directly. The same numbers - and a few extras - are also available as a structured sub-object on `Stats`, alongside the existing Sharpe / drawdown / trade stats:

* `total_fees` - cumulative fees charged across the run
* `fee_drag_pct` - `total_fees / initial_equity` (the headline drag number)
* `avg_fee_per_trade` - fees averaged across `trade_stats.position_count`
* `fees_pct_of_gross_pnl` - fees as a share of gross alpha magnitude (≥100% means fees swallowed gross PnL)
* `max_pulse_fees` + `max_pulse_fees_datetime` - the single largest fee spike and when it happened

```python theme={null}
fee_stats = result_with_fees.strategy.stats.fee_stats
assert fee_stats is not None  # populated by run_sequentially via Stats.from_strategy

print(f"total_fees:               {fee_stats.total_fees:>14,.2f}")
print(f"fee_drag_pct:             {fee_stats.fee_drag_pct:>14.4%}")
print(f"avg_fee_per_trade:        {fee_stats.avg_fee_per_trade:>14,.2f}")
print(f"fees_pct_of_gross_pnl:    {fee_stats.fees_pct_of_gross_pnl:>14.4%}")
print(f"max_pulse_fees:           {fee_stats.max_pulse_fees:>14,.2f}")
print(f"max_pulse_fees_datetime:  {fee_stats.max_pulse_fees_datetime}")
```

```text Output theme={null}
total_fees:                     2,800.69
fee_drag_pct:                    0.2801%
avg_fee_per_trade:                 48.29
fees_pct_of_gross_pnl:           7.4837%
max_pulse_fees:                   322.36
max_pulse_fees_datetime:  2025-02-28 08:00:00
```

## Chart 1 - Per-pulse fees

`portfolio.pulse_fees_history` is aligned 1:1 with `portfolio.datetimes`. Spikes correspond to pulses where a trade was opened, rebalanced, or closed.

```python theme={null}
plot_pulse_fees_history(result_with_fees.strategy)
```

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

## Chart 2 - Cumulative fees

Running sum of `pulse_fees_history`. The terminal value equals `portfolio.total_fees`.

```python theme={null}
plot_cumulative_fees(result_with_fees.strategy)
```

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

## Chart 3 - Equity: with vs without fees

The no-fee curve is synthesised from a single strategy run as `initial_equity + cumsum(pulse_total_pnl_history)` - `pulse_total_pnl_history` is the *gross* (pre-fee) per-pulse PnL, so adding it back gives the equity the strategy would have had without any fee charges. The gap between the two curves at the end equals `portfolio.total_fees`.

```python theme={null}
plot_fee_impact_on_equity(result_with_fees.strategy)
```

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

## Custom example: minimum-fee floor

Both built-in calculators (`FixedFeeCalculator`, `PercentageFeeCalculator`) treat every event the same way. For anything more interesting - broker commissions, exchange tiers, block-trade pricing - subclass `FeeCalculator` directly.

Subclasses implement a single method:

```python theme={null}
def calculate(self, events: list[FeeEvent], datafeed: DataFeed) -> list[float]:
    ...
```

It receives every entry / rebalance / exit event collected this pulse and returns one non-negative fee per event in the same order. Each `FeeEvent` carries:

* `trade` - the `Trade` being transacted
* `quantity_units` - signed quantity in units (lots already expanded)
* `price` - fill price of the transaction
* `event_type` - `FeeEventType.ENTRY`, `REBALANCE`, or `EXIT`

Below we implement a broker-style **minimum-fee floor**: charge `max(floor, rate × |quantity_units| × |price|)` per event. This is how Interactive Brokers (USD 1.00 floor) and tastytrade structure their options commissions - the floor binds for small trades, and percentage-of-notional dominates once the trade is large enough.

```python theme={null}
class MinFloorFeeCalculator(FeeCalculator):
    """Charge ``max(floor, rate * |quantity_units| * |price|)`` per event."""

    def __init__(self, floor: float, rate: float):
        if floor < 0 or rate < 0:
            raise ValueError("floor and rate must be non-negative")
        self._floor = floor
        self._rate = rate

    def calculate(self, events: list[FeeEvent], datafeed: DataFeed) -> list[float]:
        return [
            max(self._floor, self._rate * abs(e.quantity_units) * abs(e.price))
            for e in events
        ]
```

### Run the strategy with the custom calculator

Same `NakedOption` short-put, same period - only the fee scheme changes. At `FLOOR=$5` and `RATE=0.1%`, the floor binds on pulses where premium × quantity is small (below \~\$5,000 notional), and the percentage component takes over for larger ones.

```python theme={null}
FLOOR_FEE = 5.0  # USD per transaction event
FLOOR_RATE = 0.001  # 0.1% of notional above the floor

strategy_floor = NakedOption(
    underlying_id=UNDERLYING_ID,
    side="short",
    option_type="put",
    delta=0.25,
    expiry_nearest=1,
    min_dte=10,
    quantity=2,
)

result_floor = run_sequentially(
    [strategy_floor],
    initial_equity=INITIAL_EQUITY,
    fee_calculator=MinFloorFeeCalculator(floor=FLOOR_FEE, rate=FLOOR_RATE),
)[0]

floor_fee_stats = result_floor.strategy.stats.fee_stats
assert floor_fee_stats is not None

delta_total = floor_fee_stats.total_fees - fee_stats.total_fees
print(f"Custom (min-floor) total_fees:  {floor_fee_stats.total_fees:>14,.2f}")
print(f"Percentage         total_fees:  {fee_stats.total_fees:>14,.2f}")
print(f"Δ total_fees:                   {delta_total:>14,.2f}")
```

```text Output theme={null}
Custom (min-floor) total_fees:          654.34
Percentage         total_fees:        2,800.69
Δ total_fees:                        -2,146.35
```

### Visualise the floor in action

The per-pulse bar chart makes the floor-vs-rate behaviour visually obvious - bars cluster at the floor amount on small-premium pulses and rise above it on large-premium pulses.

```python theme={null}
plot_pulse_fees_history(result_floor.strategy)
```

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


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