Calculating 50 and 200 SMA with Python for Stocks Technical Analysis
Learn how to add 50-day and 200-day SMA’s to your automated trading bot in Python.
Learn how to add 50-day and 200-day SMA’s to your automated trading bot in Python.
Stock market technical analysis uses the 50-day and 200-day Simple Moving Average (SMA) to inform trading decisions. According to Investopedia, the SMA’s can be used to determine:
Incorporating this analysis into your algorithmic trading can be a powerful way to trade forex, crypto, stocks, and more.
In this article, I’ll show you how.
Check out how to build your own Python MetaTrader 5 Expert Advisor trading bot with my series.
All the code for this article is contained in my GitHub Repository trading_library
. Feel free to browse it and use it as you like — I only ask that you acknowledge me in your code and give me a shout-out on LinkedIn if you use it ❤
All code is used at your own risk 😁
If you review the GitHub setup, you’ll see a modular code setup. This allows us to constantly expand the functionality of the code, something I’d highly recommend for anyone. The GitHub project shows you everything you need to trade on MetaTrader 5, and is linked to my series “How to Build a MetaTrader 5 Python Trading Bot”.
Using a modular approach, the first step is to develop a generic moving average function.
The function should:
The function calculate_sma
below shows how to do this using Pandas Dataframes:
# Function to calculate the average of n number of entries
def calculate_sma(symbol, sma_size, timeframe, exchange):
# Retrieve the raw data
if exchange == "mt5":
raw_data = mt5.query_historic_data(symbol=symbol, timeframe=timeframe, number_of_candles=sma_size)
# Add other exchanges as they become available
# Convert raw_data into a dataframe
dataframe = pandas.DataFrame(raw_data)
# Get the average of the close price
sma = dataframe['close'].mean()
return sma
This function can be leveraged to define the 50-day and 200-day Simple Moving Average.
Here’s the code for the 50-day SMA calculate_50_day_sma
:
# Function to calculate the 50-day SMA
def calculate_50_day_sma(symbol, exchange):
return calculate_sma(symbol=symbol, sma_size=50, timeframe="D1", exchange=exchange)
Here’s the code for the 200-day SMA calculate_200_day_SMA
:
# Function to calculate the 200-day SMA
def calculate_200_day_sma(symbol, exchange):
return calculate_sma(symbol=symbol, sma_size=200, timeframe="D1", exchange=exchange)
So far so good. Using these code samples, you’ll be able to smooth out day-to-day price volatility and start to develop areas of support and resistance.
However, this approach can also be used to identify Death Cross or Golden Cross events. Let’s see how.
In stocks technical analysis, a Death Cross is defined as when the 50-day SMA crosses below the 200-day SMA. From a code perspective, this could be restated as:
“If the previous 50-day SMA is above the 200-day SMA and the current 50-day SMA is below the 200-day SMA then a Death Cross has occurred.”
The same approach could be used for a Golden Cross. In stock market technical analysis, a Golden Cross is when the 50-day SMA crosses above the 200-day SMA. From a code perspective:
“If the previous 50-day SMA is below the 200-day SMA and the current 50-day SMA is above the 200-day SMA, then a Golden Cross has occurred.”
Combing together, a pseudo-code example could be generated:
Get the previous 2 50-day SMAs
Get the previous 2 200-day SMAs
if 50-day SMA [1] > 200-day SMA [1] AND 50-day SMA [0] < 200-day SMA: Death Cross!else if 50-day SMA [1] < 200-day SMA [1] AND 50-day SMA [0] > 200-day SMA: Golden Cross!else: Do Nothing
Following the modular approach to code development, here’s the base Python function.
# Function to identify if a Death Cross or Golden Cross has occurred
def calculate_a_cross(symbol, timeframe, exchange):
pandas.set_option("display.max_columns", None)
pandas.set_option("display.max_rows", None)
# Retreive the raw data
if exchange == "mt5":
sma_50_raw = mt5.query_historic_data(symbol=symbol, timeframe=timeframe, number_of_candles=51)
sma_200_raw = mt5.query_historic_data(symbol=symbol, timeframe=timeframe, number_of_candles=201)
# Convert into Dataframe
sma_50_dataframe = pandas.DataFrame(sma_50_raw)
sma_200_dataframe = pandas.DataFrame(sma_200_raw)
# Extract the four averages
# Current 50 SMA
sma_50_current = sma_50_dataframe['close'].tail(50).mean()
# Previous 50 SMA
sma_50_previous = sma_50_dataframe['close'].head(50).mean()
# Current 200 SMA
sma_200_current = sma_200_dataframe['close'].tail(200).mean()
# Previous 200 SMA
sma_200_previous = sma_200_dataframe['close'].head(200).mean()
# Compare the results
if sma_50_previous > sma_200_previous and sma_50_current < sma_200_current:
return "DeathCross"
elif sma_50_previous < sma_200_previous and sma_50_current > sma_200_current:
return "GoldenCross"
else:
return "NoCross"
Adding in the function for the classic Day events:
# Function to calculate Death Cross and Golden Cross for daily trading
def calculate_day_cross(symbol, exchange):
return calculate_a_cross(symbol=symbol, timeframe="D1", exchange=exchange)
And that’s it! You’ve got all the code you need to calculate a Death Cross and Golden Cross into your automated trading bot!
Pretty cool!
There are tons you can do with this! For instance, you could extend the functionality of the cross to implement a new trading strategy. You could use it to clear out your portfolio.
Whatever it is, I wish you all the best with your trading journey.