Home Python Trading Strategy How to Build a Simple SMA Trading Strategy Using Python

# How to Build a Simple SMA Trading Strategy Using Python

This tutorial will explain the procedure to build a Simple Moving Trading Strategy in Python; it will begin by explaining the indicator and subsequently implementing a Python example.

## What is a simple moving average (SMA)?

The SMA is a trading indicator that calculates the average in a range of days; it is for many traders the most important technical indicator.

The following table shows how to calculate a four-day SMA; its third column (Formula SMA(4)) shows the procedure.

For example, a 4-day Simple Moving Average for day 11 is:

Day 11:

In the chart provided earlier, we see the evolution of Price and SMA; it is evident that from month 10, there is an upward trend in Price; to identify the change in trends is the utility of this indicator.

If there is no relevant news, in theory, Price should always have the same value; therefore, SMA should be equal to Price; on the other hand, when Price crosses SMA, in theory, it shows that there is important news that influences the closing price.

If there is no relevant news, in theory, Price should always have the same value; therefore, SMA should be equal to Price; on the other hand, when Price crosses SMA, in theory, it shows that there is important news that influences the closing price.

## Trading rules of the strategy

We will implement the following trading rule:

• when the closing price is higher than the SMA(15)

Sell SPY

• when the closing price is lower or equal to the SMA(15)

This strategy will implement only long positions. In this tutorial, we will not consider short positions.

## Importing libraries – how to

The procedure to import the Python libraries is:

Pandas and numpy are packages for data analysis; yfinance is a package to download data from Yahoo Finance, and matplotlib is for plotting data.

## How to import data

The following image shows how to download data from SPY; the start period is 2021-01-01, and the end period is 2021-12-31, respectively; we will use the SPY (stock_name). Subsequently, the package yfinance will retrieve data through (stock = yf.Ticker(stock_name) and stock_data = stock.history(interval=’1d’, start= start, end= end):

The variable stock_data is a pandas data frame with historical financial information of SPY:

The function .head() retrieves the first five values from the stock_data; .head(20) will get the first 20 values, etc.

In case, it is necessary to see all columns, print(stock_data.head().to_string()) does the trick:

## How to calculate daily returns in Python

The daily return is how much in percentage the closing price has changed from one day to another:

Using stock_data[”Close”].pct_change(), we will get the previous formula. The code is:

When we print the result:

Please note the green arrow is an example of the previous formula.

## Simple Moving Average Estimation in Python

The following image shows how to estimate a 15-day Simple Moving Average:

The .rolling(interval).mean() function will generate a pandas series with the SMA(15) values associated with each date; in the next image, we will see two green rectangles; the big rectangle shows the data, while the small rectangle shows the SMA(15) calculated with the values from the big rectangle; also, see the two red rectangles.

## Plotting Close Price and SMA

The following code shows how to plot the closing price and rolling SMA; it is simple, we chose two columns, Close and SMA, using stock_data.loc[:, [”Close”, “SMA”]]; next we add .plot(). Finally, we show the chart using plt.show():

Let’s see how is the evolution of both series. We can see how SMA(15) is a smooth representation of the closing price.

## How to calculate trading signals

In this part, we are going to calculate the signals; first, remember the trading rules:

• when the closing price is higher than the SMA(15)

Sell SPY

• when the closing price is lower or equal to the SMA(15)

The numpy function np.where(stock_data[“Close”] > stock_data[“SMA”], 1, 0) creates an array with values 1 and 0; A value of 1 means the closing price is higher than SMA(15); while a value of cero (0) means the closing price is lower or equal to the SMA(15):

Let’s see the last five elements with .tail():

Calculate Strategy Performance

The following image shows how to calculate the returns:

What does .shift()?; let’s see with the following example:

If we print stock_data[”Close”].pct_change() * stock_data[”Signal”].shift(1), we will get:

For illustration purposes, I added the green lines (in your output, you will not have them). They show how the multiplication between both variables is.

Remember, one (1) means Price > SMA(15) and implies a long position; therefore, the multiplication between one (1) by its associated return will be the return. When Price <= SMA(15) means there is no position; hence, zero (0) by any value is zero.

stock_data[”Cummulative Returns”] shows the cumulative return (or equity curve). Let’s see how was the performance of the strategy:

After one year, the final capital is 108.56%, which represents an 8.56% yearly return.