How to do a SMA in Python

1 min readFinancePandasDataDataFramePlot
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.