Exponential Moving Average and Implementation with Python

Dayanand Shah
4 min readJan 26, 2023

--

Exponential moving average

An exponential moving average (EMA) is a type of moving average that gives more weight to recent data and less weight to older data.

To calculate the EMA, we have the following formula:

EMA = (Price(t) * k) + (EMA(y) * (1 – k))

Where:
Price(t) is the price at time (t)
EMA(y) is the previous period’s EMA
k is the smoothing constant, which is typically set at 2/(n+1) where n is the number of periods for the EMA

The EMA formula is based on the idea of giving more weight to more recent data points. The smoothing constant, k, controls the degree to which more recent data points are given more weight. The larger the value of k, the more weight is given to more recent data points, and the more quickly the EMA will respond to changes in the data set.

The weighting factor is typically set at a value between 0 and 1, with a higher value giving more weight to recent data and a lower value giving more weight to older data. A common value for the weighting factor is 0.2, which means that the most recent data is given a weight of 20% and the oldest data is given a weight of 2%.

One of the main advantages of using an EMA is that it is able to respond more quickly to changes in the data set than an SMA (Simple Moving Average). This is because it places more weight on recent data, which is more relevant for short-term trends. However, because it gives more weight to recent data, it can also be more prone to volatility and can produce false signals. It is a technical indicator often used in stock and currency trading to identify short-term trends and make trading decisions.

Let us see EMA function with Python Implementation

import numpy as np

def exponential_moving_average(prices, period, weighting_factor=0.2):
ema = np.zeros(len(prices))
sma = np.mean(prices[:period])
ema[period - 1] = sma
for i in range(period, len(prices)):
ema[i] = (prices[i] * weighting_factor) + (ema[i - 1] * (1 - weighting_factor))
return ema

prices = [100, 105, 110, 115, 120, 125, 130, 135, 140, 145]
period = 5
weighting_factor = 0.2

ema = exponential_moving_average(prices, period, weighting_factor)
print(ema)

Above code explanation

This code defines a function called exponential_moving_average that takes in three parameters: prices, period, and weighting_factor. The prices parameter is an array of closing prices for a stock or currency, the period parameter is the number of days over which to calculate the EMA, and the weighting_factor parameter is the weighting factor to use in the EMA calculation.

The function first initializes an array called ema filled with zeroes, and then it calculates the SMA for the first period days. It uses the SMA as the base for the EMA calculation. Then it uses a for loop to iterate through the remaining days, using the EMA formula to calculate the EMA for each day and storing the result in the ema array. Finally, it returns the ema array.

In the example, I have defined the prices, period and weighting factor, then passed it to the function and printed the EMA’s.

Another python implementation

We can use Pandas library to easily calculate the exponential moving average (EMA) for a given dataset. The pandas.DataFrame.ewm method can be used to apply an exponential weighting function to a dataset, which can then be used to calculate the EMA.

Here is an example of how you would use the ewm method to calculate the EMA for a dataset

import pandas as pd

# Create a dataset with closing prices for a stock
prices = [100, 105, 110, 115, 120, 125, 130, 135, 140, 145]
df = pd.DataFrame({'close': prices})

# Calculate the EMA with a period of 5 days and a weighting factor of 0.2
df['ema'] = df['close'].ewm(span=5, adjust=False, min_periods=5).mean()

print(df)

Above code explanation

In this example, I have first defined the prices, then created a DataFrame with the closing prices as the column ‘close’ and then used the ewm method to calculate the EMA for the dataset and added that column as 'ema' in the dataframe. The span parameter is used to set the period for the EMA calculation, in this case 5 days. The adjust parameter is set to False to use an unbiased EWM, which is the same as using a weighting factor of 2/(span + 1) and min_periods parameter is used to set the minimum number of periods required to calculate the EMA.

Check the pandas documentation for more.

Thanks for the read I hope now you have understood the above concept.

If you found this information helpful and would like to stay updated with more valuable insights and analysis, please consider following my page. I strive to provide high-quality content and keep our readers informed with the latest trends and developments in the field. Thank you for your support!

--

--

Dayanand Shah
Dayanand Shah

Responses (1)