Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

python - Calculate EMA with Pandas?

I am trying to calculate the EMA myself with Pandas, but I am stuck...

This is the code I want to implement with Pandas

# smooth the data using the exponential moving average
EMA_ = 0.0
gamma = 0.1
df['EMA_1']=np.nan

for i in range(len(df)):
    EMA_ = gamma * df['Price'].iloc[i] + (1-gamma)*EMA_
    print(EMA_)
    df['EMA_1'].iloc[i] = EMA_
def get_EMA(df, EMA=0.0, gamma=0.1):
    df['EMA']=np.nan
    df['EMA'].iloc[0] = df['Price'].iloc[0]
    
    return df.assign(
        EMA = lambda d: gamma*d['Price'] + d['EMA'].expanding().apply(lambda x: x.tail(1)*(1-gamma))
    )

So I tried to expand on the column 'EMA' and take the last element of that Series to calculate the next EMA.

Price   EMA_1   EMA
0   1   0.10000 1.0
1   10  1.09000 NaN
2   2   1.18100 NaN
3   20  3.06290 NaN
4   5   3.25661 NaN

Someone? :)

question from:https://stackoverflow.com/questions/66049542/calculate-ema-with-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...