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

Asset Classes

CFD

Introduction

This page explains how to get historical quotes and indicator data for CFDs.

Quotes

To get historical quote data, call the History<QuoteBar> method with a security's Symbol.

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.

public class CFDQuoteBarHistoryAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2024, 12, 19);
        // Get the Symbol of a security.
        var symbol = AddCfd("XAUUSD").Symbol;
        // Get the 5 trailing minute QuoteBar objects of the security. 
        var history = History<QuoteBar>(symbol, 5, Resolution.Minute);
        // Iterate through the QuoteBar objects and calculate the spread.
        foreach (var bar in history)
        {
            var t = bar.EndTime;
            var spread = bar.Ask.Close - bar.Bid.Close;
        }
    }
}
class CFDQuoteBarHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of a security.
        symbol = self.add_cfd('XAUUSD').symbol
        # Get the 5 trailing minute QuoteBar objects of the security in DataFrame format. 
        history = self.history(QuoteBar, symbol, 5, Resolution.MINUTE)
askcloseaskhighasklowaskopenbidclosebidhighbidlowbidopenclosehighlowopen
symboltime
XAUUSD2024-12-18 23:56:002607.962608.532607.912608.532607.492607.992607.432607.992607.7252608.262607.6702608.260
2024-12-18 23:57:002608.312608.362607.922607.962607.742607.802607.452607.492608.0252608.082607.6852607.725
2024-12-18 23:58:002608.472608.552608.282608.312607.892608.012607.712607.742608.1802608.282607.9952608.025
2024-12-18 23:59:002609.482609.702608.432608.472609.052609.122607.892607.892609.2652609.412608.1602608.180
2024-12-19 00:00:002609.482610.172609.482609.482609.102609.652609.032609.052609.2902609.912609.2552609.265
# Calculate the spread at each minute.
spread = history.askclose - history.bidclose
symbol  time               
XAUUSD  2024-12-18 23:56:00    0.47
        2024-12-18 23:57:00    0.57
        2024-12-18 23:58:00    0.58
        2024-12-18 23:59:00    0.43
        2024-12-19 00:00:00    0.38
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<Tick> method with a security's Symbol and Resolution.Tick.

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.

public class CFDTickHistoryAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2024, 12, 19);
        // Get the Symbol of a security.
        var symbol = AddCfd("XAUUSD").Symbol;
        // Get the trailing 2 days of ticks for the security.
        var history = History<Tick>(symbol, TimeSpan.FromDays(2), Resolution.Tick);
        // Calculate the spread.
        var spread = history.Select(tick => tick.AskPrice - tick.BidPrice);
    }
}
class CFDTickHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of a security.
        symbol = self.add_cfd('XAUUSD').symbol
        # Get the trailing 2 days of ticks for the security in DataFrame format.
        history = self.history(symbol, timedelta(2), Resolution.TICK)
askpricebidpricelastprice
symboltime
XAUUSD2024-12-17 00:00:00.0479692652.072651.612651.840
2024-12-17 00:00:00.7167462652.032651.532651.780
2024-12-17 00:00:00.7420112652.022651.492651.755
2024-12-17 00:00:00.7708192652.022651.472651.745
2024-12-17 00:00:00.7816222652.022651.492651.755
# Calculate the spread.
spread = history.askprice - history.bidprice
symbol  time                      
XAUUSD  2024-12-17 00:00:00.047969    0.46
        2024-12-17 00:00:00.716746    0.50
        2024-12-17 00:00:00.742011    0.53
        2024-12-17 00:00:00.770819    0.55
        2024-12-17 00:00:00.781622    0.53
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 Historyhistory 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.
        AddCfd("XAUUSD");
        // Get the historical Slice objects over the last 5 minutes for all the subcriptions in your algorithm.
        var history = History(5, Resolution.Minute);
        // Iterate through each historical Slice.
        foreach (var slice in history)
        {
            // Iterate through each QuoteBar in this Slice.
            foreach (var kvp in slice.QuoteBars)
            {
                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_cfd('XAUUSD')
        # 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 IndicatorHistoryindicator_history method with an indicator and the security's Symbol.

public class CFDIndicatorHistoryAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2024, 12, 19);
        // Get the Symbol of a security.
        var symbol = AddCfd("SPX500USD").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 CFDIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Get the Symbol of a security.
        symbol = self.add_cfd('SPX500USD').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 18:00:006033.309524126699.5
2024-12-15 18:00:006039.390476126827.2
2024-12-16 18:00:006045.090476126946.9
2024-12-17 18:00:006049.180952127032.8
2024-12-18 18:00:006044.276190126929.8
# Get the maximum of the SMA values.
sma_max = history_df.current.max()

The IndicatorHistoryindicator_history method resets your indicator, makes a history request, and updates the indicator with the historical data. Just like with regular history requests, the IndicatorHistoryindicator_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 IndicatorHistoryindicator_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 ask price.
var history = IndicatorHistory(indicator, symbol, TimeSpan.FromDays(30), selector: Field.AskClose);
# 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.

public class CFDMultiAssetIndicatorHistoryAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2024, 12, 19);
        // Add the target and reference securities.
        var targetSymbol = AddCfd("XAUUSD").Symbol;
        var referenceSymbol = AddCfd("SPX500USD").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 CFDMultiAssetIndicatorHistoryAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 12, 19)
        # Add the target and reference securities.
        target_symbol = self.add_cfd('XAUUSD').symbol
        reference_symbol = self.add_cfd('SPX500USD').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 IndicatorHistoryindicator_history method to avoid the internal history request.

var slices = History(new[] {symbol}, 30, Resolution.Daily);
var history = IndicatorHistory(indicator, slices);

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: