self.get_historical_prices#
- lumibot.strategies.strategy.Strategy.get_historical_prices(self, asset: Asset | str, length: int, timestep: str = '', timeshift: timedelta = None, quote: Asset = None, exchange: str = None, include_after_hours: bool = True, return_polars: bool = False)
Get historical pricing data for a given symbol or asset.
Return data bars for a given symbol or asset. Any number of bars can be return limited by the data available. This is set with ‘length’ in number of bars. Bars may be returned as daily or by minute. And the starting point can be shifted backwards by time or bars.
- Parameters:
asset (str or Asset) – The symbol string representation (e.g. AAPL, GOOG, …) or asset object. Cryptocurrencies must also specify the quote currency.
length (int) – The number of rows (number of timesteps)
timestep (str) –
Time interval for each bar. Supports multiple formats:
- Basic formats:
"minute"
or"day"
- Single minute or day bars
- Multi-timeframe formats (automatically aggregated):
Minutes:
"5min"
,"5m"
,"5 minutes"
,"15min"
,"30m"
, etc.Hours:
"1h"
,"1hour"
,"2h"
,"4 hours"
, etc. (converted to minutes)Days:
"2d"
,"2 days"
,"1 week"
,"1w"
, etc.Flexible formatting: Case-insensitive, with/without spaces
When using multi-timeframe formats, the method automatically fetches the underlying minute or day data and resamples it to your desired timeframe. Default value depends on the data_source (minute for alpaca, day for yahoo, …)
timeshift (timedelta) –
None
by default. If specified indicates the time shift from the present. If backtesting in Pandas, use integer representing number of bars.quote (Asset) – The quote currency for crypto currencies (e.g. USD, USDT, EUR, …). Default is the quote asset for the strategy.
exchange (str) – The exchange to pull the historical data from. Default is None (decided based on the broker)
include_after_hours (bool) – Whether to include after hours data. Default is True. Currently only works with Interactive Brokers.
return_polars (bool) – If True, return Bars with Polars DataFrame for better performance. Default is False (returns pandas). When False and data is in Polars format, a warning will be issued about the conversion.
- Returns:
The bars object with all the historical pricing data. Please check the
Entities.Bars
object documentation for more details on how to use Bars objects. To get aDataFrame
from the Bars object, usebars.df
.- Return type:
Bars
Example
Extract 2 rows of SPY data with one day timestep between each row with the latest data being 24h ago (timedelta(days=1)) (in a backtest)
>>> # Get the data for SPY for the last 2 days >>> bars = self.get_historical_prices("SPY", 2, "day") >>> # To get the DataFrame of SPY data >>> df = bars.df >>> >>> # Then, to get the DataFrame of SPY data >>> df = bars.df >>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have) >>> self.log_message(f"Last price of BTC in USD: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")
>>> # Get the data for AAPL for the last 30 minutes >>> bars = self.get_historical_prices("AAPL", 30, "minute") >>> >>> # Then, to get the DataFrame of SPY data >>> df = bars.df >>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have) >>> self.log_message(f"Last price of AAPL: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")
>>> # Get 5-minute bars for the last 10 5-minute periods (using new multi-timeframe support) >>> bars = self.get_historical_prices("SPY", 10, "5min") >>> df = bars.df # DataFrame with 10 rows of 5-minute OHLCV data >>> >>> # Get hourly bars for the last 24 hours >>> bars = self.get_historical_prices("AAPL", 24, "1h") >>> >>> # Get 15-minute bars (multiple format options work) >>> bars = self.get_historical_prices("TSLA", 20, "15m") # Short format >>> bars = self.get_historical_prices("TSLA", 20, "15min") # Alternative >>> bars = self.get_historical_prices("TSLA", 20, "15 minutes") # With space
>>> # Get the historical data for an AAPL option for the last 30 minutes >>> asset = self.create_asset("AAPL", asset_type="option", expiration=datetime.datetime(2020, 1, 1), strike=100, right="call") >>> bars = self.get_historical_prices(asset, 30, "minute") >>> >>> # Then, to get the DataFrame of SPY data >>> df = bars.df >>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have) >>> self.log_message(f"Last price of BTC in USD: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")
>>> # Get the data for BTC in USD for the last 2 days >>> asset_base = self.create(symbol="BTC", asset_type="crypto"), >>> asset_quote = self.create(symbol="USDT", asset_type="crypto"), >>> >>> bars = self.get_historical_prices(asset_base, 2, "day", quote=asset_quote) >>> >>> # Then, to get the DataFrame of SPY data >>> df = bars.df >>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have) >>> self.log_message(f"Last price of BTC in USD: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")