Initial values of an exponential moving average in python pandas

Asked

Viewed 782 times

-2

Hello,

I’m trying to implement the calculation of an exponential moving average with the python pandas package. I know there are several ways of exponential weighting for a moving average, but the one I’m interested in is expressed in pseudocode for a data set y_i's as:

MME_i = ((y_i - MME_i-1) * k) + MME_i-1

Where i is the position of the data, k is defined by the number of periods (n) of the average as: k = 2 / (1 + n). The calculation of averages starts from the nth value and is used as an approximation to the first average value MME_i-1 a simple average of n's first values.

In that initial approach is my problem, using the pre-built pandas package function Series.ewm I can’t adjust this approach to initial values. I tried to turn the 'Adjust' option on and off and I could not get the desired results.

import pandas as pd
import numpy as np

dados = np.array([[22.17,21.18],[23.08,21.01],[22.68,20.63],[22.22,20.26],[20.85,19.9],[20.19,19.73],[21.58,19.64],[19.63,19.29],[21.95,19.23],[19.18,18.73],[18.18,18.65],[15.01,18.73],[17.39,19.41],[18.53,19.78],[15.7,20.01],[15.4,20.79],[16.05,21.77],[13.95,22.81],[18,24.42],[15.99,25.59],[21.5,27.33],[24.95,28.39],[28.09,29.02],[31,29.19],[30.5,28.86],[29.81,28.56],[31.47,28.33],[31.4,27.76],[32.41,27.1],[28.95,26.13],[29,25.62],[28.85,25],[28.66,np.nan],[28.16,np.nan],[25.77,np.nan],[23.66,np.nan],[23.18,np.nan],[23.63,np.nan],[23.63,np.nan],[23.83,np.nan],[23.02,np.nan],[24.03,np.nan],[23.61,np.nan]])
df = pd.DataFrame(dados, columns = ['Dados','MME_12_controle'])
df = df.iloc[::-1]
n = 12
df['MME_12'] = df.Dados.ewm(span = n ,min_periods = n , adjust=False).mean()
print(df)

Where 'Data' is the values to calculate the mean, 'Mme_12_control' is the average calculated by the method described (rounded to 2 decimal places) and 'MME_12' the values calculated with the function Series.ewm.

Question: Is there a way to calculate this exponential moving average method using the Pandas or Python libraries?

1 answer

0


I do not understand why my question was negative. But after some time I was able to calculate the exponential moving average starting with an arithmetic mean approximation for the first term and using the pre-built function .ewm. I hope it can be useful to someone else, follow the code:

df['MME_12'] = pd.Series(data = df['Dados'].iloc[:n].mean(), index = [df['Dados'].index[n-1]]).append(df['Dados'].iloc[n:]).ewm(alpha=(2/(1+n)), adjust = False).mean()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.