pythonpandasbacktrader

Difference between the calculation results of the BackTrader indicators EMA and Pandas.DataFrame.EWM


I found a problem when using the backtrader EMA indicator to calculate the values. The larger the period value input( ex. 120days ), the greater the difference between the value of the EMA displayed by the market software and the value calculated by BackTrader.

Computing with pandas.dataframe.ewm doesn't have this problem.(load same close data)

This error decreases as the bar time advances, so I'm guessing the formula is correct, but what's wrong with the initialization calculation of EMA? Does anyone know about it?

The EMA output I calculated by BackTrader.ind.ema is as follows: backtrader ema result backtrader ema result2

and the ema4 output I calculated by Pandas.dataframe.ewm is as follows:

pandas output

Below is the class i write by backtrader

class BaseStrategy(bt.Strategy):
    """base strategy"""

    _name = "base"
    params = (("printlog", False),)


class EMaCrossStrategy(BaseStrategy):

    params = (
        ("emaperiod", {"ema1": 13, "ema2": 30, "ema3": 60, "ema4": 120})
    )
    def __init__(self):
        self.ema1 = bt.ind.EMA(self.dataclose, period=self.p.emaperiod["ema1"])
        self.ema2 = bt.ind.EMA(self.dataclose,period=self.p.emaperiod["ema2"])
        self.ema3 = bt.ind.EMA(self.dataclose,period=self.p.emaperiod["ema3"])
        self.ema4 = bt.ind.EMA(self.dataclose,period=self.p.emaperiod["ema4"])

Below is the code i write use pandas.dataframe.ewm:

import pandas as pd



def calculate_ema(day_count: int, close: pd.DataFrame):
    """
           calculate ema
           :param day_count:
           :param close:
           :return:
    """
    result = close.ewm(span=day_count, adjust=False).mean()
    result = result.iloc[day_count:]
    return result.dropna(axis=0, how='any').round(2)

Solution

  • Circumvent the EMA calculation accuracy problem by building my own DataFeed class