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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…