Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I compute a weighted moving average using pandas

Tags:

python

pandas

Using pandas I can compute

  • simple moving average SMA using pandas.stats.moments.rolling_mean
  • exponential moving average EMA using pandas.stats.moments.ewma

But how do I compute a weighted moving average (WMA) as described in wikipedia http://en.wikipedia.org/wiki/Exponential_smoothing ... using pandas?

Is there a pandas function to compute a WMA?

like image 281
thatshowthe Avatar asked Mar 08 '12 16:03

thatshowthe


People also ask

How do pandas calculate moving averages?

In Python, we can calculate the moving average using . rolling() method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .

How do you calculate SMA in pandas?

SMA can be implemented by using pandas. DataFrame. rolling() function is used to calculate the moving average over a fixed window. Where the window will be a fixed size and it is the number of observations used for calculating the statistic.

How do you calculate exponential weighted moving average in Python?

To calculate exponential weights moving averages in Python, we can use the pandas ewm() function.


2 Answers

Using pandas you can calculate a weighted moving average (wma) using:
.rolling() combined with .apply()

Here's an example with 3 weights and window=3:

data = {'colA': random.randint(1, 6, 10)}
df = pd.DataFrame(data)

weights = np.array([0.5, 0.25, 0.25])
sum_weights = np.sum(weights)

df['weighted_ma'] = (df['colA']
    .rolling(window=3, center=True)
    .apply(lambda x: np.sum(weights*x) / sum_weights, raw=False)
)


Please note that in .rolling() I have used argument center=True.
You should check if this applies with your usecase or whether you need center=False.

like image 174
Sander van den Oord Avatar answered Oct 14 '22 15:10

Sander van den Oord


No, there is no implementation of that exact algorithm. Created a GitHub issue about it here:

https://github.com/pydata/pandas/issues/886

I'd be happy to take a pull request for this-- implementation should be straightforward Cython coding and can be integrated into pandas.stats.moments

like image 24
Wes McKinney Avatar answered Oct 14 '22 13:10

Wes McKinney