How to Build a 20-EMA on MetaTrader with Python and Pandas
Learn how to build an EMA calculator to use on any candlestick data.
Learn how to build an EMA calculator to use on any candlestick data.
The 20 Exponential Moving Average (20-EMA) is a popular indicator for day traders. It can be used to provide rapid indications of likely price movements, making it incredibly useful to incorporate in an algorithmic trading bot.
The signal is incredibly valuable as it can be used on any timeframe where candles are provided, making it useful on almost any exchange.
In this article, I’ll show you to build a generic EMA calculator and then show you how easy it can be to apply it to any timeframe of your choice. All code is used at your own risk 😄
What would it take for Crypto, AI, and Cyber to truly change the world?
No spam. Unsubscribe anytime.
The formula for an EMA is:
EMA = Todays_Price * multiplier + Yesterdays_EMA * (1 — multiplier)
The multiplier is simply:
Smoothing_Value / (Number of Periods +1)
Most traders use 2 as the smoothing value, so we will do the same.
Astute readers probably immediately noticed a problem. yesterdays_EMA
is a calculated value, which begs the question: “How do we figure out the first EMA value?”
This brings about a couple of notes I’ll outline here for your awareness:
Therefore, the answer to the question “How do we calculate the first value?” is to use a Simple Moving Average (SMA).
Converting this into a function, we have the following generic EMA calculator function:
# Define function to calculate an arbitrary EMA
def calc_ema(dataframe, ema_size):
# Create column string
ema_name = "ema_" + str(ema_size)
# Create the multiplier
multiplier = 2/(ema_size + 1)
# Calculate the initial value (SMA)
pandas.set_option('display.max_columns', None)
initial_mean = dataframe['close'].head(ema_size).mean()
# Iterate through Dataframe
for i in range(len(dataframe)):
if i == ema_size:
dataframe.loc[i, ema_name] = initial_mean
#print(f"Initial Mean: {initial_mean}")
elif i > ema_size:
ema_value = dataframe.loc[i, 'close'] * multiplier + dataframe.loc[i-1, ema_name]*(1-multiplier)
#ema_value = round(ema_value, 4)
dataframe.loc[i, ema_name] = ema_value
else:
dataframe.loc[i, ema_name] = 0.00
return dataframe
To expand this function to calculate a 20-EMA, add this line to your Python code:
ema_20 = calc_ema(dataframe=<your dataframe>, ema_size=20)
Make sure that the dataframe you pass meets the minimum size required (300 candles for a 20-EMA) and you’re all set.
I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.
❤