Datasets

Indices

Introduction

This page explains how to request, manipulate, and visualize historical Index 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 an Index security:

  1. Load the required assembly files and data types.
  2. #load "../Initialize.csx"
    #load "../QuantConnect.csx"
    
    using QuantConnect;
    using QuantConnect.Data;
    using QuantConnect.Algorithm;
    using QuantConnect.Research;
  3. Create a QuantBook.
  4. var qb = new QuantBook();
    qb = QuantBook()
  5. Call the AddIndex method with a ticker and then save a reference to the Index Symbol.
  6. var spx = qb.AddIndex("SPX").Symbol;
    var vix = qb.AddIndex("VIX").Symbol;
    spx = qb.AddIndex("SPX").Symbol
    vix = qb.AddIndex("VIX").Symbol

To view all of the available indices, see Supported Indices.

Get Historical Data

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

Trailing Number of Bars

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

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

// TradeBar objects
var singleHistoryTradeBars = qb.History<TradeBar>(spx, 10);
var subsetHistoryTradeBars = qb.History<TradeBar>(new[] {spx, vix}, 10);
var allHistoryTradeBars = qb.History<TradeBar>(qb.Securities.Keys, 10);
# DataFrame
single_history_df = qb.History(spx, 10)
single_history_trade_bar_df = qb.History(TradeBar, spx, 10)
subset_history_df = qb.History([spx, vix], 10)
subset_history_trade_bar_df = qb.History(TradeBar, [spx, vix], 10)
all_history_df = qb.History(qb.Securities.Keys, 10)
all_history_trade_bar_df = qb.History(TradeBar, qb.Securities.Keys, 10)

# Slice objects
all_history_slice = qb.History(10)

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

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

Trailing Period of Time

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

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

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

// Tick objects
var singleHistoryTicks = qb.History<Tick>(spx, TimeSpan.FromDays(3), Resolution.Tick);
var subsetHistoryTicks = qb.History<Tick>(new[] {spx, vix}, TimeSpan.FromDays(3), Resolution.Tick);
var allHistoryTicks = qb.History<Tick>(qb.Securities.Keys, TimeSpan.FromDays(3), Resolution.Tick);
# DataFrame
single_history_df = qb.History(spx, timedelta(days=3))
single_history_trade_bar_df = qb.History(TradeBar, spx, timedelta(days=3))
subset_history_df = qb.History([spx, vix], timedelta(days=3))
subset_history_trade_bar_df = qb.History(TradeBar, [spx, vix], timedelta(days=3))
all_history_df = qb.History(qb.Securities.Keys, timedelta(days=3))
all_history_trade_bar_df = qb.History(TradeBar, 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](spx, timedelta(days=3))
subset_history_trade_bars = qb.History[TradeBar]([spx, vix], timedelta(days=3))
all_history_trade_bars = qb.History[TradeBar](qb.Securities.Keys, timedelta(days=3))

# Tick objects
single_history_ticks = qb.History[Tick](spx, timedelta(days=3), Resolution.Tick)
subset_history_ticks = qb.History[Tick]([spx, vix], timedelta(days=3), Resolution.Tick)
all_history_ticks = qb.History[Tick](qb.Securities.Keys, timedelta(days=3), Resolution.Tick)

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

Defined Period of Time

To get historical data for a specific period of time, call the History method with the Symbol object(s), a start DateTimedatetime, and an end DateTimedatetime.

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

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

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

// Tick objects
var singleHistoryTicks = qb.History<Tick>(spx, startTime, endTime, Resolution.Tick);
var subsetHistoryTicks = qb.History<Tick>(new[] {spx, vix}, startTime, endTime, Resolution.Tick);
var allHistoryTicks = qb.History<Tick>(qb.Securities.Keys, startTime, endTime, Resolution.Tick);
start_time = datetime(2021, 1, 1)
end_time = datetime(2021, 2, 1)

# DataFrame
single_history_df = qb.History(spx, start_time, end_time)
single_history_trade_bar_df = qb.History(TradeBar, spx, start_time, end_time)
subset_history_df = qb.History([spx, vix], start_time, end_time)
subset_history_trade_bar_df = qb.History(TradeBar, [spx, vix], start_time, end_time)
all_history_df = qb.History(qb.Securities.Keys, start_time, end_time)
all_history_trade_bar_df = qb.History(TradeBar, qb.Securities.Keys, start_time, end_time)

# Slice objects
all_history_slice = qb.History(start_time, end_time)

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

# Tick objects
single_history_ticks = qb.History[Tick](spx, start_time, end_time, Resolution.Tick)
subset_history_ticks = qb.History[Tick]([spx, vix], start_time, end_time, Resolution.Tick)
all_history_ticks = qb.History[Tick](qb.Securities.Keys, start_time, end_time, Resolution.Tick)

The preceding calls return the bars or ticks that have a timestamp within the defined period of time.

Resolutions

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

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

Markets

The only market available for Indices is Market.USA.

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 the History method returns a DataFrame, the first level of the DataFrame index is the Index Symbol and the second level is the EndTime of the data sample. The columns of the DataFrame are the data properties.

DataFrame of two Indices

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

all_history_df.loc[spx]  # or all_history_df.loc['SPX']
DataFrame of one Index

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

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

If you request historical data for multiple Indices, you can transform the DataFrame so that it's a time series of close values for all of the Indices. To transform the DataFrame, select the column you want to display for each Index 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 Index 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 Index subscriptions. To avoid issues, check if the Slice contains data for your Index before you index it with the Index Symbol.

foreach (var slice in allHistorySlice)
{
    if (slice.Bars.ContainsKey(spx))
    {
        var tradeBar = slice.Bars[spx];
    }
}
for slice in all_history_slice:
    if slice.Bars.ContainsKey(spx):
        trade_bar = slice.Bars[spx]

You can also iterate through each TradeBar in the Slice.

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

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 Index. The TradeBars may not have data for all of your Index subscriptions. To avoid issues, check if the TradeBars object contains data for your security before you index it with the Index Symbol.

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

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

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 Index. The Ticks may not have data for all of your Index subscriptions. To avoid issues, check if the Ticks object contains data for your security before you index it with the Index Symbol.

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

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

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

You need some historical Index data to produce plots. 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(spx, datetime(2021, 11, 24), datetime(2021, 12, 8), Resolution.Daily).loc[spx]
  3. Import the plotly library.
  4. import plotly.graph_objects as go
  5. Create a Candlestick.
  6. candlestick = go.Candlestick(x=history.index,
                                 open=history['open'],
                                 high=history['high'],
                                 low=history['low'],
                                 close=history['close'])
  7. Create a Layout.
  8. layout = go.Layout(title=go.layout.Title(text='SPX OHLC'),
                       xaxis_title='Date',
                       yaxis_title='Price',
                       xaxis_rangeslider_visible=False)
  9. Create a Figure.
  10. fig = go.Figure(data=[candlestick], layout=layout)
  11. Show the Figure.
  12. fig.show()

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

Line Chart

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

  1. Get some historical data.
  2. history = qb.History([spx, vix], datetime(2021, 11, 24), datetime(2021, 12, 8), Resolution.Daily)
  3. Select the data to plot.
  4. pct_change = history['close'].unstack(0).pct_change().dropna()
  5. Call the plot method on the pandas object.
  6. pct_change.plot(title="Close Price %Change", figsize=(15, 10))
  7. Show the plot.
  8. 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: