# Calculating 50 and 200 SMA with Python for Stocks Technical Analysis

#### Automated Python Trading Bot

### Calculating 50 and 200 SMA with Python for Stocks Technical Analysis

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:

- Levels of support
- Levels of resistance
- The ‘Death Cross’ — when the 50-day SMA crosses below the 200-day SMA
- The ‘Golden Cross’ — when the 200-day SMA crosses above the 50-day SMA
- Smoothing out price volatility

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.

### What You Need

- Python 3. I’ll be using Python 3.10 for this series.
- An exchange to retrieve data from. I’ll be using MetaTrader 5.
- (Optional) An IDE. I’ll be using JetBrains Pycharm Community Edition.

### Build Your Own Trading Bot Series

Check out how to build your own Python MetaTrader 5 Expert Advisor trading bot with my series.

### Working GitHub Code

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 😁

### Project Setup

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”.

### Develop SMA Function

Using a modular approach, the first step is to develop a generic moving average function.

The function should:

- Use the
**closing price**of a given stock/cryptocurrency/future - Calculate an average on an arbitrary number of entries and timeframes

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.

### Identifying Death Crosses and Golden Crosses

However, this approach can *also* be used to identify Death Cross or Golden Cross events. Let’s see how.

#### Death Cross

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.”**

#### Golden Cross

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.”**

#### Combined Together

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)
```

### Wrap It Up

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.