Pandas' EMA not matching the stock's EMA?

后端 未结 1 2020
夕颜
夕颜 2021-02-04 10:53

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

1条回答
  •  伪装坚强ぢ
    2021-02-04 11:17

    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

                      ewm  backward_ewm
    Date                               
    2018-01-26  45.370936     48.205638
    2018-01-29  45.809895     48.008337
    2018-01-30  46.093714     47.800794
    2018-01-31  46.288599     47.696667
    2018-02-01  46.418256     47.650000
    

    This agrees with Marketwatch which says the EWMA(20) on 2018-02-01 was 46.42.

    0 讨论(0)
提交回复
热议问题