NexusTrade guides

Backtest SPY options spreads in Python

Backtest a SPY bull put credit spread and a bear put debit spread on a $2,000 account with the NexusTrade Python SDK, then read the equity curve and every fill.

As of 2026-11-20

Explore more topics

TL;DR

Define each spread with open_option and close_option, submit both backtests with generate_events=True, then read statistics from the result, the equity curve from get_backtest_history and every fill from list_backtest_events. Contracts are sized from each spread's maximum loss, so 5% of a $2,000 account risks about $100 per trade. From March 2022 through 2025 the bull put spread lost 35.16% and the bear put spread lost 48.33% while SPY gained 66.41%. These are worked examples of the workflow, not strategies to trade.

Both spreads against SPY, March 2022 to December 2025

Portfolio value (USD)

Bull put credit spreadBear put debit spreadFull-capital SPY buy and holdHistorical simulation
$1,500
$2,000
$2,500
$3,000
Recorded backtests, $2,000 starting capital
Bull put credit spread 2025-12-31, 21:00:00 UTC
$1,296.78
Bear put debit spread 2025-12-31, 21:00:00 UTC
$1,033.40
Full-capital SPY buy and hold 2025-12-31, 21:00:00 UTC
$3,328.14
2022-03-072023202420252025-12-31

Bull put credit spread: 36.47% largest decline in plotted observations. 2022-03-28, 20:00:00 UTC ($2,025.41) to 2025-06-02, 20:00:00 UTC ($1,286.83).

Bull put return
-35.16%
Bear put return
-48.33%
SPY return
66.41%
Show the table · 7 rows, 4 columns

Scroll sideways to compare all columns. Select a heading to sort.

Return-35.16%-48.33%66.41%
Sharpe ratio-1.28-1.350.81
Sortino ratio-1.55-1.821.16
Maximum drawdown36.47%48.47%23.84%
Spreads traded7163n/a
Total commissions$192.40$163.80$0.00
Peak capital at risk$88.00$98.87n/a

Both portfolios ran on November 20, 2026 with the code below: daily data from 2022-03-07 through 2025-12-31, $2,000 starting capital, $0.65 commission per contract and the default fill halfway between the midpoint and the historical bid or ask.

SPY invests the whole $2,000 and pays no commissions. Each spread portfolio had at most about $100 at risk at once, so the comparison shows the cost of the strategy, not two equal bets.

Install and authenticate

The equity curve and fill reads need NexusTrade Python SDK 5.4.0 or later. Create an API key at nexustrade.io/developers. These shell commands prompt for it without displaying it.

Shell
python3 -m pip install --upgrade "nexustrade>=5.4.0"
printf 'NexusTrade API key: '
read -rs NEXUSTRADE_API_KEY
export NEXUSTRADE_API_KEY
printf '\n'

Define both spreads and submit the backtests

A credit vertical uses direction "short" and a debit vertical uses "long" in the spread filters. Each portfolio opens one spread when none is held and closes it at a profit target, a loss limit or 7 days before expiration. Swap "put" for "call" to build the call-side versions.

generate_events=True records every order so you can read the fills later. It costs 5 times the research tokens of a plain run, and the events are kept for 3 days.

Python
import nexustrade as nt

client = nt.NexusTradeClient.from_environment()


def put_leg(direction, dollars_below):
    return nt.leg(
        option_type="put",
        direction=direction,              # "short" sells the leg, "long" buys it
        min_days_to_expiration=30,
        max_days_to_expiration=45,
        distance=dollars_below,           # snaps to the nearest listed strike
        distance_type="dollars",
    )


def open_vertical(direction, legs):
    # Open a spread only when none is held. Contracts are sized from the
    # spread's max loss, so 5% of the portfolio is the risk per trade.
    return nt.strategy(
        f"Open SPY {direction} put vertical",
        nt.OptionSpreadCount("SPY", "put", direction, "vertical") < nt.Value(1),
        nt.open_option(
            builder=nt.options_builder(underlying_symbol="SPY", spread_type="vertical", legs=legs),
            allocation={"type": "percent of portfolio", "amount": 5},
        ),
    )


def close_vertical(direction, take_profit, stop_loss):
    return nt.strategy(
        f"Close SPY {direction} put verticals",
        nt.always(),
        nt.close_option(
            underlyings=["SPY"], option_type="put", direction=direction, spread_type="vertical",
            triggers=[
                nt.pnl_trigger(min_pnl_percent=take_profit),
                nt.pnl_trigger(max_pnl_percent=stop_loss),
                nt.dte_trigger(max_dte=7),
            ],
        ),
    )


# Bull put credit spread: sell the put about $5 below SPY, buy the one about $6 below.
bull_put = nt.portfolio("SPY bull put credit spread", [
    open_vertical("short", [put_leg("short", 5), put_leg("long", 6)]),
    close_vertical("short", take_profit=50, stop_loss=-100),
], initial_value=2_000)

# Bear put debit spread: buy the put about $1 below SPY, sell the one about $3 below.
bear_put = nt.portfolio("SPY bear put debit spread", [
    open_vertical("long", [put_leg("long", 1), put_leg("short", 3)]),
    close_vertical("long", take_profit=50, stop_loss=-50),
], initial_value=2_000)

operations = client.create_backtests(
    [
        nt.backtest(book, start_date="2022-03-07", end_date="2025-12-31", generate_events=True)
        for book in (bull_put, bear_put)
    ],
    idempotency_key="spy-put-spreads-v1",
)
results = client.wait_for_backtests(operations, timeout_seconds=1800)
for finished in results:
    result = finished["result"]
    stats = result["statistics"]
    print(result["backtestId"], stats["percentChange"], stats["sharpeRatio"],
          stats["maxDrawdown"], stats["totalFees"])

Read the equity curve

get_backtest_history returns up to 5,000 points per page with the portfolio value, cash, position value, the SPY comparison and the collateral locked at each tick. Follow nextPage until it is None. The bull put run returned 2,938 points, two per trading day. Per-tick history is kept for 30 days after a run.

Python
backtest_id = results[0]["result"]["backtestId"]

curve, page = [], 1
while page is not None:
    batch = client.get_backtest_history(backtest_id, page=page, page_size=5000)
    curve += batch["points"]   # time, value, cash, positionValue, comparisonValue, reservedCollateral
    page = batch["nextPage"]

print(len(curve), curve[0]["value"], curve[-1]["value"])

Read every fill and pair entries with exits

list_backtest_events returns 50 events per page. Each filled order carries the contract symbol, strike, expiration, side, quantity, filledAtPrice per share, filledAtTime, fees and positionEffect. Legs of one spread share a multiLegGroupId, and a closing order's targetSpreadId names the spread it closed.

The bull put run filled 284 legs: 71 spreads opened and 71 closed. Their summed cash flows come to -$703.22, which matches the curve's fall from $2,000.00 to $1,296.78.

Python
fills, page = [], 1
while True:
    batch = client.list_backtest_events(
        backtest_id, event_types=["Order"], order_statuses=["Filled"], page=page, page_size=50,
    )
    fills += [row["event"] for row in batch["events"]]
    if not batch["hasMore"]:
        break
    page += 1

# Group legs into spreads, then pair each opening spread with the close that names it.
spreads = {}
for leg in fills:
    spreads.setdefault(leg["multiLegGroupId"], []).append(leg)
opens = {gid: legs for gid, legs in spreads.items() if legs[0]["positionEffect"] == "open"}
closes = {legs[0]["targetSpreadId"]: legs for legs in spreads.values() if legs[0]["positionEffect"] == "close"}


def cash_flow(legs):
    return sum(
        (leg["filledAtPrice"] if leg["side"] == "Sell" else -leg["filledAtPrice"]) * 100 * leg["quantity"]
        - leg["fees"]
        for leg in legs
    )


trades = [(opens[gid][0]["filledAtTime"], cash_flow(opens[gid]) + cash_flow(closes[gid]))
          for gid in opens if gid in closes]
print(len(trades), "round trips, total P&L", round(sum(pnl for _, pnl in trades), 2))

One winning and one losing trade

  1. 2024-01-11 14:32

    Contract

    SPY240216P00473000

    Action

    Sell to open

    Contracts

    1

    Price per share

    $4.0624

    Fee

    $0.65

  2. 2024-01-11 14:32

    Contract

    SPY240216P00472000

    Action

    Buy to open

    Contracts

    1

    Price per share

    $3.7852

    Fee

    $0.65

  3. 2024-01-23 20:59

    Contract

    SPY240216P00473000

    Action

    Buy to close

    Contracts

    1

    Price per share

    $1.5750

    Fee

    $0.65

  4. 2024-01-23 20:59

    Contract

    SPY240216P00472000

    Action

    Sell to close

    Contracts

    1

    Price per share

    $1.4525

    Fee

    $0.65

  5. 2024-07-08 13:32

    Contract

    SPY240809P00551000

    Action

    Sell to open

    Contracts

    1

    Price per share

    $4.3262

    Fee

    $0.65

  6. 2024-07-08 13:32

    Contract

    SPY240809P00550000

    Action

    Buy to open

    Contracts

    1

    Price per share

    $4.0826

    Fee

    $0.65

  7. 2024-07-25 13:32

    Contract

    SPY240809P00551000

    Action

    Buy to close

    Contracts

    1

    Price per share

    $12.1075

    Fee

    $0.65

  8. 2024-07-25 13:32

    Contract

    SPY240809P00550000

    Action

    Sell to close

    Contracts

    1

    Price per share

    $11.2250

    Fee

    $0.65

Recorded rows in source order; spacing does not represent elapsed time.

Show the table · 8 rows, 6 columns

Scroll sideways to compare all columns. Select a heading to sort.

2024-01-11 14:32SPY240216P00473000Sell to open1$4.0624$0.65
2024-01-11 14:32SPY240216P00472000Buy to open1$3.7852$0.65
2024-01-23 20:59SPY240216P00473000Buy to close1$1.5750$0.65
2024-01-23 20:59SPY240216P00472000Sell to close1$1.4525$0.65
2024-07-08 13:32SPY240809P00551000Sell to open1$4.3262$0.65
2024-07-08 13:32SPY240809P00550000Buy to open1$4.0826$0.65
2024-07-25 13:32SPY240809P00551000Buy to close1$12.1075$0.65
2024-07-25 13:32SPY240809P00550000Sell to close1$11.2250$0.65

On January 11, 2024 the bull put portfolio sold the February 16 473 put for $4.0624 and bought the 472 put for $3.7852, a credit of $27.72. It closed on January 23 for a debit of $12.25. After four $0.65 commissions the trade made $12.86 at the engine's unrounded prices ($12.87 from the rounded prices in the table).

On July 8, 2024 it collected $24.36 on the August 9 551/550 spread. SPY fell, and the spread closed on July 25 for $88.25. After commissions the trade lost $66.49, about five winning trades' worth.

Size a small account before you run it

At 5% risk, a $2,000 account can lose about $100 on each spread. That fits $1-wide SPY spreads. A wider spread's maximum loss exceeds the allocation, so it sizes to zero contracts and never trades. Check peakReservedCollateral in the statistics to see how much was actually at risk.

Commissions matter at this size. The bull put portfolio paid $192.40 over four years, nearly 10% of its starting capital. Change the rate with fee_config={"Option": {"type": "dollars", "amount": 0.5}} on nt.backtest. Set fee_config={"OptionSlippageFraction": 0} to fill at the midpoint or 1 to fill at the ask when buying and the bid when selling; the default is 0.5.

Daily option backtests start in March 2022. The API rejected a January 2022 start for this portfolio and named 2022-03-07 as the earliest supported date.

Run the same test in Aurora

Aurora builds the same two portfolios from a description, shows the rules for review and runs both backtests. Use this when you want the result without writing code.

Next steps

Continue exploring

Discussion

Sign in or create a free account to join the discussion.

No comments yet.

Aurora · AI research assistant

Try this in Aurora

Edit the request, then open it in Aurora. You choose when to send it.