How to Build a 20-EMA on MetaTrader with Python and Pandas
Python Trading Bot
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 😄
How to Code in Python using Pandas
Pseudo Code
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.
How to Calculate the First Value?
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:
- The most accurate EMA is the EMA which includes all the values.
- In the real world where this could be millions of candles, the compute time required to calculate an EMA can be huge.
- Our testing indicates that the sweet spot is between 300–1,000 candles (1,000 for a 200-EMA, 300 for a 20-EMA)
Therefore, the answer to the question “How do we calculate the first value?” is to use a Simple Moving Average (SMA).
Generic EMA Function
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
How to Calculate a 20-EMA
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.
Say Hi!
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.
❤