How to do a SMA in Python

1 min

SMAs are by far the most famous technical indicators used in financial analysis.

Here is a simple example of how to compute it in Python using the Pandas library.

We get our data

In order to compute the SMA we first need to get a financial dataset.

Here we take APPLE stock price data from yahoo finance using the yfinance library.

# In order to get Apple stock price data from yahoo
import yfinance as yf

# We download the stock price from start date until end date
df = yf.download("AAPL", start="2021-01-01", end="2021-06-01")
We get our APPLE stock data from the yfinance library

We compute the SMA

Using the Close prices we got back from the yfinance download method we compute the a 10 days close price SMA using the pandas .rolling() method.

df["7d_sma"] = df["Close"].rolling(10).mean()
We compute the 10 days close sma using the rolling and mean methods

The rolling method here is used to get the past 10 days close prices and the mean method is used to compute the average of those prices.

In the end we have the 10 days close price SMA !

Plotting the SMA

In order to see if we did a good job of computing the SMA on the Close prices, we use the .plot() method to see the results.

df[["7d_sma", "Close"]].plot(title="Apple close price vs 10 days close sma")
Plotting the close prices along with the 10 days SMA
We can see the results of our 10 days SMA computation