11

I try to calculate ema with pandas but the result is not good. I try 2 techniques to calculate :

The first technique is the panda's function ewn:

window = 100
c = 2 / float(window + 1)
df['100ema'] = df['close'].ewm(com=c).mean()

But the last result of this function gives. 2695.4 but the real result is 2656.2

The second technique is

window = 100
c = 2 / float(window + 1)
df['100sma'] = df['close'].rolling(window).mean()
df['100ema'] = (c * df['close']) + ((1 - c) * df['100sma'])

The result is 2649.1 it's closer than first technique but is always not good

The sma function give the good result

** EDIT **

The response is

df['100ema'] = pd.Series.ewm(df['close'], span=window).mean()
john
  • 468
  • 1
  • 9
  • 26

2 Answers2

7

If you want to calculate EWMA or any technical indicator in Python, I recommend using ta-lib.

Casey Jones
  • 155
  • 9
  • 1
    nice a want use this lib instead of breaking my head – john Apr 06 '18 at 20:07
  • I spent days and was willing to spend days more implementing like 20 of these on my own. thank you. Of all of the things I googled in my work. "Python TA library" wasnt one of them – Hudson Hughes Nov 06 '18 at 23:33
  • 2
    df is my dataframe and 'close' is the closing price of the stock. I calculated ema for various timeperiods using these instructions: >>> df['ema12'] = talib.EMA(df['close'],timeperiod=12) >>> df['ema18'] = talib.EMA(df['close'],timeperiod=18) >>> df['ema25'] = talib.EMA(df['close'],timeperiod=25) – KawaiKx Oct 25 '19 at 20:00
2
expwighted_avg = ts_log.ewm(halflife=12).mean()

where 'ts_log' is dataframe or series of Time Series

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103