How to compute the simple moving average (SMA) in Python with Pandas
• 2 minSimple moving averages are one of the core indicators in technical analysis.
Every one has its own preference on the period but I found that the 50 and the 200 are used quite often.
Here is how to compute them with Pandas.
We first get our prices
Using the yfinance library we can get stock prices quite easily.
# 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="2018-01-01", end="2021-06-01")
How to compute the 50 SMA
As you can see the desired period is passed in the rolling method.
We apply a rolling window to the adjusted close price to compute the 50 SMA adjusted close. You could use the close price instead but it is always better better to take the adjusted close.
How to compute the 200 SMA
It is pretty much the same thing with the 200 period.
df["20_sma"] = df["Adj Close"].rolling(200).mean()
Check the results
As a sanity check, it is always nice to graph your solution.
Here is the code
# We plot the results
df[["200_sma","50_sma","Adj Close"]].plot(figsize=(8,4), grid=True, title="SMA 50 vs SMA 200")
Good job! You now know how to compute an SMA in Python.
You could also based on those 50 and 200 SMAs compute the golden cross, which is when a smaller period SMA such as the 50 SMA crosses a longer period SMA such as the 200 SMA.
I will soon write an article on how to compute the golden cross based in Python.
So stay tuned!
More on Financial Analysis
In the meantime, if you want to know more about DataFrame and Pandas. Check out the other articles I wrote on the topic, just here :