Datasets

Futures Options

Introduction

This page explains how to request, manipulate, and visualize historical Future Options data.

Prerequisites

Working knowledge of C#.

Working knowedge of Python and pandas. If you are not familiar with pandas, see the pandas documentation.

Create Subscriptions

Follow these steps to subscribe to a Future security:

  1. Load the required assembly files and data types.
  2. #load "../Initialize.csx"
    #load "../QuantConnect.csx"
    
    using QuantConnect;
    using QuantConnect.Data;
    using QuantConnect.Data.Market;
    using QuantConnect.Algorithm;
    using QuantConnect.Securities;
    using QuantConnect.Securities.Future;
    using QuantConnect.Research;
  3. Create a QuantBook.
  4. var qb = new QuantBook();
    qb = QuantBook()
  5. Call the AddFuture method with a ticker and resolution.
  6. var future = qb.AddFuture(Futures.Indices.SP500EMini, Resolution.Minute);
    future = qb.AddFuture(Futures.Indices.SP500EMini, Resolution.Minute)

    If you do not pass a resolution argument, Resolution.Minute is used by default.

  7. (Optional) Call the SetFilter method with a specified expiration range value.
  8. future.SetFilter(0, 90);
    future.SetFilter(0, 90)

    If you don't call the SetFilter method, the default values of the minExpiryDays and maxExpiryDays parameters are 0 and 35 respectively.

  9. Call the GetFuturesContractList method with the underlying Future Symbol and a datetimeDateTime.
  10. var startDate = new DateTime(2021,12,20);
    var futureSymbols = qb.FutureChainProvider.GetFutureContractList(future.Symbol, startDate);
    start_date = datetime(2021,12,20)
    future_symbols = qb.FutureChainProvider.GetFutureContractList(future.Symbol, start_date)

    The call returns a list of Symbols that reference the FutureContracts that were trading at the given time.

  11. Select the Symbol of the FutureContract(s) for which you want to get historical data.
  12. For example, select the Symbol of the contract with the closest expiry.

    var futureContractSymbol = futureSymbols.OrderBy(s => s.ID.Date).FirstOrDefault();
    qb.AddFutureContract(futureContractSymbol, fillDataForward: false);
    future_contract_symbol = sorted(future_symbols, key=lambda s: s.ID.Date)[0]
    qb.AddFutureContract(future_contract_symbol, fillDataForward = False)
  13. Call the GetOptionsContractList method with the underlying Future Contract Symbol and a datetime DateTime object.
  14. var symbols = qb.OptionChainProvider.GetOptionContractList(futureContractSymbol, startDate);
    symbols = qb.OptionChainProvider.GetOptionContractList(future_contract_symbol, start_date)

    The call returns a list of Symbols that reference the OptionContracts that were trading at the given time.

  15. Select the Symbol of the OptionContract(s) for which you want to get historical data.
  16. For example, select an arbitrary Symbol.

    symbols.OrderBy(s => Math.Abs(s.ID.StrikePrice - qb.Securities[s.Underlying].Price)).FirstOrDefault();
    contract_symbol = symbols[-1]
  17. Call the GetOptionContractList method with an OptionContract Symbol and disable fill-forward.
  18. qb.AddFutureOptionContract(contractSymbol, fillDataForward: false);
    qb.AddFutureOptionContract(contract_symbol, fillDataForward = False)

Get Historical Data

You need a subscription before you can request historical data for a security. You can request an amount of historical data based on a trailing number of bars, a trailing period of time, or a defined period of time. To reduce the risk of look-ahead bias, before you request historical data, call the SetStartDate method with a datetimeDateTime.

qb.SetStartDate(startDate);
qb.SetStartDate(start_date)

The datetimeDateTime passed to the SetStartDate method is the most recent day for which you can receive historical data. You can not receive historical data that is timestamped after the datetimeDateTime.

Trailing Number of Bars

Call the History method with a Symbol and integer to request historical data based on the given number of trailing bars.

var contractHistory = qb.History(contractSymbol, 400);
contract_history = qb.History(contract_symbol, 400)

These calls return the most recent bars, excluding periods of time when the exchange was closed.

Trailing Period of Time

Call the History method with a symbol and TimeSpantimedelta to request historical data based on the given trailing period of time.

var contractHistory = qb.History(contractSymbol, TimeSpan.FromDays(10));
contract_history = qb.History(contract_symbol, timedelta(days=10))

These calls return the most recent bars, excluding periods of time when the exchange was closed.

In all of the cases above, the History method returns an IEnumerable<TradeBar> for the market price history requests.

The History method returns an IEnumerable<Slice> for the market price history requests, if the first argument is a list. For example, the defined period of time case will be coded as follows:

var contractHistorySlices = qb.History(new [] { contractSymbol }, startTime, endTime);

In all of the cases above, the History method returns a DataFrame with a MultiIndex. If you request history for the continuous Future, the DataFrame contains quote prices, trade prices, and volume data.

future option history DataFrame

Defined Period of Time

Call the History method with a symbol, start DateTimedatetime, and end DateTimedatetime to request historical data based on the defined period of time.

var startTime = new DateTime(2021, 12, 1);
var endTime = new DateTime(2021, 12, 20);
contractHistory = qb.History(contractSymbol, startTime, endTime);
start_time = datetime(2021, 12, 1)
end_time = datetime(2021, 12, 10)
contract_history = qb.History(contract_symbol, start_time, end_time)

These calls return the bars that are timestamped within the defined period of time.

Adjust Universe Size

You need to subscribe to all of the FutureOptions for which you want historical data. You can request historical data for a subset of the FutureOptions contract properties or a subset of the FutureOptions contracts.

You need to subscribe to all of the FutureOptions for which you want historical data. You can request historical data for a subset of the Option contract properties or a subset of the Option contracts. Before you request historical data, redefine the start datetimeDateTime to reduce the amount of data that the history requests return.

Subset of Options Contract Properties

This functionality is not currently supported for C# research environments. Use Python to get a subset of Options contract properties.

  1. Call the GetOptionHistory method with an Future Contract Symbol, start datetimeDateTime, end datetimeDateTime, and resolution to get historical Option contract data for the given Symbol.
  2. option_history = qb.GetOptionHistory(future_contract_symbol, start_time, end_time, Resolution.Minute)

    The call returns an OptionHistory object. If you don't call the SetFilter method, the GetOptionHistory method uses the default filter definition to select OptionContracts and their historical data.

  3. Call the GetAllData method to get all of the historical data for the selected contracts and the underlying Future Contract.
  4. history = option_history.GetAllData()

    The call returns a DataFrame with a MultiIndex.

  5. Call the GetExpiryDates method to get all of the expiry dates for the selected contracts.
  6. expiries = option_history.GetExpiryDates()

    The call returns a list of datetimes.

  7. Call the OptionHistory's GetStrikes method to get all of the strike prices for the selected contracts.
  8. strikes = option_history.GetStrikes()

    The call returns a list of floats.

Subset of Option Contracts

Follow these steps to get historical data for a subset of the Option contracts to which you are subscribed:

  1. Call the GetOptionsContractList method with an Future Contract Symbol and a datetimeDateTime argument to get a list of OptionContract Symbols that were trading at the given time.
  2. var symbols = qb.OptionChainProvider.GetOptionContractList(futureContractSymbol, endTime);
    symbols = qb.OptionChainProvider.GetOptionContractList(future_contract_symbol, end_time)
  3. Select the subset of Symbols for which you want to get historical data.
  4. var selectedSymbols = symbols.Where(x => x.ID.StrikePrice >= 4500m && x.ID.StrikePrice <= 5100m);
    selected_symbols = [symbol for symbol in symbols \
        if symbol.ID.StrikePrice in strikes[:5] and symbol.ID.Date == min(expiries)]

    The code above mimics the filter specidied by the SetFilter method from the Create Subscriptions section.

  5. Call the AddFutureOptionContract method with the OptionContract Symbol and disable fill-forward.
  6. foreach (var symbol in selectedSymbols)
    {
        qb.AddOptionContract(symbol, fillDataForward: false);
    }
    for symbol in selected_symbols:
        qb.AddFutureOptionContract(symbol, fillDataForward = False)
  7. Call the History method with a list of Symbols to get the historical data of the given Symbols.
  8. var definedPeriodPriceHistory = qb.History(symbols, startTime, endTime);
    var timespanPriceHistory = qb.History(symbols, TimeSpan.FromDays(10));
    var barCountPriceHistory = qb.History(symbols, 10);
    var definedPeriodPriceHistory = qb.History(symbols, startTime, endTime);
    var timespanPriceHistory = qb.History(symbols, TimeSpan.FromDays(10));
    var barCountPriceHistory = qb.History(symbols, 10);

Wrangle Data

You need some historical data to perform wrangling operations. Run a cell in a Jupyter Notebook with the pandas object as the last line to display the historical data.

The DataFrame that contains historical data for Option contracts has a MultiIndex with levels for the strike, expiry, OptionRight, Symbol, and timestamp. For some of the wrangling operations, you need to drop the first 3 index level. To drop the index level, run:

contract_history.index = contract_history.index.droplevel([0,1,2])

You need some historical data to perform wrangling operations. Use LINQ to wrangle the data and then call the Console.WriteLine method in a Jupyter Notebook to display the data.

Select One Contract

Index the DataFrame with a Symbol to select the historical data of the contract.

To display the price data of the contract, run:

Iterate through the IEnumerable<T> to get the historical data of the contract. The Jupyter Notebook displays the contents of the last 5 TradeBars.

foreach(var bar in contractHistory.TakeLast(5))
{
    Console.WriteLine($"{bar} EndTime: {bar.EndTime}");
}
contract_history.loc[contract_symbol]

The Jupyter Notebook displays a DataFrame containing the trade and quote data of the contract.

Select a Property of the Contract

Index the DataFrame with a Symbol to select the historical data of the contract and then select a property column to get the historical values of the property. The pandas.DataFrames are transformed into pandas.Series of ask closing prices.

To display the closing ask prices of the contract, run:

Iterate through the IEnumerable<T> and select a property of the Slice to get the historical data of the contract. The Jupyter Notebook displays the contents of the last 5 closing prices of the contract.

var closingPrices = contractHistory
    .Select(x => $"{x.Symbol}: Close: {x.Close} EndTime:{x.EndTime}");

foreach(var closingPrice in closingPrices.TakeLast(5))
{
    Console.WriteLine(closingPrice);
}
contract_history.loc[contract_symbol]['askclose']

The Jupyter Notebook displays a Series containing the closing ask prices of the contract.

Unstack the Dataframe

If you request historical data for multiple contracts, you can transform the DataFrame so that it is a time series of a property value for all of the containing contracts. Select the column that you want to display for each contract and then call the unstack method to transform the DataFrame into the desired format. You can rename the columns of the transformed DataFrame to be the respective OptionsContract Symbols.

To display the closing bid prices of all of the contracts, run:

df = timespan_contract_history.copy().droplevel([0,1,2])
df = df['bidclose'].unstack(level=0)
df.columns = [Symbol.GetAlias(SecurityIdentifier.Parse(x), contract_symbol)
    for x in df.columns]
df

The Jupyter Notebook displays a DataFrame that contains the closing bid prices of the contracts and has the Symbol of each OptionsContract as the column indices.

Plot Data

Jupyter Notebooks don't currently support libraries to plot historical data, but we are working on adding the functionality. Until we add the functionality, use Python to plot historical Future Options data.

You need to get some historical Future Options data to plot it. You can use many of the supported plotting libraries to visualize data in various formats. For example, you can plot candlestick and line charts.

Candlestick Chart

Follow these steps to plot candlestick charts:

  1. Call the History method with an OptionContract Symbol, time argument(s) and resolution.
  2. history = qb.History(contract_symbol, start_time, end_time)
  3. Drop the first four index levels of the returned pandas.DataFrame.
  4. history.index = history.index.droplevel([0,1,2,3])
  5. (Optional) Select just first few hours of the returned history.
  6. history = history.loc[(history.index < start_time+timedelta(hours=12))]
  7. Import the Plotly library.
  8. import plotly.graph_objects as go
  9. Create a Candlestick.
  10. candlestick = go.Candlestick(x=history.index,
                                 open=history['open'],
                                 high=history['high'],
                                 low=history['low'],
                                 close=history['close'])
  11. Create a Layout.
  12. layout = go.Layout(title=go.layout.Title(text=f'{symbol.Value} OHLC'),
                       xaxis_title='Date',
                       yaxis_title='Price',
                       xaxis_rangeslider_visible=False)
  13. Create the Figure.
  14. fig = go.Figure(data=[candlestick], layout=layout)
  15. Show the Figure. Candlestick charts display the open, high, low, and close prices of the contract.
  16. fig.show()

Line Chart

Follow these steps to plot line charts using built-in methods:

  1. Call the History method with the OptionContract Symbols and defined period.
  2. history = qb.History(selected_symbols, start_time, end_time)
  3. Drop the first three index levels of the returned pandas.DataFrame.
  4. history.index = history.index.droplevel([0,1,2])
  5. Select the data to plot.
  6. In this tutorial, close price was chosen.

    close = history['close'].unstack(level=0)
    close.columns = [Symbol.GetAlias(SecurityIdentifier.Parse(x), contract_symbol)
        for x in close.columns]
  7. Call the plot method on the pandas object.
  8. close.plot(title="Close", figsize=(15, 12))
  9. Show the plot.
  10. plt.show()

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: