Asset Classes
Index
Bars
To get historical price data, call the History
method with an Index Symbol
.
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.
public class IndexPriceHistoryAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2024, 12, 19); // Get the Symbol of an Index. var symbol = AddIndex("SPX").Symbol; // Get the 5 trailing daily bars of the Index. var history = History(symbol, 5, Resolution.Daily); // Iterate through each bar and get its price. foreach (var bar in history) { var t = bar.EndTime; var price = bar.Close; } } }
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)
close | high | low | open | ||
---|---|---|---|---|---|
symbol | time | ||||
SPX | 2024-12-12 15:15:00 | 6051.70 | 6079.68 | 6051.70 | 6074.05 |
2024-12-13 15:15:00 | 6050.83 | 6078.58 | 6035.77 | 6068.48 | |
2024-12-16 15:15:00 | 6074.48 | 6085.19 | 6059.14 | 6064.04 | |
2024-12-17 15:15:00 | 6050.31 | 6057.68 | 6035.19 | 6046.33 | |
2024-12-18 15:15:00 | 5869.22 | 6070.67 | 5867.79 | 6048.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
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.
public class SliceHistoryAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2024, 12, 1); // Add some securities and datasets. AddIndex("SPX"); // Get the historical Slice objects over the last 5 days for all the subcriptions in your algorithm. var history = History(5, Resolution.Daily); // Iterate through each historical Slice. foreach (var slice in history) { // Iterate through each TradeBar in this Slice. foreach (var kvp in slice.Bars) { var symbol = kvp.Key; var bar = kvp.Value; } } } }
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 IndicatorHistory
indicator_history
method with an indicator and the security's Symbol
.
public class IndexIndicatorHistoryAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2024, 12, 19); // Get the Symbol of a security. var symbol = AddIndex("SPX").Symbol; // Get the 21-day SMA values of the security for the last 5 trading days. var history = IndicatorHistory(new SimpleMovingAverage(21), symbol, 5, Resolution.Daily); // Get the maximum of the SMA values. var maxSMA = history.Max(indicatorDataPoint => indicatorDataPoint.Current.Value); } }
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
current | rollingsum | |
---|---|---|
2024-12-12 15:15:00 | 6003.055714 | 126064.17 |
2024-12-13 15:15:00 | 6006.096667 | 126128.03 |
2024-12-16 15:15:00 | 6012.036190 | 126252.76 |
2024-12-17 15:15:00 | 6020.634286 | 126433.32 |
2024-12-18 15:15:00 | 6019.442381 | 126408.29 |
# Get the maximum of the SMA values. sma_max = history_df.current.max()
The IndicatorHistory
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 IndicatorHistory
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 IndicatorHistory
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.
// Get the historical values of an indicator over the last 30 days, applying the indicator to the security's high price. var history = IndicatorHistory(indicator, symbol, TimeSpan.FromDays(30), selector: Field.High);
# 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.
public class IndexMultiAssetIndicatorHistoryAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2024, 12, 19); // Add the target and reference securities. var targetSymbol = AddIndex("NDX").Symbol; var referenceSymbol = AddIndex("SPX").Symbol; // Create a 21-period Beta indicator. var beta = new Beta("", targetSymbol, referenceSymbol, 21); // Get the historical values of the indicator over the last 10 trading days. var history = IndicatorHistory(beta, new[] {targetSymbol, referenceSymbol}, 10, Resolution.Daily); // Get the average Beta value. var avgBeta = history.Average(indicatorDataPoint => indicatorDataPoint.Current.Value); } }
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()
If you already have a list of Slice objects, you can pass them to the IndicatorHistory
indicator_history
method to avoid the internal history request.
var slices = History(new[] {symbol}, 30, Resolution.Daily); var history = IndicatorHistory(indicator, slices);