Exponential Moving Average(EMA) using Python Pandas

Anoob Paul
3 min readFeb 11, 2024

--

The ewm function in pandas allows us to apply exponential weighting to data points in a series.We can calculate exponential moving averages using ewm functions. Below is the sample implementation for ewm function to calculate the ema’s as required.

data['EMA_9'] = data['Close'].ewm(span=9, adjust=False).mean()

the above code snippet calculates the 9 ema on closing price of the candle.

EMA is a technical indicator which help us to determine the direction of a stock movement based on the past prices. if we say 9 ema, then the moving average of past 9 candles are considered.

Tested this code using fyers api and here are the steps.

First step is to get history data from fyers api. Here we are using nifty 50 index, 5 minutes candles and time frame for today and yesterday. we can give resolution as “D” for daily candles. date_format should be given as 1 to set the format as yyyy-mm-dd

fyers history function will retrieve the Time stamp , OHLC values for the given date and timeframe as input.

 hdata = {
"symbol":"NSE:NIFTY50-INDEX",
"resolution":"5",
"date_format":"1",
"range_from":yesterday_date,
"range_to":today_date,
"cont_flag":"1"
}
response = fyers.history(data=hdata) # fetching the data for the timeframe
# print(response)

the response has the candles data containing array of particular time stamp
1. Current epoch time
2. Open Value
3. Highest Value
4. Lowest Value
5. Close Value
6. Volume

the epoch time format need to be converted to yyyy-mm-dd hh:mm:ss. we are looping through the candles and coverting the time format as below. Once converted, the first column is set as timestamp in our preferred format.

   for candle in response['candles']:
epoch_time = candle[0]
timestamp = datetime.fromtimestamp(epoch_time).strftime('%Y-%m-%d %H:%M:%S')
candle[0] = timestamp

response are extracted to a dataframe and heading section is added for redability . Here we are setting the titles as TimeStamp, Open, High, Low Close and Volume to the dataframe.

    data = pd.DataFrame.from_dict(response['candles'])
cols = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
data.columns = cols

Now comes the ema calcumation. We can determine any EMAs by changing the span values.For example, if we need to get the 20 EMA, simply change the span =15 and set to dictionary as EMA_20

data['EMA_9'] = data['Close'].ewm(span=9, adjust=False).mean()
data['EMA_15'] = data['Close'].ewm(span=15, adjust=False).mean()
print (data)

Following the the response after printing the data frame. Since we have retrieved the data for bank nifty indices, the volume is coming as 0 as there is no trading happeing on indices.

              Timestamp     Open      High       Low    Close  Volume         EMA_9        EMA_15
0 2024-02-08 09:15:00 22009.7 22011.05 21959.55 21993.0 0 21993.000000 21993.000000
1 2024-02-08 09:20:00 21992.0 22008.05 21988.65 21991.6 0 21992.720000 21992.825000
2 2024-02-08 09:25:00 21991.8 22005.60 21991.35 21998.5 0 21993.876000 21993.534375
3 2024-02-08 09:30:00 21997.2 22002.85 21980.10 21987.9 0 21992.680800 21992.830078
4 2024-02-08 09:35:00 21988.6 21991.35 21969.10 21973.9 0 21988.924640 21990.463818
.. ... ... ... ... ... ... ... ...
145 2024-02-09 15:05:00 21780.8 21795.20 21774.30 21789.3 0 21774.332199 21768.511839
146 2024-02-09 15:10:00 21790.2 21800.35 21780.35 21782.8 0 21776.025759 21770.297859
147 2024-02-09 15:15:00 21783.9 21790.20 21777.10 21777.9 0 21776.400607 21771.248127
148 2024-02-09 15:20:00 21777.7 21784.40 21772.50 21780.8 0 21777.280486 21772.442111
149 2024-02-09 15:25:00 21781.3 21787.25 21773.75 21786.0 0 21779.024389 21774.136847

Written the complete function for a better understanding. Please import the pandas and other required libraires as needed.

def calculate_ema():
today_date = datetime.now().strftime('%Y-%m-%d')
yesterday_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
# Date format : yyyy-mm-dd

# today_date ="2024-02-09"
# yesterday_date="2024-02-08"
print(f"Today's date: {today_date}")
print(f"Yesterday's date: {yesterday_date}")

hdata = {
"symbol":"NSE:NIFTY50-INDEX",
"resolution":"5",
"date_format":"1",
"range_from":yesterday_date,
"range_to":today_date,
"cont_flag":"1"
}
response = fyers.history(data=hdata) # fetching the data for the timeframe
# print(response)

for candle in response['candles']:
epoch_time = candle[0]
timestamp = datetime.fromtimestamp(epoch_time).strftime('%Y-%m-%d %H:%M:%S')
candle[0] = timestamp

data = pd.DataFrame.from_dict(response['candles'])
cols = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
data.columns = cols
data['EMA_9'] = data['Close'].ewm(span=9, adjust=False).mean()
data['EMA_15'] = data['Close'].ewm(span=15, adjust=False).mean()
print (data)

Hope this helps in our learning . thank you

--

--

Anoob Paul

scribbles from my learning. interested in java, python and financial markets