Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using latest panda APIs to compute exponential moving average

I have a python v3.6 function using panda to compute exponential moving average of a list containing floating numbers. Here is the function and it is tested to work;

def get_moving_average(values, period):
    import pandas as pd
    import numpy as np

    values = np.array(values)
    moving_average = pd.ewma(values, span=period)[-1]
    return moving_average

However, pd.ewma is a deprecated function and although it still works, I would like to use the latest API to use panda the correct way.

Here is the documentation for the latest exponential moving average API.

http://pandas.pydata.org/pandas-docs/stable/api.html#exponentially-weighted-moving-window-functions

I modified the original function into this to use the latest API;

def get_moving_average(values, period, type="exponential"):
    import pandas as pd
    import numpy as np

    values = np.array(values)
    moving_average = 0
    moving_average = pd.ewm.mean(values, span=period)[-1]
    return moving_average

Unfortunately, I got the error AttributeError: module 'pandas' has no attribute 'EWM'

like image 884
user3848207 Avatar asked Oct 18 '25 10:10

user3848207


1 Answers

The ewm() method now has a similar API to moving() and expanding(): you call ewm() and then follow it with a compatible method like mean(). For example:

df=pd.DataFrame({'x':np.random.randn(5)})

df['x'].ewm(halflife=2).mean()

0   -0.442148
1   -0.318170
2    0.099168
3   -0.062827
4   -0.371739
Name: x, dtype: float64

If you try df['x'].ewm() without arguments it will tell you:

Must pass one of com, span, halflife, or alpha

See below for documentation that may be more clear than the link in the OP:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ewm.html#pandas.DataFrame.ewm

http://pandas.pydata.org/pandas-docs/stable/computation.html#exponentially-weighted-windows

like image 126
JohnE Avatar answered Oct 20 '25 01:10

JohnE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!