book
Checkout our new book! Hands on AI Trading with Python, QuantConnect, and AWS Learn More arrow

Asset Classes

Index

Introduction

This page explains how to get historical price and indicator data for Indices.

Bars

To get historical price data, call the history method with an Index Symbol. This method returns a DataFrame with columns for the open, high, low, and close.

Select Language:
class IndexPriceHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of an Index.
        symbol = self.add_index('SPX').symbol
        # Get the 5 trailing daily bars of the Index in DataFrame format. 
        history = self.history(symbol, 5, Resolution.DAILY)
closehighlowopen
symboltime
SPX2024-12-12 15:15:006051.706079.686051.706074.05
2024-12-13 15:15:006050.836078.586035.776068.48
2024-12-16 15:15:006074.486085.196059.146064.04
2024-12-17 15:15:006050.316057.686035.196046.33
2024-12-18 15:15:005869.226070.675867.796048.69
# Calculate the daily growth.
daily_growth = history.close.pct_change().iloc[1:]
symbol  time               
SPX     2024-12-13 15:15:00   -0.000144
        2024-12-16 15:15:00    0.003909
        2024-12-17 15:15:00   -0.003979
        2024-12-18 15:15:00   -0.029931
Name: close, dtype: float64

If you intend to use the data in the DataFrame to create TradeBar objects, request that the history request returns the data type you need. Otherwise, LEAN consumes unnecessary computational resources populating the DataFrame. To get a list of TradeBar objects instead of a DataFrame, call the history[TradeBar] method.

# Get the 5 trailing daily bars of the Index in TradeBar format. 
history = self.history[TradeBar](symbol, 5, Resolution.DAILY)
# Iterate through the TradeBar objects and access their prices.
for trade_bar in history:
    price = trade_bar.price

Request minute, hour, or daily resolution data. Otherwise, the history request won't return any data.

Slices

To get historical Slice data, call the history method without passing any Symbol objects. This method returns Slice objects, which contain data points from all the datasets in your algorithm. If you omit the resolution argument, it uses the resolution that you set for each security and dataset when you created the subscriptions.

Select Language:
class SliceHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 1)
        # Add some securities and datasets.
        self.add_index('SPX')
        # Get the historical Slice objects over the last 5 days for all the subcriptions in your algorithm.
        history = self.history(5, Resolution.DAILY)
        # Iterate through each historical Slice.
        for slice_ in history:
            # Iterate through each TradeBar in this Slice.
            for symbol, trade_bar in slice_.bars.items():
                close = trade_bar.close

Indicators

To get historical indicator values, call the indicator_history method with an indicator and the security's Symbol.

Select Language:
class IndexIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of a security.
        symbol = self.add_index('SPX').symbol
        # Get the 21-day SMA values of the security for the last 5 trading days. 
        history = self.indicator_history(SimpleMovingAverage(21), symbol, 5, Resolution.DAILY)

To organize the data into a DataFrame, use the data_frame property of the result.

# Organize the historical indicator data into a DataFrame to enable pandas wrangling.
history_df = history.data_frame
currentrollingsum
2024-12-12 15:15:006003.055714126064.17
2024-12-13 15:15:006006.096667126128.03
2024-12-16 15:15:006012.036190126252.76
2024-12-17 15:15:006020.634286126433.32
2024-12-18 15:15:006019.442381126408.29
# Get the maximum of the SMA values.
sma_max = history_df.current.max()

The indicator_history method resets your indicator, makes a history request, and updates the indicator with the historical data. Just like with regular history requests, the indicator_history method supports time periods based on a trailing number of bars, a trailing period of time, or a defined period of time. If you don't provide a resolution argument, it defaults to match the resolution of the security subscription.

To make the indicator_history method update the indicator with an alternative price field instead of the close (or mid-price) of each bar, pass a selector argument.

Select Language:
# Get the historical values of an indicator over the last 30 days, applying the indicator to the security's high price.
history = self.indicator_history(indicator, symbol, timedelta(30), selector=Field.HIGH)

Some indicators require the prices of two securities to compute their value (for example, Beta). In this case, pass a list of the Symbol objects to the method.

Select Language:
class IndexMultiAssetIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Add the target and reference securities.
        target_symbol = self.add_index('NDX').symbol
        reference_symbol = self.add_index('SPX').symbol
        # Create a 21-period Beta indicator.
        beta = Beta("", target_symbol, reference_symbol, 21)
        # Get the historical values of the indicator over the last 10 trading days.
        history = self.indicator_history(beta, [target_symbol, reference_symbol], 10, Resolution.DAILY)
        # Get the average Beta value.
        beta_avg = history.data_frame.mean()

Examples

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: