---
title: "Forex"
description: "Some of the Forex data you can get include prices, indicators, and universe selection data."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/asset-classes/forex
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/asset-classes/forex.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/20%20Historical%20Data/04%20Asset%20Classes/05%20Forex
modified: 2026-10-29
index: https://www.quantconnect.com/llms.txt
---

# Forex

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Historical Data > Asset Classes > Forex

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## 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](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/forex/handling-data.md#02-Quotes), 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, and close 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.

```python
class ForexQuoteBarHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        self.set_end_date(2024, 12, 31)
        # 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)
```

| symbol | time | askclose | askhigh | asklow | askopen | bidclose | bidhigh | bidlow | bidopen | close | high | low | open |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| EURUSD | 2024-12-18 23:56:00 | 1.03782 | 1.03809 | 1.03779 | 1.03809 | 1.03766 | 1.03794 | 1.03764 | 1.03794 | 1.037740 | 1.038015 | 1.037715 | 1.038015 |
| EURUSD | 2024-12-18 23:57:00 | 1.03772 | 1.03789 | 1.03769 | 1.03782 | 1.03757 | 1.03773 | 1.03755 | 1.03766 | 1.037645 | 1.037810 | 1.037620 | 1.037740 |
| EURUSD | 2024-12-18 23:58:00 | 1.03784 | 1.03786 | 1.03769 | 1.03772 | 1.03768 | 1.03771 | 1.03754 | 1.03757 | 1.037760 | 1.037785 | 1.037615 | 1.037645 |
| EURUSD | 2024-12-18 23:59:00 | 1.03801 | 1.03807 | 1.03784 | 1.03784 | 1.03784 | 1.03790 | 1.03768 | 1.03768 | 1.037925 | 1.037985 | 1.037760 | 1.037760 |
| EURUSD | 2024-12-19 00:00:00 | 1.03798 | 1.03803 | 1.03795 | 1.03801 | 1.03782 | 1.03788 | 1.03779 | 1.03784 | 1.037900 | 1.037955 | 1.037870 | 1.037925 |

```python
# Calculate the spread at each minute.
spread = history.askclose - history.bidclose
```

```python
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.

```python
# 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](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/forex/handling-data.md#03-Ticks), 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.

```python
class ForexTickHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        self.set_end_date(2024, 12, 31)
        # 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)
```

| symbol | time | askprice | bidprice | lastprice |
| --- | --- | --- | --- | --- |
| EURUSD | 2024-12-17 00:00:01.113566 | 1.0509 | 1.05074 | 1.050820 |
| EURUSD | 2024-12-17 00:00:01.158183 | 1.0509 | 1.05076 | 1.050830 |
| EURUSD | 2024-12-17 00:00:08.514324 | 1.0509 | 1.05074 | 1.050820 |
| EURUSD | 2024-12-17 00:00:09.034650 | 1.0509 | 1.05075 | 1.050825 |
| EURUSD | 2024-12-17 00:00:09.222588 | 1.0509 | 1.05074 | 1.050820 |

```python
# Calculate the spread.
spread = history.askprice - history.bidprice
```

```python
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.

```python
# 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](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/timeslices.md) 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.

```python
class SliceHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 1)
        self.set_end_date(2024, 12, 31)
        # 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](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/key-concepts.md) values, call the `indicator_history` method with an indicator and the security's `Symbol`.

```python
class ForexIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        self.set_end_date(2024, 12, 31)
        # 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.

```python
# Organize the historical indicator data into a DataFrame to enable pandas wrangling.
history_df = history.data_frame
```

|  | current | rollingsum |
| --- | --- | --- |
| 2024-12-13 19:00:00 | 1.051928 | 22.090485 |
| 2024-12-15 19:00:00 | 1.051755 | 22.086865 |
| 2024-12-16 19:00:00 | 1.051983 | 22.091650 |
| 2024-12-17 19:00:00 | 1.052336 | 22.099055 |
| 2024-12-18 19:00:00 | 1.051723 | 22.086175 |

```python
# 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](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/automatic-indicators.md#07-Alternative-Price-Fields) instead of the close (or mid-price) of each bar, pass a `selector` argument.

```python
# 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](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/supported-indicators/beta.md)). In this case, pass a list of the `Symbol` objects to the method.

```python
class ForexMultiAssetIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        self.set_end_date(2024, 12, 31)
        # 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

The following examples demonstrate some common practices for trading Forex with historical data.

### Example 1: Arbitration with Cointegration

The below example uses linear regression with historical data of 3 related Forex pairs to obtain the cointegrating vector between them. We measure the spread between the 3 Forex pairs and trade mean reversal upon their spread divergence.

```python
from sklearn.linear_model import LinearRegression

class CointegrationVectorRegressionAlgorithm(QCAlgorithm):
    # Threshold of spread divergence to enter position.
    entry_threshold = 0.0001

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(1000000)

        # Request Forex data to form the cointegrating vectors and trade.
        self.currency_pairs = [self.add_forex(pair).symbol for pair in ["USDJPY", "EURUSD", "EURJPY"]]

        # Initialize cointegration vector
        self.cointegration_vector = np.array([0.0, 0.0, 0.0])

        # Daily recalibration on the cointegrating vectors.
        self.schedule.on(
            self.date_rules.every_day(self.currency_pairs[0]),
            self.time_rules.at(0, 1),
            self.recalibrate
        )

    def on_data(self, slice: Slice) -> None:
        y = slice.quote_bars.get(self.currency_pairs[0])
        x1 = slice.quote_bars.get(self.currency_pairs[1])
        x2 = slice.quote_bars.get(self.currency_pairs[2])
        if y and x1 and x2:
            # Calculate the spread based on the cointegration vector.
            spread = self.calculate_spread(y.close, x1.close, x2.close, self.cointegration_vector)

            # Exit if spread is converged.
            if (self.portfolio[self.currency_pairs[0]].is_short and spread < 0) or (self.portfolio[self.currency_pairs[0]].is_long and spread > 0):
                self.liquidate()
                return

            # If the spread is too high, short the dependent and long the independent variables based on the weightings of the cointegrating vectors.
            # Else, vice versa.
            total_weights = 1 / (abs(self.cointegration_vector[1]) + abs(self.cointegration_vector[2]) + 1)
            if spread > self.entry_threshold:
                self.set_holdings(self.currency_pairs[0], -total_weights)
                self.set_holdings(self.currency_pairs[1], self.cointegration_vector[1] * total_weights)
                self.set_holdings(self.currency_pairs[2], self.cointegration_vector[2] * total_weights)
            elif spread < -self.entry_threshold:
                self.set_holdings(self.currency_pairs[0], total_weights)
                self.set_holdings(self.currency_pairs[1], -self.cointegration_vector[1] * total_weights)
                self.set_holdings(self.currency_pairs[2], -self.cointegration_vector[2] * total_weights)

    def recalibrate(self) -> None:
        # Calculate the cointegration vector from historical data.
        log_price = np.log(self.history(self.currency_pairs, 252, Resolution.DAILY).unstack(0).close.dropna())
        self.cointegration_vector = self.calculate_cointegrating_vector(log_price)

    def calculate_cointegrating_vector(self, history: pd.DataFrame) -> np.array:
        try:
            # Perform regression.
            lr = LinearRegression().fit(history[self.currency_pairs[1:]], history[self.currency_pairs[0]])

            # The coefficients array will contain the coefficients for each independent variable.
            return np.array([lr.intercept_, lr.coef_[0], lr.coef_[1]])
        except:
            return self.cointegration_vector

    def calculate_spread(self, y: float, x1: float, x2: float, cointegration_vector: np.array) -> float:
        # Using the cointegration vector to calculate the spread.
        return np.log(y) - (cointegration_vector[0] + np.log(x1) * cointegration_vector[1] + np.log(x2) * cointegration_vector[2])
```
