Equity Options

Handling Data

Introduction

LEAN passes the data you request to the OnDataon_data method so you can make trading decisions. The default OnDataon_data method accepts a Slice object, but you can define additional OnDataon_data methods that accept different data types. For example, if you define an OnDataon_data method that accepts a TradeBar argument, it only receives TradeBar objects. The Slice object that the OnDataon_data method receives groups all the data together at a single moment in time. To access the Slice outside of the OnDataon_data method, use the CurrentSlicecurrent_slice property of your algorithm.

All the data formats use DataDictionary objects to group data by Symbol and provide easy access to information. The plural of the type denotes the collection of objects. For instance, the TradeBars DataDictionary is made up of TradeBar objects. To access individual data points in the dictionary, you can index the dictionary with the contract ticker or Symbolsymbol, but we recommend you use the Symbolsymbol.

To view the resolutions that are available for Equity Options data, see Resolutions.

Trades

TradeBar objects are price bars that consolidate individual trades from the exchanges. They contain the open, high, low, close, and volume of trading activity over a period of time.

Tradebar decomposition

To get the TradeBar objects in the Slice, index the Slice or index the Barsbars property of the Slice with the contract Symbolsymbol. If the contract doesn't actively trade or you are in the same time step as when you added the contract subscription, the Slice may not contain data for your Symbolsymbol. To avoid issues, check if the Slice contains data for your contract before you index the Slice with the contract Symbolsymbol.

public override void OnData(Slice slice)
{
    // Check if the symbol is contained in TradeBars object
    if (slice.Bars.ContainsKey(_contractSymbol))
    {
        // Obtain the mapped TradeBar of the symbol
        var tradeBar = slice.Bars[_contractSymbol];
    }
}
def on_data(self, slice: Slice) -> None:
    # Obtain the mapped TradeBar of the symbol if any
    trade_bar = slice.bars.get(self._contract_symbol)   # None if not found

You can also iterate through the TradeBars dictionary. The keys of the dictionary are the Symbol objects and the values are the TradeBar objects.

public override void OnData(Slice slice)
{
    // Iterate all received Symbol-TradeBar key-value pairs
    foreach (var kvp in slice.Bars)
    {
        var symbol = kvp.Key;
        var tradeBar = kvp.Value;
        var closePrice = tradeBar.Close;
    }
}
def on_data(self, slice: Slice) -> None:
    # Iterate all received Symbol-TradeBar key-value pairs
    for symbol, trade_bar in slice.bars.items():
        close_price = trade_bar.close

TradeBar objects have the following properties:

Quotes

QuoteBar objects are bars that consolidate NBBO quotes from the exchanges. They contain the open, high, low, and close prices of the bid and ask. The Openopen, Highhigh, Lowlow, and Closeclose properties of the QuoteBar object are the mean of the respective bid and ask prices. If the bid or ask portion of the QuoteBar has no data, the Openopen, Highhigh, Lowlow, and Closeclose properties of the QuoteBar copy the values of either the Bidbid or Askask instead of taking their mean.

Quotebar decomposition

To get the QuoteBar objects in the Slice, index the QuoteBars property of the Slice with the contract Symbolsymbol. If the contract doesn't actively get quotes or you are in the same time step as when you added the contract subscription, the Slice may not contain data for your Symbolsymbol. To avoid issues, check if the Slice contains data for your contract before you index the Slice with the contract Symbolsymbol.

public override void OnData(Slice slice)
{
    // Check if the symbol is contained in QuoteBars object
    if (slice.QuoteBars.ContainsKey(_contractSymbol))
    {
        // Obtain the mapped QuoteBar of the symbol
        var quoteBar = slice.QuoteBars[_contractSymbol];
    }
}
def on_data(self, slice: Slice) -> None:
    # Obtain the mapped QuoteBar of the symbol if any
    quote_bar = slice.quote_bars.get(self._contract_symbol)   # None if not found

You can also iterate through the QuoteBars dictionary. The keys of the dictionary are the Symbol objects and the values are the QuoteBar objects.

public override void OnData(Slice slice)
{
    // Iterate all received Symbol-QuoteBar key-value pairs
    foreach (var kvp in slice.QuoteBars)
    {
        var symbol = kvp.Key;
        var quoteBar = kvp.Value;
        var askPrice = quoteBar.Ask.Close;
    }
}
def on_data(self, slice: Slice) -> None:
    # Iterate all received Symbol-QuoteBar key-value pairs
    for symbol, quote_bar in slice.quote_bars.items():
        ask_price = quote_bar.ask.close

QuoteBar objects let LEAN incorporate spread costs into your simulated trade fills to make backtest results more realistic.

QuoteBar objects have the following properties:

Option Chains

OptionChain objects represent an entire chain of Option contracts for a single underlying security.

To get the OptionChain, index the OptionChainsoption_chains property of the Slice with the canonical Symbol.

public override void OnData(Slice slice)
{
    // Try to get the OptionChain using the canonical symbol
    if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        // Get all contracts if the OptionChain contains any member
        var contracts = chain.Contracts;
    }
}
def on_data(self, slice: Slice) -> None:
    # Try to get the OptionChain using the canonical symbol (None if no OptionChain return)
    chain = slice.option_chains.get(self._contract_symbol.Canonical)
    if chain:
        # Get all contracts if the OptionChain contains any member
        contracts = chain.contracts

You can also loop through the OptionChainsoption_chains property to get each OptionChain.

public override void OnData(Slice slice)
{
    // Iterate all received Canonical Symbol-OptionChain key-value pairs
    foreach (var kvp in slice.OptionChains)
    {
        var canonicalSymbol = kvp.Key;
        var chain = kvp.Value;
        var contracts = chain.Contracts;
    }
}
def on_data(self, slice: Slice) -> None:
    # Iterate all received Canonical Symbol-OptionChain key-value pairs
    for canonical_symbol, chain in slice.option_chains.items():
        contracts = chain.contracts

OptionChain objects have the following properties:

Option Contracts

OptionContract objects represent the data of a single Option contract in the market. To get the Option contracts in the Slice, use the Contractscontracts property of the OptionChain.

public override void OnData(Slice slice)
{
    // Try to get the OptionChain using the canonical symbol
    if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        // Get individual contract data
        if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
        {
            var price = contract.Price;
        }
    }
}
def on_data(self, slice: Slice) -> None:
    # Try to get the OptionChain using the canonical symbol
    chain = slice.option_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            price = contract.price

Greeks and Implied Volatility

To get the Greeks and implied volatility of an Option contract, use the Greeksgreeks and implied_volatility members.

public override void OnData(Slice slice)
{
    // Try to get the OptionChain using the canonical symbol
    if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        // Get individual contract data
        if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
        {
            // Get greeks data of the selected contract
            var delta = contract.Greeks.Delta;
            var iv = contract.ImpliedVolatility;
        }
    }
}
def on_data(self, slice: Slice) -> None:
    # Try to get the OptionChain using the canonical symbol
    chain = slice.option_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            # Get greeks data of the selected contract
            delta = contract.greeks.delta
            iv = contract.implied_volatility

LEAN only calculates Greeks and implied volatility when you request them because they are expensive operations. If you invoke the Greeksgreeks property, the Greeks aren't calculated. However, if you invoke the Greeks.Deltagreeks.delta, LEAN calculates the delta. To avoid unecessary computation in your algorithm, only request the Greeks and implied volatility when you need them. For more information about the Greeks and implied volatility, see Options Pricing.

Open Interest

Open interest is the number of outstanding contracts that haven't been settled. It provides a measure of investor interest and the market liquidity, so it's a popular metric to use for contract selection. Open interest is calculated once per day. To get the latest open interest value, use the OpenInterestopen_interest property of the Option or OptionContractoption_contract.

public override void OnData(Slice slice)
{
    // Try to get the OptionChains using the canonical symbol
    if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        // Get individual contract data
        if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
        {
            // Get the open interest of the selected contracts
            var openInterest = contract.OpenInterest;
        }
    }
}

public void OnData(OptionChains optionChains)
{
    // Try to get the OptionChains using the canonical symbol
    if (optionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        // Get individual contract data
        if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
        {
            // Get the open interest of the selected contracts
            var openInterest = contract.OpenInterest;
        }
    }
}
def on_data(self, slice: Slice) -> None:
    # Try to get the option_chains using the canonical symbol
    chain = slice.option_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            # Get the open interest of the selected contracts
            open_interest = contract.open_interest

Properties

OptionContract objects have the following properties:

Examples

Example 1: Get Mid Price For Individual Contracts

This example shows how to handle QuoteBar data for shortlisted Equity Option contracts to calculate mid price using bid close and ask close data, while filter individual option contracts and request data using OptionChain self.option_chain method for the contracts that expires within the current week. Using mid price, we can examine the market fair value of the Option and compare with model theoretical price.

public class EquityOptionHandlingDataAlgorithm : QCAlgorithm
{
    private Symbol _spy;
    private List<Symbol> _contracts = new();
        
    public override void Initialize()
    {
        SetStartDate(2024, 9, 1);
        SetEndDate(2024, 9, 30);
        
        // Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        Settings.SeedInitialPrices = true;
        // Subscribe to underlying data for ATM calculation using the update underlying price.
        // Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        _spy = AddEquity("SPY", dataNormalizationMode: DataNormalizationMode.Raw).Symbol;

        // Update the tradable contracts daily before market open since the option contract list provider populate them daily.
        Schedule.On(
            DateRules.EveryDay(_spy),
            TimeRules.At(9, 0),
            UpdateContracts
        );
    }

    private void UpdateContracts()
    {
        // Get all contracts that expiring this week to trade with, subscribe to data for trading need.
        _contracts = OptionChain(_spy)
            .Where(x => x.ID.Date <= Expiry.EndOfWeek(Time))
            .Select(x => AddOptionContract(x).Symbol)
            .ToList();
    }

    public override void OnData(Slice slice)
    {
        // Only focus on filtered list of option contracts to trade.
        foreach (var contract in _contracts)
        {
            // Mid price can only be calculated when quote bar data is available.
            if (slice.QuoteBars.TryGetValue(contract, out var quote))
            {
                if (quote.Bid != null && quote.Ask != null)
                {
                    // Mid price = average of bid close price and ask close price.
                    var midPrice = (quote.Bid.Close + quote.Ask.Close) * 0.5m;
                }
            }
        }
    }
}
class EquityOptionHandlingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 9, 30)

        self.contracts = []

        # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        self.settings.seed_initial_prices = True
        # Subscribe to underlying data for ATM calculation using the update underlying price.
        # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        self.spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
    
        # Update the tradable contracts daily before market open since the option contract list provider populate them daily.
        self.schedule.on(
            self.date_rules.every_day(self.spy),
            self.time_rules.at(9, 0),
            self.update_contracts
        )

    def update_contracts(self) -> None:
        # Get all contracts that expiring this week to trade with, subscribe to data for trading need.
        contracts = self.option_chain(self.spy)
        self.contracts = [self.add_option_contract(x).symbol for x in contracts
            if x.id.date < Expiry.end_of_week(self.time)]
    
    def on_data(self, slice: Slice) -> None:
        # Only focus on filtered list of option contracts to trade.
        for contract in self.contracts:
            # Mid price can only be calculated when quote bar data is available.
            quote = slice.quote_bars.get(contract)
            if quote and quote.bid is not None and quote.ask is not None:
                # Mid price = average of bid close price and ask close price.
                mid_price = (quote.bid.close + quote.ask.close) * 0.5

Example 2: Get Mid Price For Universe

This example shows how to handle QuoteBar data for shortlisted Equity Option contracts to calculate mid price using bid close and ask close data, while request data through universe selection function using SetFilter set_filter method for the contracts that expires within the current week. Using mid price, we can examine the market fair value of the Option and compare with model theoretical price.

public class EquityOptionHandlingDataAlgorithm : QCAlgorithm
{
    private Symbol _symbol;
        
    public override void Initialize()
    {
        SetStartDate(2024, 9, 1);
        SetEndDate(2024, 9, 30);

        // Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        Settings.SeedInitialPrices = true;
        // Subscribe to underlying data for ATM calculation using the update underlying price.
        // Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        var spy = AddEquity("SPY", dataNormalizationMode: DataNormalizationMode.Raw).Symbol;
        // Subscribe to SPY option data.
        var option = AddOption(spy);
        _symbol = option.Symbol;
        // We wish to only trade the contracts expiring within the same week since they have the highest volume.
        option.SetFilter((u) => u.Contracts((x) => x.Where(s => s.ID.Date <= Expiry.EndOfWeek(Time))));
    }

    public override void OnData(Slice slice)
    {
        // Only want to obtain the option chain of the selected symbol.
        if (slice.OptionChains.TryGetValue(_symbol, out var chain))
        {
            foreach (var contract in chain)
            {
                // Mid price = average of bid close price and ask close price.
                var midPrice = (contract.BidPrice + contract.AskPrice) * 0.5m;
            }
        }
    }
}
class EquityOptionHandlingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 9, 30)

        # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        self.settings.seed_initial_prices = True
        # Subscribe to underlying data for ATM calculation using the update underlying price.
        # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
        # Subscribe to SPY option data.
        option = self.add_option(spy)
        self._symbol = option.symbol
        # We wish to only trade the contracts expiring within the same week since they have the highest volume.
        option.set_filter(lambda u: u.contracts(lambda x: [s for s in x if s.id.date <= Expiry.end_of_week(self.time)]))
    
    def on_data(self, slice: Slice) -> None:
        # Only want to obtain the option chain of the selected symbol.
        chain = slice.option_chains.get(self._symbol)
        if not chain:
            return
    
        for contract in chain:
            # Mid price = average of bid close price and ask close price
            mid_price = (contract.bid_price + contract.ask_price) * 0.5

Example 3: Get Instant Delta

The option greeks change rapidly, so we need to obtain the instant greeks to accurately calculate the hedge size for arbitration or replication portfolio. You can call the Greeks property from the OptionChain data to access various greeks. In this example, we will demonstrate how to obtain the contract with delta closest to 0.4 among all call contracts expiring the same week.

public class EquityOptionHandlingDataAlgorithm : QCAlgorithm
{
    private Symbol _symbol;
        
    public override void Initialize()
    {
        SetStartDate(2024, 9, 5);
        SetEndDate(2024, 9, 5);

        // Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        Settings.SeedInitialPrices = true;
        // Subscribe to underlying data for ATM calculation using the update underlying price.
        // Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        var spy = AddEquity("SPY", dataNormalizationMode: DataNormalizationMode.Raw).Symbol;
        // Subscribe to SPY option data.
        var option = AddOption(spy);
        _symbol = option.Symbol;
        // We wish to only trade the contracts expiring within the same week since they have the highest volume.
        // 0.4 Delta will only appear in call contracts.
        option.SetFilter((u) => u.Delta(0.2m, 0.6m).Contracts((x) => x.Where(s => s.ID.Date <= Expiry.EndOfWeek(Time))));
    }

    public override void OnData(Slice slice)
    {
        // Only want to obtain the option chain of the selected symbol.
        if (slice.OptionChains.TryGetValue(_symbol, out var chain))
        {
            // Get the contract with Delta closest to 0.4 to trade.
            // The arbitary delta criterion might be set due to hedging need or risk adjustment.
            var selected = chain.OrderBy(x => Math.Abs(x.Greeks.Delta - 0.4m)).First();
        }
    }
}
class EquityOptionHandlingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 5)
        self.set_end_date(2024, 9, 5)
        
        # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        self.settings.seed_initial_prices = True
        # Subscribe to underlying data for ATM calculation using the update underlying price.
        # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
        # Subscribe to SPY option data.
        option = self.add_option(spy)
        self._symbol = option.symbol
        # We wish to only trade the contracts expiring within the same week since they have the highest volume.
        # 0.4 Delta will only appear in call contracts.
        option.set_filter(lambda u: u.delta(0.2, 0.6).contracts(lambda x: [s for s in x if s.id.date <= Expiry.end_of_week(self.time)]))
    
    def on_data(self, slice: Slice) -> None:
        # Only want to obtain the option chain of the selected symbol.
        chain = slice.option_chains.get(self._symbol)
        if not chain:
            return
    
        # Get the contract with Delta closest to 0.4 to trade.
        # The arbitary delta criterion might be set due to hedging need or risk adjustment.
        selected = sorted(chain, key=lambda x: abs(x.greeks.delta - 0.4))[0]

Example 4: Delta-Hedged Short Straddle

This example demonstrates a delta-hedged short straddle strategy that sells an at-the-money (ATM) straddle with 7-30 days to expiration and continuously neutralizes the portfolio delta using the underlying shares. The StraddleSelector helper class picks the farthest expiry within the DTE range and the strike closest to the spot price. On each slice, the combined Option delta is accumulated from the OptionChain and the net portfolio delta is computed by adding the underlying position. The DeltaHedger helper enforces a minimum share threshold and a rehedge band to avoid over-trading, and applies a time delay between successive hedges. A Scheduled Event closes the straddle on expiration day and assignment events are handled to keep the underlying position clean.

public class DeltaHedgedStraddleAlgorithm : QCAlgorithm
{
    private Equity _spy;
    private Symbol _canonicalOption;
    private OptionStrategy _shortStraddle;
    private StraddleSelector _straddleSelector;
    private DeltaHedger _hedger;
    private decimal _straddleWeight = 0.5m, _delta = 0m;
    private DateTime? _exitDay;

    public override void Initialize()
    {
        SetStartDate(2024, 9, 1);
        SetEndDate(2024, 12, 31);
        SetCash(1_000_000);
        Settings.SeedInitialPrices = true;
        _spy = AddEquity("SPY", dataNormalizationMode: DataNormalizationMode.Raw);
        // Initialize the straddle selector with 7-30 day DTE range.
        _straddleSelector = new StraddleSelector(minDte: 7, maxDte: 30);
        // Initialize the delta hedger with 30 share minimum, 20 share rehedge band, and 4 hour delay.
        _hedger = new DeltaHedger(30, 20, TimeSpan.FromHours(4));
        _canonicalOption = QuantConnect.Symbol.CreateCanonicalOption(_spy.Symbol);
        // Schedule the rebalance method to run 30 minutes after market open.
        Schedule.On(
            DateRules.EveryDay(_spy.Symbol),
            TimeRules.AfterMarketOpen(_spy.Symbol, 30),
            Rebalance
        );
        // Schedule the close expiring method to run 60 minutes before market close.
        Schedule.On(
            DateRules.EveryDay(_spy.Symbol),
            TimeRules.BeforeMarketClose(_spy.Symbol, 60),
            CloseExpiring
        );
        SetWarmUp(TimeSpan.FromDays(45));
    }

    public override void OnData(Slice slice)
    {
        if (IsWarmingUp || !slice.Bars.Any()) return;
        if (!slice.OptionChains.TryGetValue(_canonicalOption, out var chain) || _shortStraddle == null) return;

        // Accumulate the delta from all option legs in the straddle.
        foreach (var leg in _shortStraddle.OptionLegs)
        {
            if (chain.Contracts.TryGetValue(leg.Symbol, out var contract))
            {
                _delta += contract.Greeks.Delta;
            }
        }
        // Calculate the net portfolio delta including underlying and options.
        var netDelta = _hedger.ComputeNetDelta(this, _shortStraddle.OptionLegs, _spy.Holdings.Quantity, _delta);
        // Reset the delta accumulator for the next iteration.
        _delta = 0m;
        // Exit if it's not time to hedge or net delta is zero.
        if (!(_hedger.ShouldHedge(Time) && netDelta != 0)) return;
        // Calculate the hedge quantity needed to neutralize delta.
        var hedgeQty = _hedger.GetQuantity(netDelta);
        if (hedgeQty.HasValue)
        {
            MarketOrder(_spy.Symbol, hedgeQty.Value, tag: $"Daily delta hedge ({netDelta:F2} share delta)");
            // Record the hedge operation with timestamp and delta.
            _hedger.RecordHedge(Time, netDelta);
            // Update the net delta after the hedge.
            netDelta += hedgeQty.Value;
        }
        Plot("Portfolio Delta", "Delta", netDelta);
    }

    private void Rebalance()
    {
        if (IsWarmingUp || Portfolio.Invested) return;
        var chain = OptionChain(_spy.Symbol);
        if (!chain.Any()) return;
        // Use the straddle selector to find the best ATM straddle.
        var result = _straddleSelector.Select(chain, _spy.Price, Time.Date);
        if (result == null) return;
        _delta = result.Value.Delta;
        _shortStraddle = OptionStrategies.ShortStraddle(_canonicalOption, result.Value.Strike, result.Value.Expiry);
        // Calculate the number of contracts based on portfolio value and weight.
        var qty = (int)(Portfolio.TotalPortfolioValue * _straddleWeight / (_spy.Price * 100m));
        if (qty > 0)
            Buy(_shortStraddle, qty, tag: $"Sell ATM straddle exp {result.Value.Expiry:d}");
        _hedger.Reset();
        _exitDay = result.Value.Expiry.Date;
    }

    private void CloseExpiring()
    {
        if (_shortStraddle == null || !_exitDay.HasValue || Time.Date < _exitDay.Value) return;
        // Liquidate all positions before expiration.
        Liquidate(tag: "Expiry hedge liquidation");
    }

    public override void OnOrderEvent(OrderEvent orderEvent)
    {
        // Handle option assignment events.
        if (orderEvent.Status == OrderStatus.Filled && orderEvent.IsAssignment)
        {
            // Liquidate all option legs of the straddle.
            foreach (var leg in _shortStraddle.OptionLegs)
            {
                Liquidate(leg.Symbol, tag: "Assignment liquidation");
            }
            // Determine the direction based on whether it's a call or put assignment.
            var direction = Securities[orderEvent.Symbol].Symbol.ID.OptionRight == OptionRight.Call ? 1 : -1;
            MarketOrder(_spy.Symbol, -_spy.Holdings.Quantity + orderEvent.FillQuantity * direction * 100);
            _shortStraddle = null;
        }
    }
}

public class StraddleSelector
{
    private readonly int _minDte, _maxDte;

    public StraddleSelector(int minDte, int maxDte)
    {
        // Store the minimum days to expiration for contract selection.
        _minDte = minDte;
        // Store the maximum days to expiration for contract selection.
        _maxDte = maxDte;
    }

    public (decimal Delta, DateTime Expiry, decimal Strike)? Select(IEnumerable<OptionContract> chain, decimal spotPrice, DateTime currentDate)
    {
        // Filter contracts to those within the specified DTE range.
        var contracts = chain.Where(c =>
        {
            var dte = (c.Expiry.Date - currentDate).Days;
            return dte >= _minDte && dte <= _maxDte;
        }).ToList();
        if (!contracts.Any()) return null;
        // Select the farthest expiration date from the filtered contracts.
        var expiry = contracts.Max(c => c.Expiry);
        // Filter to only contracts with the selected expiration.
        contracts = contracts.Where(c => c.Expiry == expiry).ToList();
        // Find the strike price closest to the current spot price.
        var strike = contracts.OrderBy(c => Math.Abs(c.Strike - spotPrice)).First().Strike;
        // Filter to only contracts with the selected strike.
        contracts = contracts.Where(c => c.Strike == strike).ToList();
        // Ensure we have both call and put for a straddle.
        if (contracts.Count < 2) return null;
        // Return the combined delta, expiry, and strike for the straddle.
        return (contracts.Sum(c => c.Greeks.Delta), expiry, strike);
    }
}

public class DeltaHedger
{
    private readonly int _minShares, _rehedgeBand;
    private readonly TimeSpan _hedgeDelay;
    private DateTime _nextHedgeTime;
    private decimal? _lastHedgedDelta;

    public DeltaHedger(int minShares, int rehedgeBand, TimeSpan hedgeDelay)
    {
        // Store the minimum number of shares required to execute a hedge.
        _minShares = minShares;
        // Store the rehedge band threshold to prevent excessive hedging.
        _rehedgeBand = rehedgeBand;
        // Store the time delay between hedging operations.
        _hedgeDelay = hedgeDelay;
        Reset();
    }

    public void Reset()
    {
        _nextHedgeTime = DateTime.MinValue;
        _lastHedgedDelta = null;
    }

    public bool ShouldHedge(DateTime currentTime)
    {
        // Check if enough time has passed since the last hedge.
        return currentTime >= _nextHedgeTime;
    }

    public decimal ComputeNetDelta(QCAlgorithm algorithm, IEnumerable<Leg> legs, decimal underlyingQuantity, decimal contractDelta)
    {
        // Calculate the net portfolio delta by combining underlying and option positions.
        return underlyingQuantity + legs.Sum(leg =>
            algorithm.Securities[leg.Symbol].Holdings.Quantity * contractDelta * 100);
    }

    public int? GetQuantity(decimal netDelta)
    {
        if (_lastHedgedDelta.HasValue
            && Math.Abs(netDelta - _lastHedgedDelta.Value) < _rehedgeBand
            && Math.Abs(netDelta) < _minShares + _rehedgeBand)
        {
            return null;
        }
        // Calculate the required hedge quantity to neutralize the net delta.
        var hedgeQty = (int)Math.Round(-netDelta);
        if (Math.Abs(hedgeQty) < _minShares) return null;
        // Return the calculated hedge quantity.
        return hedgeQty;
    }

    public void RecordHedge(DateTime currentTime, decimal netDelta)
    {
        // Record the delta value after this hedge operation.
        _lastHedgedDelta = netDelta;
        // Set the next allowed hedge time based on the configured delay.
        _nextHedgeTime = currentTime + _hedgeDelay;
    }
}
class DeltaHedgedStraddleAlgo(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(1_000_000)
        self.settings.seed_initial_prices = True
        self._spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW)
        # Initialize the straddle selector with 7-30 day DTE range.
        self._straddle_selector = StraddleSelector(min_dte=7, max_dte=30)
        # Initialize the delta hedger with 30 share minimum, 20 share rehedge band, and 4 hour delay.
        self._hedger = DeltaHedger(30, 20, timedelta(hours=4))
        self._canonical_option = Symbol.create_canonical_option(self._spy)
        # Set the straddle position size to 50% of portfolio value.
        self._straddle_weight = 0.5
        self._short_straddle = None
        self._exit_day = None
        # Schedule the rebalance method to run 30 minutes after market open.
        self.schedule.on(
            self.date_rules.every_day(self._spy),
            self.time_rules.after_market_open(self._spy, 30),
            self._rebalance
        )
        # Schedule the close expiring method to run 60 minutes before market close.
        self.schedule.on(
            self.date_rules.every_day(self._spy),
            self.time_rules.before_market_close(self._spy, 60),
            self._close_expiring
        )
        self.set_warm_up(timedelta(45))

    def on_data(self, data):
        if self.is_warming_up or not data.bars:
            return
        chain = data.option_chains.get(self._canonical_option)
        if not chain or not self._short_straddle:
            return
        # Accumulate the delta from all option legs in the straddle.
        for leg in self._short_straddle.option_legs:
            contract = chain.contracts.get(leg.symbol)
            if contract:
                self._delta += contract.greeks.delta
        # Calculate the net portfolio delta including underlying and options.
        net_delta = self._hedger.compute_net_delta(self, self._short_straddle.option_legs, self._spy.holdings.quantity, self._delta)
        # Reset the delta accumulator for the next iteration.
        self._delta = 0
        # Exit if it's not time to hedge or net delta is zero.
        if not (self._hedger.should_hedge(self.time) and net_delta):
            return
        # Calculate the hedge quantity needed to neutralize delta.
        hedge_qty = self._hedger.get_quantity(net_delta)
        if hedge_qty:
            self.market_order(self._spy, hedge_qty, tag=f"Daily delta hedge ({net_delta:.2f} share delta)")
            # Record the hedge operation with timestamp and delta.
            self._hedger.record_hedge(self.time, net_delta)
            # Update the net delta after the hedge.
            net_delta += hedge_qty
        self.plot("Portfolio Delta", "Delta", net_delta)

    def _rebalance(self):
        if self.is_warming_up or self.portfolio.invested:
            return
        chain = self.option_chain(self._spy)
        if not chain:
            return
        # Use the straddle selector to find the best ATM straddle.
        result = self._straddle_selector.select(chain, self._spy.price, self.time.date())
        if not result:
            return
        self._delta, expiry, strike = result
        self._short_straddle = OptionStrategies.short_straddle(self._canonical_option, strike, expiry)
        # Calculate the number of contracts based on portfolio value and weight.
        qty = int(self.portfolio.total_portfolio_value * self._straddle_weight / (self._spy.price * 100.0))
        if qty:
            self.buy(self._short_straddle, qty, tag=f"Sell ATM straddle exp {expiry.date()}")
        self._hedger.reset()
        self._exit_day = expiry.date()

    def _close_expiring(self):
        if not self._short_straddle or not self._exit_day or self.time.date() < self._exit_day:
            return
        # Liquidate all positions before expiration.
        self.liquidate(tag="Expiry hedge liquidation")

    def on_order_event(self, order_event):
        # Handle option assignment events.
        if order_event.status == OrderStatus.FILLED and order_event.is_assignment:
            # Liquidate all option legs of the straddle.
            for leg in self._short_straddle.option_legs:
                self.liquidate(leg.symbol, tag="Assignment liquidation")
            # Determine the direction based on whether it's a call or put assignment.
            direction = 1 if self.securities[order_event.symbol].right == OptionRight.CALL else -1
            self.market_order(self._spy, -self._spy.holdings.quantity + order_event.quantity * direction * 100)
            self._short_straddle = None


class StraddleSelector:

    def __init__(self, min_dte, max_dte):
        # Store the minimum days to expiration for contract selection.
        self._min_dte = min_dte
        # Store the maximum days to expiration for contract selection.
        self._max_dte = max_dte

    def select(self, chain, spot_price, current_date):
        # Filter contracts to those within the specified DTE range.
        contracts = [
            contract for contract in chain
            if self._min_dte <= (contract.expiry.date() - current_date).days <= self._max_dte
        ]
        if not contracts:
            return
        # Select the farthest expiration date from the filtered contracts.
        expiry = max(contract.expiry for contract in contracts)
        # Filter to only contracts with the selected expiration.
        contracts = [contract for contract in contracts if contract.expiry == expiry]
        # Find the strike price closest to the current spot price.
        strike = min(contracts, key=lambda c: abs(c.strike - spot_price)).strike
        # Filter to only contracts with the selected strike.
        contracts = [contract for contract in contracts if contract.strike == strike]
        # Ensure we have both call and put for a straddle.
        if len(contracts) < 2:
            return
        # Return the combined delta, expiry, and strike for the straddle.
        return sum(contract.greeks.delta for contract in contracts), expiry, strike


class DeltaHedger:

    def __init__(self, min_shares, rehedge_band, hedge_delay):
        # Store the minimum number of shares required to execute a hedge.
        self._min_shares = min_shares
        # Store the rehedge band threshold to prevent excessive hedging.
        self._rehedge_band = rehedge_band
        # Store the time delay between hedging operations.
        self._hedge_delay = hedge_delay
        self.reset()

    def reset(self):
        self._next_hedge_time = datetime.min
        self._last_hedged_delta = None

    def should_hedge(self, current_time):
        # Check if enough time has passed since the last hedge.
        return current_time >= self._next_hedge_time

    def compute_net_delta(self, algorithm, legs, underlying_quantity, contract_delta):
        # Calculate the net portfolio delta by combining underlying and option positions.
        return underlying_quantity + sum(
            algorithm.securities[leg.symbol].holdings.quantity * contract_delta * 100
            for leg in legs
        )

    def get_quantity(self, net_delta):
        if (
            self._last_hedged_delta is not None
            and abs(net_delta - self._last_hedged_delta) < self._rehedge_band
            and abs(net_delta) < self._min_shares + self._rehedge_band
        ):
            return
        # Calculate the required hedge quantity to neutralize the net delta.
        hedge_qty = int(round(-net_delta))
        if abs(hedge_qty) < self._min_shares:
            return
        # Return the calculated hedge quantity.
        return hedge_qty

    def record_hedge(self, current_time, net_delta):
        # Record the delta value after this hedge operation.
        self._last_hedged_delta = net_delta
        # Set the next allowed hedge time based on the configured delay.
        self._next_hedge_time = current_time + self._hedge_delay

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: