Datasets

Futures

Introduction

This page explains how to request, manipulate, and visualize historical Futures 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, resolution, and contract rollover settings.
  6. var future = qb.AddFuture(Futures.Indices.SP500EMini, Resolution.Minute,
                    dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
                    dataMappingMode: DataMappingMode.LastTradingDay,
                    contractDepthOffset: 0);
    future = qb.AddFuture(Futures.Indices.SP500EMini, Resolution.Minute,
                    dataNormalizationMode = DataNormalizationMode.BackwardsRatio,
                    dataMappingMode = DataMappingMode.LastTradingDay,
                    contractDepthOffset = 0)

    To view the available tickers in the US Futures dataset, see Supported Assets.

    If you omit any of the arguments after the ticker, see the following table for their default values:

    ArgumentDefault Value
    resolutionResolution.Minute
    dataNormalizationModeDataNormalizationMode.Adjusted
    dataMappingModeDataMappingMode.OpenInterest
    contractDepthOffset0
  7. (Optional) Set a contract filter.
  8. future.SetFilter(0, 90);
    future.SetFilter(0, 90)

    If you don't call the SetFilter method, the GetFutureHistory method won't return historical data.

If you want historical data on individual contracts and their OpenInterest, follow these steps to subscribe to individual Future contracts:

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

    This method returns a list of Symbol objects that reference the Future contracts that were trading at the given time.

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

    var contractSymbol = symbols.OrderBy(s => s.ID.Date).FirstOrDefault();
    contract_symbol = sorted(symbols, key=lambda s: s.ID.Date)[0]
  5. Call the AddFutureContract method with an FutureContract Symbol and disable fill-forward.
  6. qb.AddFutureContract(contractSymbol, fillDataForward: false);
    qb.AddFutureContract(contract_symbol, fillDataForward = False)

    Disable fill-forward because there are only a few OpenInterest data points per day.

Get Historical Data

You need a subscription before you can request historical data for Futures contracts. On the time dimension, 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. On the contract dimension, you can request historical data for a single contract, a subset of the contracts you created subscriptions for in your notebook, or all of the contracts in your notebook.

Before you request historical data, call the SetStartDate method with a datetimeDateTime to reduce the risk of look-ahead bias.

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

If you call the SetStartDate method, the date that you pass to the method is the latest date for which your history requests will return data.

Trailing Number of Bars

To get historical data for a number of trailing bars, call the History method with the contract Symbol object(s) and an integer.

// Slice objects
var singleHistorySlice = qb.History(contractSymbol, 10);
var subsetHistorySlice = qb.History(new[] {contractSymbol}, 10);
var allHistorySlice = qb.History(10);

// TradeBar objects
var singleHistoryTradeBars = qb.History<TradeBar>(contractSymbol, 10);
var subsetHistoryTradeBars = qb.History<TradeBar>(new[] {contractSymbol}, 10);
var allHistoryTradeBars = qb.History<TradeBar>(qb.Securities.Keys, 10);

// QuoteBar objects
var singleHistoryQuoteBars = qb.History<QuoteBar>(contractSymbol, 10);
var subsetHistoryQuoteBars = qb.History<QuoteBar>(new[] {contractSymbol}, 10);
var allHistoryQuoteBars = qb.History<QuoteBar>(qb.Securities.Keys, 10);

// OpenInterest objects
var singleHistoryOpenInterest = qb.History<OpenInterest>(contractSymbol, 400);
var subsetHistoryOpenInterest = qb.History<OpenInterest>(new[] {contractSymbol}, 400);
var allHistoryOpenInterest = qb.History<OpenInterest>(qb.Securities.Keys, 400);
# DataFrame of trade and quote data
single_history_df = qb.History(contract_symbol, 10)
subset_history_df = qb.History([contract_symbol], 10)
all_history_df = qb.History(qb.Securities.Keys, 10)

# DataFrame of trade data
single_history_trade_bar_df = qb.History(TradeBar, contract_symbol, 10)
subset_history_trade_bar_df = qb.History(TradeBar, [contract_symbol], 10)
all_history_trade_bar_df = qb.History(TradeBar, qb.Securities.Keys, 10)

# DataFrame of quote data
single_history_quote_bar_df = qb.History(QuoteBar, contract_symbol, 10)
subset_history_quote_bar_df = qb.History(QuoteBar, [contract_symbol], 10)
all_history_quote_bar_df = qb.History(QuoteBar, qb.Securities.Keys, 10)

# DataFrame of open interest data
single_history_open_interest_df = qb.History(OpenInterest, contract_symbol, 400)
subset_history_open_interest_df = qb.History(OpenInterest, [contract_symbol], 400)
all_history_open_interest_df = qb.History(OpenInterest, qb.Securities.Keys, 400)

# Slice objects
all_history_slice = qb.History(10)

# TradeBar objects
single_history_trade_bars = qb.History[TradeBar](contract_symbol, 10)
subset_history_trade_bars = qb.History[TradeBar]([contract_symbol], 10)
all_history_trade_bars = qb.History[TradeBar](qb.Securities.Keys, 10)

# QuoteBar objects
single_history_quote_bars = qb.History[QuoteBar](contract_symbol, 10)
subset_history_quote_bars = qb.History[QuoteBar]([contract_symbol], 10)
all_history_quote_bars = qb.History[QuoteBar](qb.Securities.Keys, 10)

# OpenInterest objects
single_history_open_interest = qb.History[OpenInterest](contract_symbol, 400)
subset_history_open_interest = qb.History[OpenInterest]([contract_symbol], 400)
all_history_open_interest = qb.History[OpenInterest](qb.Securities.Keys, 400)

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

To get historical data for the continous Futures contract, in the preceding history requests, replace contract_symbolcontractSymbol with future.Symbol.

Trailing Period of Time

To get historical data for a trailing period of time, call the History method with the contract Symbol object(s) and a TimeSpantimedelta.

// Slice objects
var singleHistorySlice = qb.History(contractSymbol, TimeSpan.FromDays(3));
var subsetHistorySlice = qb.History(new[] {contractSymbol}, TimeSpan.FromDays(3));
var allHistorySlice = qb.History(10);

// TradeBar objects
var singleHistoryTradeBars = qb.History<TradeBar>(contractSymbol, TimeSpan.FromDays(3));
var subsetHistoryTradeBars = qb.History<TradeBar>(new[] {contractSymbol}, TimeSpan.FromDays(3));
var allHistoryTradeBars = qb.History<TradeBar>(TimeSpan.FromDays(3));

// QuoteBar objects
var singleHistoryQuoteBars = qb.History<QuoteBar>(contractSymbol, TimeSpan.FromDays(3), Resolution.Minute);
var subsetHistoryQuoteBars = qb.History<QuoteBar>(new[] {contractSymbol}, TimeSpan.FromDays(3), Resolution.Minute);
var allHistoryQuoteBars = qb.History<QuoteBar>(qb.Securities.Keys, TimeSpan.FromDays(3), Resolution.Minute);
    
// Tick objects
var singleHistoryTicks = qb.History(contractSymbol, TimeSpan.FromDays(3), Resolution.Tick);
var subsetHistoryTicks = qb.History(new[] {contractSymbol}, TimeSpan.FromDays(3), Resolution.Tick);
var allHistoryTicks = qb.History(qb.Securities.Keys, TimeSpan.FromDays(3), Resolution.Tick);
        
// OpenInterest objects
var singleHistoryOpenInterest = qb.History<OpenInterest>(contractSymbol, TimeSpan.FromDays(2));
var subsetHistoryOpenInterest = qb.History<OpenInterest>(new[] {contractSymbol}, TimeSpan.FromDays(2));
var allHistoryOpenInterest = qb.History<OpenInterest>(qb.Securities.Keys, TimeSpan.FromDays(2));
# DataFrame of trade and quote data
single_history_df = qb.History(contract_symbol, timedelta(days=3))
subset_history_df = qb.History([contract_symbol], timedelta(days=3))
all_history_df = qb.History(qb.Securities.Keys, timedelta(days=3))

# DataFrame of trade data
single_history_trade_bar_df = qb.History(TradeBar, contract_symbol, timedelta(days=3))
subset_history_trade_bar_df = qb.History(TradeBar, [contract_symbol], timedelta(days=3))
all_history_trade_bar_df = qb.History(TradeBar, qb.Securities.Keys, timedelta(days=3))

# DataFrame of quote data
single_history_quote_bar_df = qb.History(QuoteBar, contract_symbol, timedelta(days=3))
subset_history_quote_bar_df = qb.History(QuoteBar, [contract_symbol], timedelta(days=3))
all_history_quote_bar_df = qb.History(QuoteBar, qb.Securities.Keys, timedelta(days=3))

# DataFrame of open interest data
single_history_open_interest_df = qb.History(OpenInterest, contract_symbol, timedelta(days=3))
subset_history_open_interest_df = qb.History(OpenInterest, [contract_symbol], timedelta(days=3))
all_history_open_interest_df = qb.History(OpenInterest, qb.Securities.Keys, timedelta(days=3))

# Slice objects
all_history_slice = qb.History(timedelta(days=3))

# TradeBar objects
single_history_trade_bars = qb.History[TradeBar](contract_symbol, timedelta(days=3))
subset_history_trade_bars = qb.History[TradeBar]([contract_symbol], timedelta(days=3))
all_history_trade_bars = qb.History[TradeBar](qb.Securities.Keys, timedelta(days=3))

# QuoteBar objects
single_history_quote_bars = qb.History[QuoteBar](contract_symbol, timedelta(days=3), Resolution.Minute)
subset_history_quote_bars = qb.History[QuoteBar]([contract_symbol], timedelta(days=3), Resolution.Minute)
all_history_quote_bars = qb.History[QuoteBar](qb.Securities.Keys, timedelta(days=3), Resolution.Minute)

# Tick objects
single_history_ticks = qb.History[Tick](contract_symbol, timedelta(days=3), Resolution.Tick)
subset_history_ticks = qb.History[Tick]([contract_symbol], timedelta(days=3), Resolution.Tick)
all_history_ticks = qb.History[Tick](qb.Securities.Keys, timedelta(days=3), Resolution.Tick)
        
# OpenInterest objects
single_history_open_interest = qb.History[OpenInterest](contract_symbol, timedelta(days=2))
subset_history_open_interest = qb.History[OpenInterest]([contract_symbol], timedelta(days=2))
all_history_open_interest = qb.History[OpenInterest](qb.Securities.Keys, timedelta(days=2))

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

To get historical data for the continous Futures contract, in the preceding history requests, replace contract_symbolcontractSymbol with future.Symbol.

Defined Period of Time

To get historical data for individual Futures contracts during a specific period of time, call the History method with the Futures contract Symbol object(s), a start DateTimedatetime, and an end DateTimedatetime. The start and end times you provide are based in the notebook time zone.

var startTime = new DateTime(2021, 12, 1);
var endTime = new DateTime(2021, 12, 31);

// Slice objects
var singleHistorySlice = qb.History(contractSymbol, startTime, endTime);
var subsetHistorySlice = qb.History(new[] {contractSymbol}, startTime, endTime);
var allHistorySlice = qb.History(startTime, endTime);

// TradeBar objects
var singleHistoryTradeBars = qb.History<TradeBar>(contractSymbol, startTime, endTime);
var subsetHistoryTradeBars = qb.History<TradeBar>(new[] {contractSymbol}, startTime, endTime);
var allHistoryTradeBars = qb.History<TradeBar>(qb.Securities.Keys, startTime, endTime);

// QuoteBar objects
var singleHistoryQuoteBars = qb.History<QuoteBar>(contractSymbol, startTime, endTime, Resolution.Minute);
var subsetHistoryQuoteBars = qb.History<QuoteBar>(new[] {contractSymbol}, startTime, endTime, Resolution.Minute);
var allHistoryQuoteBars = qb.History<QuoteBar>(qb.Securities.Keys, startTime, endTime, Resolution.Minute);
    
// Tick objects
var singleHistoryTicks = qb.History(contractSymbol, startTime, endTime, Resolution.Tick);
var subsetHistoryTicks = qb.History(new[] {contractSymbol}, startTime, endTime, Resolution.Tick);
var allHistoryTicks = qb.History(qb.Securities.Keys, startTime, endTime, Resolution.Tick);
        
// OpenInterest objects
var singleHistoryOpenInterest = qb.History<OpenInterest>(contractSymbol, startTime, endTime);
var subsetHistoryOpenInterest = qb.History<OpenInterest>(new[] {contractSymbol}, startTime, endTime);
var allHistoryOpenInterest = qb.History<OpenInterest>(qb.Securities.Keys, startTime, endTime);
start_time = datetime(2021, 12, 1)
end_time = datetime(2021, 12, 31)

# DataFrame of trade and quote data
single_history_df = qb.History(contract_symbol, start_time, end_time)
subset_history_df = qb.History([contract_symbol], start_time, end_time)
all_history_df = qb.History(qb.Securities.Keys, start_time, end_time)

# DataFrame of trade data
single_history_trade_bar_df = qb.History(TradeBar, contract_symbol, start_time, end_time)
subset_history_trade_bar_df = qb.History(TradeBar, [contract_symbol], start_time, end_time)
all_history_trade_bar_df = qb.History(TradeBar, qb.Securities.Keys, start_time, end_time)

# DataFrame of quote data
single_history_quote_bar_df = qb.History(QuoteBar, contract_symbol, start_time, end_time)
subset_history_quote_bar_df = qb.History(QuoteBar, [contract_symbol], start_time, end_time)
all_history_quote_bar_df = qb.History(QuoteBar, qb.Securities.Keys, start_time, end_time)

# DataFrame of open interest data
single_history_open_interest_df = qb.History(OpenInterest, contract_symbol, start_time, end_time)
subset_history_open_interest_df = qb.History(OpenInterest, [contract_symbol], start_time, end_time)
all_history_trade_open_interest_df = qb.History(OpenInterest, qb.Securities.Keys, start_time, end_time)

# TradeBar objects
single_history_trade_bars = qb.History[TradeBar](contract_symbol, start_time, end_time)
subset_history_trade_bars = qb.History[TradeBar]([contract_symbol], start_time, end_time)
all_history_trade_bars = qb.History[TradeBar](qb.Securities.Keys, start_time, end_time)

# QuoteBar objects
single_history_quote_bars = qb.History[QuoteBar](contract_symbol, start_time, end_time, Resolution.Minute)
subset_history_quote_bars = qb.History[QuoteBar]([contract_symbol], start_time, end_time, Resolution.Minute)
all_history_quote_bars = qb.History[QuoteBar](qb.Securities.Keys, start_time, end_time, Resolution.Minute)
    
# Tick objects
single_history_ticks = qb.History[Tick](contract_symbol, start_time, end_time, Resolution.Tick)
subset_history_ticks = qb.History[Tick]([contract_symbol], start_time, end_time, Resolution.Tick)
all_history_ticks = qb.History[Tick](qb.Securities.Keys, start_time, end_time, Resolution.Tick)
        
# OpenInterest objects
single_history_open_interest = qb.History[OpenInterest](contract_symbol, start_time, end_time)
subset_history_open_interest = qb.History[OpenInterest]([contract_symbol], start_time, end_time)
all_history_open_interest = qb.History[OpenInterest](qb.Securities.Keys, start_time, end_time)

To get historical data for the continous Futures contract, in the preceding history requests, replace contract_symbolcontractSymbol with future.Symbol.

To get historical data for all of the Futures contracts that pass your filter during a specific period of time, call the GetFutureHistory method with the Symbol object of the continuous Future, a start DateTimedatetime, and an end DateTimedatetime.

future_history = qb.GetFutureHistory(future.Symbol, end_time-timedelta(days=2), end_time, Resolution.Minute, fillForward=False, extendedMarket=False)

The preceding calls return data that have a timestamp within the defined period of time.

Resolutions

The following table shows the available resolutions and data formats for Futures subscriptions:

ResolutionTradeBarQuoteBarTrade TickQuote Tick
Tickgreen checkgreen check
Secondgreen checkgreen check
Minutegreen checkgreen check
Hourgreen checkgreen check
Dailygreen checkgreen check

Markets

The following Market enumeration members are available for Futures:

Wrangle Data

You need some historical data to perform wrangling operations. The process to manipulate the historical data depends on its data type. To display pandas objects, run a cell in a notebook with the pandas object as the last line. To display other data formats, call the print method.

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. The process to manipulate the historical data depends on its data type.

DataFrame Objects

If your history request returns a DataFrame, the DataFrame has the following index levels:

  1. Contract expiry
  2. Contract Symbol
  3. The EndTime of the data sample

The columns of the DataFrame are the data properties. Depending on how you request data, the DataFrame may contain data for the continuous Futures contract, which has an expiry date before the year 1900.

To select the rows of the contract(s) that expire at a specific time, index the loc property of the DataFrame with the expiry time.

all_history_df.loc[datetime(2022, 3, 18, 13, 30)]

If you remove the first index level, you can index the DataFrame with just the contract Symbol, similiar to how you would with non-derivative asset classes. To remove the first index level, call the droplevel method.

all_history_df.index = all_history_df.index.droplevel(0)

To select the historical data of a single Futures contract, index the loc property of the DataFrame with the contract Symbol.

all_history_df.loc[contract_symbol]
DataFrame of one Futures

To select a column of the DataFrame, index it with the column name.

all_history_df.loc[contract_symbol]['close']
Series of close values

If you request historical data for multiple Futures contracts, you can transform the DataFrame so that it's a time series of close values for all of the Futures contracts. To transform the DataFrame, select the column you want to display for each Futures contract and then call the unstack method.

all_history_df['close'].unstack(level=0)

The DataFrame is transformed so that the column indices are the Symbol of each security and each row contains the close value.

Slice Objects

If the History method returns Slice objects, iterate through the Slice objects to get each one. The Slice objects may not have data for all of your Futures subscriptions. To avoid issues, check if the Slice contains data for your Futures contract before you index it with the Futures Symbol.

foreach (var slice in allHistorySlice)
{
    if (slice.Bars.ContainsKey(contractSymbol))
    {
        var tradeBar = slice.Bars[contractSymbol];
    }
    if (slice.QuoteBars.ContainsKey(contractSymbol))
    {
        var quoteBar = slice.QuoteBars[contractSymbol];
    }
}
for slice in all_history_slice:
    if slice.Bars.ContainsKey(contract_symbol):
        trade_bar = slice.Bars[contract_symbol]
    if slice.QuoteBars.ContainsKey(contract_symbol):
        quote_bar = slice.QuoteBars[contract_symbol]

You can also iterate through each TradeBar and QuoteBar in the Slice.

foreach (var slice in allHistorySlice)
{
    foreach (var kvp in slice.Bars)
    {
        var symbol = kvp.Key;
        var tradeBar = kvp.Value;
    }
    foreach (var kvp in slice.QuoteBars)
    {
        var symbol = kvp.Key;
        var quoteBar = kvp.Value;
    }
}
for slice in all_history_slice:
    for kvp in slice.Bars:
        symbol = kvp.Key
        trade_bar = kvp.Value
    for kvp in slice.QuoteBars:
        symbol = kvp.Key
        quote_bar = kvp.Value

You can also use LINQ to select each TradeBar in the Slice for a given Symbol

var tradeBars = allHistorySlice.Where(slice => slice.Bars.ContainsKey(contractSymbol)).Select(slice => slice.Bars[contractSymbol]);

TradeBar Objects

If the History method returns TradeBar objects, iterate through the TradeBar objects to get each one.

foreach (var tradeBar in singleHistoryTradeBars)
{
    Console.WriteLine(tradeBar);
}
for trade_bar in single_history_trade_bars:
    print(trade_bar)

If the History method returns TradeBars, iterate through the TradeBars to get the TradeBar of each Futures contract. The TradeBars may not have data for all of your Futures subscriptions. To avoid issues, check if the TradeBars object contains data for your security before you index it with the Futures Symbol.

foreach (var tradeBars in allHistoryTradeBars)
{
    if (tradeBars.ContainsKey(contractSymbol))
    {
        var tradeBar = tradeBars[contractSymbol];
    }
}
for trade_bars in all_history_trade_bars:
    if trade_bars.ContainsKey(contract_symbol):
        trade_bar = trade_bars[contract_symbol]

You can also iterate through each of the TradeBars.

foreach (var tradeBars in allHistoryTradeBars)
{
    foreach (var kvp in tradeBars)
    {
        var symbol = kvp.Key;
        var tradeBar = kvp.Value;
    }
}
for trade_bars in all_history_trade_bars:
    for kvp in trade_bars:
        symbol = kvp.Key
        trade_bar = kvp.Value

QuoteBar Objects

If the History method returns QuoteBar objects, iterate through the QuoteBar objects to get each one.

foreach (var quoteBar in singleHistoryQuoteBars)
{
    Console.WriteLine(quoteBar);
}
for quote_bar in single_history_quote_bars:
    print(quote_bar)

If the History method returns QuoteBars, iterate through the QuoteBars to get the QuoteBar of each Futures contract. The QuoteBars may not have data for all of your Futures subscriptions. To avoid issues, check if the QuoteBars object contains data for your security before you index it with the Futures Symbol.

foreach (var quoteBars in allHistoryQuoteBars)
{
    if (quoteBars.ContainsKey(contractSymbol))
    {
        var quoteBar = quoteBars[contractSymbol];
    }
}
for quote_bars in all_history_quote_bars:
    if quote_bars.ContainsKey(contract_symbol):
        quote_bar = quote_bars[contract_symbol]

You can also iterate through each of the QuoteBars.

foreach (var quoteBars in allHistoryQuoteBars)
{
    foreach (var kvp in quoteBars)
    {
        var symbol = kvp.Key;
        var quoteBar = kvp.Value;
    }
}
for quote_bars in all_history_quote_bars:
    for kvp in quote_bars:
        symbol = kvp.Key
        quote_bar = kvp.Value

Tick Objects

If the History method returns Tick objects, iterate through the Tick objects to get each one.

foreach (var tick in singleHistoryTicks)
{
    Console.WriteLine(tick);
}
for tick in single_history_ticks:
    print(tick)

If the History method returns Ticks, iterate through the Ticks to get the Tick of each Futures contract. The Ticks may not have data for all of your Futures subscriptions. To avoid issues, check if the Ticks object contains data for your security before you index it with the Futures Symbol.

foreach (var ticks in allHistoryTicks)
{
    if (ticks.ContainsKey(contractSymbol))
    {
        var tick = ticks[contractSymbol];
    }
}
for ticks in all_history_ticks:
    if ticks.ContainsKey(contract_symbol):
        ticks = ticks[contract_symbol]

You can also iterate through each of the Ticks.

foreach (var ticks in allHistoryTicks)
{
    foreach (var kvp in ticks)
    {
        var symbol = kvp.Key;
        var tick = kvp.Value;
    }
}
for ticks in all_history_ticks:
    for kvp in ticks:
        symbol = kvp.Key
        tick = kvp.Value

OpenInterest Objects

If the History method returns OpenInterest objects, iterate through the OpenInterest objects to get each one.

foreach (var openInterest in singleHistoryOpenInterest)
{
    Console.WriteLine(openInterest);
}
for open_interest in single_history_open_interest:
    print(open_interest)

If the History method returns a dictionary of OpenInterest objects, iterate through the dictionary to get the OpenInterest of each Futures contract. The dictionary of OpenInterest objects may not have data for all of your Futures contract subscriptions. To avoid issues, check if the dictionary contains data for your contract before you index it with the Futures contract Symbol.

foreach (var openInterestDict in allHistoryOpenInterest)
{
    if (openInterestDict.ContainsKey(contractSymbol))
    {
        var openInterest = openInterestDict[contractSymbol];
    }
}
for open_interest_dict in all_history_open_interest:
    if open_interest_dict.ContainsKey(contract_symbol):
        open_interest = open_interest_dict[contract_symbol]

You can also iterate through each of the OpenInterest dictionaries.

foreach (var openInterestDict in allHistoryOpenInterest)
{
    foreach (var kvp in openInterestDict)
    {
        var symbol = kvp.Key;
        var openInterest = kvp.Value;
    }
}
for open_interest_dict in all_history_open_interest:
    for kvp in open_interest_dict:
        symbol = kvp.Key
        open_interest = kvp.Value

FutureHistory Objects

The GetFutureHistory method returns a FutureHistory object. To convert the FutureHistory object to a DataFrame that contains the trade and quote information of each contract, call the GetAllData method.

future_history.GetAllData()

To get the expiration dates of all the contracts in an FutureHistory object, call the GetExpiryDates method.

future_history.GetExpiryDates()

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 Futures data.

You need to get some historical Futures 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. Get some historical data.
  2. history = qb.History(contract_symbol, datetime(2021, 12, 1), datetime(2021, 12, 31), Resolution.Daily)
  3. Drop the first two index levels.
  4. history.index = history.index.droplevel([0, 1])
  5. Import the plotly library.
  6. import plotly.graph_objects as go
  7. Create a Candlestick.
  8. candlestick = go.Candlestick(x=history.index,
                                 open=history['open'],
                                 high=history['high'],
                                 low=history['low'],
                                 close=history['close'])
  9. Create a Layout.
  10. layout = go.Layout(title=go.layout.Title(text=f'{contract_symbol.Value} OHLC'),
                       xaxis_title='Date',
                       yaxis_title='Price',
                       xaxis_rangeslider_visible=False)
  11. Create a Figure.
  12. fig = go.Figure(data=[candlestick], layout=layout)
  13. Show the Figure.
  14. fig.show()

    Candlestick charts display the open, high, low, and close prices of the contract.

Line Chart

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

  1. Get some historical data.
  2. history = qb.History(symbols, datetime(2021, 12, 1), datetime(2021, 12, 31), Resolution.Daily)
  3. Drop the first index level.
  4. history.index = history.index.droplevel(0)
  5. Select data to plot.
  6. closing_prices = history['close'].unstack(level=0)
  7. Rename the columns to be the Symbol of each contract.
  8. closing_prices.columns = [Symbol.GetAlias(SecurityIdentifier.Parse(x)) for x in closing_prices.columns]
  9. Call the plot method on the pandas object.
  10. closing_prices.plot(title="Close", figsize=(15, 8))
  11. Show the plot.
  12. plt.show()

    Line charts display the value of the property you selected in a time series.

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: