Pandas' Ema Not Matching The Stock's Ema?
I am trying to use Python (with Pandas) to calculate the 20-day Exponential Moving Averages (EMA) of daily stock data for Intel (INTC). Pandas has a number of ways of doing this, a
Solution 1:
Sort the DataFrame so that the dates are in increasing order.
Since your data is in decreasing order by date, if you don't sort the dates first, your ewm
calculation exponentially weights the earliest dates the most, rather than the latest date (as it should be).
import pandas as pd
df = pd.read_csv('intc_data.txt', parse_dates=['Date'], index_col=['Date'])
df['backward_ewm'] = df['Close'].ewm(span=20,min_periods=0,adjust=False,ignore_na=False).mean()
df = df.sort_index()
df['ewm'] = df['Close'].ewm(span=20,min_periods=0,adjust=False,ignore_na=False).mean()
print(df[['ewm', 'backward_ewm']].tail())
yields
ewmbackward_ewmDate2018-01-26 45.37093648.2056382018-01-29 45.80989548.0083372018-01-30 46.09371447.8007942018-01-31 46.28859947.6966672018-02-01 46.41825647.650000
This agrees with Marketwatch which says the EWMA(20) on 2018-02-01 was 46.42.
Solution 2:
I suggest using Pandas TA to calculate technical indicators in python. I find it more accurate and has many more indicators than the ones that come with pandas.
Using Pandas TA, the 20 period exponential moving average is calculated like:
import pandas_ta as ta
data["EMA20"] = ta.ema(df2["Close"], length=20)
Post a Comment for "Pandas' Ema Not Matching The Stock's Ema?"