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

QuantConnect

FOREX Data

Introduction

The FOREX Data by QuantConnect serves 71 foreign exchange (FOREX) pairs, starts on various dates from January 2007, and is delivered on any frequency from tick to daily. This dataset is created by QuantConnect processing raw tick data from OANDA.

FOREX data does not include ask and bid sizes.

For more information about the FOREX Data dataset, including CLI commands and pricing, see the dataset listing.

About the Provider

QuantConnect was founded in 2012 to serve quants everywhere with the best possible algorithmic trading technology. Seeking to disrupt a notoriously closed-source industry, QuantConnect takes a radically open-source approach to algorithmic trading. Through the QuantConnect web platform, more than 50,000 quants are served every month.

Getting Started

The following snippet demonstrates how to request data from the FOREX dataset:

self.eurusd = self.add_forex("EURUSD", Resolution.DAILY).symbol
_symbol = AddForex("EURUSD", Resolution.Daily).Symbol;

Data Summary

The following table describes the dataset properties:

PropertyValue
Start DateJanuary 2007
Asset Coverage71 Currency pairs
Data DensityDense
ResolutionTick, Second, Minute, Hour, & Daily
TimezoneUTC
Market HoursAlways Open, except from Friday 5 PM EST to Sunday 5 PM EST

Requesting Data

To add FOREX data to your algorithm, call the AddForexadd_forex method. Save a reference to the Forex Symbol so you can access the data later in your algorithm.

class ForexAlgorithm (QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2019, 2, 20)
        self.set_end_date(2019, 2, 21)
        self.set_cash(100000)

        self.eurusd = self.add_forex('EURUSD', Resolution.MINUTE).symbol

        self.set_benchmark(self.eurusd)
namespace QuantConnect.Algorithm.CSharp
{
    public class ForexAlgorithm : QCAlgorithm
    {
        private Symbol _symbol;

        public override void Initialize()
        {
            SetStartDate(2019, 2, 20);
            SetEndDate(2019, 2, 21);
            SetCash(100000);

            _symbol = AddForex("EURUSD", Resolution.Minute).Symbol;

            SetBenchmark(_symbol);
        }
    }
}

For more information about creating Forex subscriptions, see Requesting Data.

Accessing Data

To get the current Forex data, index the QuoteBarsquote_bars, or Ticksticks properties of the current Slice with the Forex Symbol. Slice objects deliver unique events to your algorithm as they happen, but the Slice may not contain data for your security at every time step. To avoid issues, check if the Slice contains the data you want before you index it.

def on_data(self, slice: Slice) -> None:
    if self.eurusd in slice.quote_bars:
        quote_bar = slice.quote_bars[self.eurusd]
        self.log(f"{self.eurusd} bid at {slice.time}: {quote_bar.bid.close}")

    if self.eurusd in slice.ticks:
        ticks = slice.ticks[self.eurusd]
        for tick in ticks:
            self.log(f"{self.eurusd} price at {slice.time}: {tick.price}")
public override void OnData(Slice slice)
{
    if (slice.QuoteBars.ContainsKey(_symbol))
    {
        var quoteBar = slice.QuoteBars[_symbol];
        Log($"{_symbol} bid at {slice.Time}: {quoteBar.Bid.Close}");
    }

    if (slice.Ticks.ContainsKey(_symbol))
    {
        var ticks = slice.Ticks[_symbol];
        foreach (var tick in ticks)
        {
            Log($"{_symbol} price at {slice.Time}: {tick.Price}");
        }
    }
}

You can also iterate through all of the data objects in the current Slice.

def on_data(self, slice: Slice) -> None:
    for symbol, quote_bar in slice.quote_bars.items():
        self.log(f"{symbol} bid at {slice.time}: {quote_bar.bid.close}")

    for symbol, ticks in slice.ticks.items():
        for tick in ticks:
            self.log(f"{symbol} price at {slice.time}: {tick.price}")
public override void OnData(Slice slice)
{
    foreach (var kvp in slice.QuoteBars)
    {
        var symbol = kvp.Key;
        var quoteBar = kvp.Value;
        Log($"{symbol} bid at {slice.Time}: {quoteBar.Bid.Close}");
    }

    foreach (var kvp in slice.Ticks)
    {
        var symbol = kvp.Key;
        var ticks = kvp.Value;
        foreach (var tick in ticks)
        {
            Log($"{symbol} price at {slice.Time}: {tick.Price}");
        }
    }
}

For more information about accessing Forex data, see Handling Data.

Historical Data

To get historical Forex data, call the Historyhistory method with the Forex Symbol. If there is no data in the period you request, the history result is empty.

# DataFrame
history_df = self.history(self.eurusd, 100, Resolution.MINUTE)

# QuoteBar objects
history_quote_bars = self.history[QuoteBar](self.eurusd, 100, Resolution.MINUTE)

# Tick objects
history_ticks = self.history[Tick](self.eurusd, timedelta(seconds=10), Resolution.TICK)
// QuoteBar objects 
var historyQuoteBars = History<QuoteBar>(_symbol, 100, Resolution.Minute);

// Tick objects 
var historyTicks = History<Tick>(_symbol, TimeSpan.FromSeconds(10), Resolution.Tick);

For more information about historical data, see History Requests.

Remove Subscriptions

To remove a Forex pair subscription, call the RemoveSecurityremove_security method.

self.remove_security(self.eurusd)
RemoveSecurity(_symbol);

The RemoveSecurityremove_security method cancels your open orders for the security and liquidates your holdings.

Supported Assets

The following table shows the available Forex pairs:

Example Applications

The FOREX price data enables you to trade currency pairs in the global market. Examples include the following strategies:

  • Exploring the impact that daily worldwide news cycles have on international currencies
  • Carry Trade: borrow from a lower interest currency pair to fund the purchase of a currency pair with a higher interest rate

Classic Algorithm Example

The following example algorithm implements a FOREX carry trade. It buys the FOREX pair of the country with the lowest interest rate and sells the FOREX pair of the country with the highest interest rate.

from AlgorithmImports import *
from QuantConnect.DataSource import *

class ForexCarryTradeAlgorithm(QCAlgorithm):

    def initialize(self) -> None:

        self.set_start_date(2008, 1, 1) 
        self.set_cash(25000)
        
        # We will use hard-coded interest rates for each base currency
        self.rates = {
            "USDAUD": 1.5,    # Australia
            "USDCAD": 0.5,    # Canada
            "USDCNY": 4.35,   # China
            "USDEUR": 0.0,    # Euro Area
            "USDINR": 6.5,    # India
            "USDJPY": -0.1,   # Japan
            "USDMXN": 4.25,   # Mexico
            "USDTRY": 7.5,    # Turkey
            "USDZAR": 7.0     # South Africa
        }

        # Subscribe to forex data for trading
        for ticker in self.rates:
            self.add_forex(ticker, Resolution.DAILY)

        # Use a month counter as variable to control rebalancing
        self.month = -1

    def on_data(self, slice: Slice) -> None:
        # Monthly rebalance checker
        if self.month == self.time.month:
            return
        self.month = self.time.month
        
        # Long the pair with highest interest rate and sell the pair with the lowest to earn the max monetary inflation difference between the two
        sorted_rates = sorted(self.rates.items(), key = lambda x: x[1])
        self.set_holdings(sorted_rates[0][0], -0.5)
        self.set_holdings(sorted_rates[-1][0], 0.5)
using QuantConnect.DataSource;

namespace QuantConnect
{
    public class ForexCarryTradeAlgorithm : QCAlgorithm
    {
        // Use a month counter as variable to control rebalancing
        private int _month = -1;
        private Dictionary<string, decimal> _rates;
        
        public override void Initialize()
        {
            SetStartDate(2008, 1, 1);
            SetCash(25000);
            
            // We will use hard-coded interest rates for each base currency
            _rates = new Dictionary<string, decimal>()
            {
                {"USDAUD", 1.5m},    // Australia
                {"USDCAD", 0.5m},    // Canada
                {"USDCNY", 4.35m},   // China
                {"USDEUR", 0.0m},    // Euro Area
                {"USDINR", 6.5m},    // India
                {"USDJPY", -0.1m},   // Japan
                {"USDMXN", 4.25m},   // Mexico
                {"USDTRY", 7.5m},    // Turkey
                {"USDZAR", 7.0m}     // South Africa
            };

            // Subscribe to forex data for trading
            foreach (var ticker in _rates.Keys)
            {
                AddForex(ticker, Resolution.Daily);
            }
        }

        public override void OnData(Slice slice)
        {
            // Monthly rebalance checker
            if (_month == Time.Month) return;
            _month = Time.Month;

            // Long the pair with highest interest rate and sell the pair with the lowest to earn the max monetary inflation difference between the two
            var sortedRates = (from kvp in _rates orderby kvp.Value ascending select kvp.Key).ToArray();
            SetHoldings(sortedRates[0], -0.5);
            SetHoldings(sortedRates[sortedRates.Length-1], 0.5);
        }
    }
}

Framework Algorithm Example

The following example algorithm implements a FOREX carry trade. It buys the FOREX pair of the country with the lowest interest rate and sells the FOREX pair of the country with the highest interest rate.

from AlgorithmImports import *
from QuantConnect.DataSource import *

class ForexCarryTradeAlgorithm(QCAlgorithm):

    def initialize(self) -> None:

        self.set_start_date(2008, 1, 1) 
        self.set_cash(25000)
        
        def to_symbol(ticker: str) -> Symbol:
            return Symbol.create(ticker, SecurityType.FOREX, Market.OANDA)
        
        # We will use hard-coded interest rates for each base currency
        rates = {
            to_symbol("USDAUD"): 1.5,    # Australia
            to_symbol("USDCAD"): 0.5,    # Canada
            to_symbol("USDCNY"): 4.35,   # China
            to_symbol("USDEUR"): 0.0,    # Euro Area
            to_symbol("USDINR"): 6.5,    # India
            to_symbol("USDJPY"): -0.1,   # Japan
            to_symbol("USDMXN"): 4.25,   # Mexico
            to_symbol("USDTRY"): 7.5,    # Turkey
            to_symbol("USDZAR"): 7.0     # South Africa
        }
        
        self.set_universe_selection(ManualUniverseSelectionModel(list(rates.keys())))
        # A custom alpha model to emit insight according to interest rate
        self.set_alpha(IntestRatesAlphaModel(rates))
        # Equal size to capitalize the monetary value of quote currency only based on interest rate difference
        # For dollar-neutral to save margin cost
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_MONTH))

class IntestRatesAlphaModel(AlphaModel):
    def __init__(self, rates: float) -> None:
        self.rates = rates
        # Variable to control the rebalancing time
        self.month = -1
                
    def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]:
        # Monthly rebalance
        if self.month == algorithm.time.month:
            return []
        self.month = algorithm.time.month

        # # Long the pair with highest interest rate and sell the pair with the lowest to earn the max monetary inflation difference between the two
        sorted_rates = sorted(self.rates.items(), key = lambda x: x[1])
        self.set_holdings(sorted_rates[0][0], -0.5)
        self.set_holdings(sorted_rates[-1][0], 0.5)
        sorted_rates = sorted(self.rates.items(), key = lambda x: x[1])
        return Insight.group(
            Insight.price(sorted_rates[0][0], Expiry.END_OF_MONTH, InsightDirection.UP),
            Insight.price(sorted_rates[-1][0], Expiry.END_OF_MONTH, InsightDirection.DOWN)
        )
using QuantConnect.DataSource;

namespace QuantConnect
{
    public class ForexCarryTradeAlgorithm : QCAlgorithm
    {
        public override void Initialize()
        {
            SetStartDate(2008, 1, 1);
            SetCash(25000);
            
            Symbol toSymbol(string ticker)
            {
                return QuantConnect.Symbol.Create(ticker, SecurityType.Forex, Market.Oanda);
            }
            
            // We will use hard-coded interest rates for each base currency
            var rates = new Dictionary<Symbol, decimal>()
            {
                {toSymbol("USDAUD"), 1.5m},    // Australia
                {toSymbol("USDCAD"), 0.5m},    // Canada
                {toSymbol("USDCNY"), 4.35m},   // China
                {toSymbol("USDEUR"), 0.0m},    // Euro Area
                {toSymbol("USDINR"), 6.5m},    // India
                {toSymbol("USDJPY"), -0.1m},   // Japan
                {toSymbol("USDMXN"), 4.25m},   // Mexico
                {toSymbol("USDTRY"), 7.5m},    // Turkey
                {toSymbol("USDZAR"), 7.0m}     // South Africa
            };
 
            SetUniverseSelection(new ManualUniverseSelectionModel(rates.Keys));
            // A custom alpha model to emit insight according to interest rate
            SetAlpha(new IntestRatesAlphaModel(rates));
            // Equal size to capitalize the monetary value of quote currency only based on interest rate difference
            // For dollar-neutral to save margin cost
            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(Expiry.EndOfMonth));
        }
    }
    
    public class IntestRatesAlphaModel : AlphaModel
    {
        // Variable to control the rebalancing time
        private int _month = -1;
        private Dictionary<Symbol, decimal> _rates;

        public IntestRatesAlphaModel(Dictionary<Symbol, decimal> rates)
        {
            _rates = rates;
        }

        public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice)
        {
            // Monthly rebalance
            if (_month == algorithm.Time.Month)
            {
                return Enumerable.Empty<Insight>();
            }
            _month = algorithm.Time.Month;

            // Long the pair with highest interest rate and sell the pair with the lowest to earn the max monetary inflation difference between the two
        sorted_rates = sorted(self.rates.items(), key = lambda x: x[1])
        self.set_holdings(sorted_rates[0][0], -0.5)
        self.set_holdings(sorted_rates[-1][0], 0.5)
            var sortedRates = (from kvp in _rates orderby kvp.Value ascending select kvp.Key).ToArray();
            
            return Insight.Group(
                Insight.Price(sortedRates[0], Expiry.EndOfMonth, InsightDirection.Up),
                Insight.Price(sortedRates[sortedRates.Length-1], Expiry.EndOfMonth, InsightDirection.Down)
                );
        }
    }
}

Data Point Attributes

The FOREX dataset provides QuoteBar and Tick objects.

QuoteBar Attributes

QuoteBar objects have the following attributes:

Tick Attributes

Tick objects have the following attributes:

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: