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

Asset Classes

Forex

Introduction

This page explains how to get historical data for Forex. Some of the data you can get include quotes, ticks, and indicator data.

Quotes

To get historical quote data, call the history method with the QuoteBar type and a security's Symbol. This method returns a DataFrame with columns for the open, high, low, close, and size of the bid and ask quotes. The columns that don't start with "bid" or "ask" are the mean of the quote prices on both sides of the market.

Select Language:
class ForexQuoteBarHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of a security.
        symbol = self.add_forex('EURUSD').symbol
        # Get the 5 trailing minute QuoteBar objects of the security in DataFrame format. 
        history = self.history(QuoteBar, symbol, 5, Resolution.MINUTE)
askcloseaskhighasklowaskopenbidclosebidhighbidlowbidopenclosehighlowopen
symboltime
EURUSD2024-12-18 23:56:001.037821.038091.037791.038091.037661.037941.037641.037941.0377401.0380151.0377151.038015
2024-12-18 23:57:001.037721.037891.037691.037821.037571.037731.037551.037661.0376451.0378101.0376201.037740
2024-12-18 23:58:001.037841.037861.037691.037721.037681.037711.037541.037571.0377601.0377851.0376151.037645
2024-12-18 23:59:001.038011.038071.037841.037841.037841.037901.037681.037681.0379251.0379851.0377601.037760
2024-12-19 00:00:001.037981.038031.037951.038011.037821.037881.037791.037841.0379001.0379551.0378701.037925
# Calculate the spread at each minute.
spread = history.askclose - history.bidclose
symbol  time               
EURUSD  2024-12-18 23:56:00    0.00016
        2024-12-18 23:57:00    0.00015
        2024-12-18 23:58:00    0.00016
        2024-12-18 23:59:00    0.00017
        2024-12-19 00:00:00    0.00016
dtype: float64

If you intend to use the data in the DataFrame to create QuoteBar 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 QuoteBar objects instead of a DataFrame, call the history[QuoteBar] method.

# Get the 5 trailing minute QuoteBar objects of the security in QuoteBar format. 
history = self.history[QuoteBar](symbol, 5, Resolution.MINUTE)
# Iterate through each QuoteBar and calculate the spread.
for quote_bar in history:
    t = quote_bar.end_time
    spread = quote_bar.ask.close - quote_bar.bid.close

Ticks

To get historical tick data, call the history method with a security's Symbol and Resolution.TICK. This method returns a DataFrame that contains data on bids, asks, and last trade prices.

Select Language:
class ForexTickHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of a security.
        symbol = self.add_forex('EURUSD').symbol
        # Get the trailing 2 days of ticks for the security in DataFrame format.
        history = self.history(symbol, timedelta(2), Resolution.TICK)
askpricebidpricelastprice
symboltime
EURUSD2024-12-17 00:00:01.1135661.05091.050741.050820
2024-12-17 00:00:01.1581831.05091.050761.050830
2024-12-17 00:00:08.5143241.05091.050741.050820
2024-12-17 00:00:09.0346501.05091.050751.050825
2024-12-17 00:00:09.2225881.05091.050741.050820
# Calculate the spread.
spread = history.askprice - history.bidprice
symbol  time                      
EURUSD  2024-12-17 00:00:01.113566    0.00016
        2024-12-17 00:00:01.158183    0.00014
        2024-12-17 00:00:08.514324    0.00016
        2024-12-17 00:00:09.034650    0.00015
        2024-12-17 00:00:09.222588    0.00016
dtype: float64

If you intend to use the data in the DataFrame to create Tick 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 Tick objects instead of a DataFrame, call the history[Tick] method.

# Get the trailing 2 days of ticks for the security in Tick format. 
history = self.history[Tick](symbol, timedelta(2), Resolution.TICK)
# Iterate through each quote tick and calculate the spread.
for tick in history:
    t = tick.end_time
    spread = tick.bid_price - tick.ask_price

Ticks are a sparse dataset, so request ticks over a trailing period of time or between start and end times.

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_forex('EURUSD')
        # Get the historical Slice objects over the last 5 minutes for all the subcriptions in your algorithm.
        history = self.history(5, Resolution.MINUTE)
        # Iterate through each historical Slice.
        for slice_ in history:
            # Iterate through each QuoteBar in this Slice.
            for symbol, quote_bar in slice_.bars.items():
                midprice = quote_bar.close

Indicators

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

Select Language:
class ForexIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of a security.
        symbol = self.add_forex('EURUSD').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-13 19:00:001.05192822.090485
2024-12-15 19:00:001.05175522.086865
2024-12-16 19:00:001.05198322.091650
2024-12-17 19:00:001.05233622.099055
2024-12-18 19:00:001.05172322.086175
# 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 ask price.
history = self.indicator_history(indicator, symbol, timedelta(30), selector=Field.ASK_CLOSE)

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 ForexMultiAssetIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Add the target and reference securities.
        target_symbol = self.add_forex('AUDUSD').symbol
        reference_symbol = self.add_forex('EURUSD').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: