Implementing Moving Averages in Python | by Posey | Towards Data Science

Moving averages are used and discussed quite commonly by technical analysts and traders alike. If you’ve never heard of a moving average, it is likely you have at least seen one in practice. A moving average can help an analyst filter noise and create a smooth curve from an otherwise noisy curve. It is important to note moving averages lag because they are based on historical data, not current price.
The most commonly used Moving Averages (MAs) are the simple and exponential moving average. Simple Moving Average (SMA) takes the average over some set number of time periods. So a 10 period SMA would be over 10 periods (usually meaning 10 trading days).
The Simple Moving Average formula is a very basic arithmetic mean over the number of periods.
The Exponential Moving Average (EMA) is a wee bit more involved. First, you should find the SMA. Second, calculate the smoothing factor. Then, use your smoothing factor with the previous EMA to find a new value. In this way, the latest prices are given higher weights, whereas the SMA assigns equal weight to all periods. We’ll see this clearer in our graphs below.
Certain periods on a moving average are widely used. Many technical traders and market participants will cite the 10, 20, 50, 100, or 200 day moving averages. It all depends on preference or desired granularity. Breaks above and below the moving average are important signals and trigger active traders and algorithms to execute trades depending on if the break is above or below the moving average.
One example of using moving averages is following crossovers. For example, a bullish crossover occurs when the short-term SMA crosses above the long-term SMA. A bearish crossover occurs when the short-term SMA crosses below the long-term SMA.
We start by plotting our desired stock over a 1 month period. In this case, we’ll check out AMD. I’m a big fan of the IEX API and really enjoy using the Python API for IEX.
import pandas as pdimport numpy as npfrom datetime import datetimeimport matplotlib.pyplot as pltimport pyEX as pticker = 'AMD'timeframe = '1y'df = p.chartDF(ticker, timeframe)df = df[['close']]df.reset_index(level=0, inplace=True)df.columns=['ds','y']plt.plot(df.ds, df.y)plt.show()
Next, we throw together a few lines to get the simple moving average working. The code should be intuitive. It simply follows the formulas stated above.
rolling_mean = df.y.rolling(window=20).mean()rolling_mean2 = df.y.rolling(window=50).mean()plt.plot(df.ds, df.y, label='AMD')plt.plot(df.ds, rolling_mean, label='AMD 20 Day SMA', color='orange')plt.plot(df.ds, rolling_mean2, label='AMD 50 Day SMA', color='magenta')plt.legend(loc='upper left')plt.show()
Next, we’ll implement the exponential moving average (EMA). For this we add a bit of granularity and go on a shorter time-frame. In this case we’re doing a 1 year time-frame.
exp1 = df.y.ewm(span=20, adjust=False).mean()exp2 = df.y.ewm(span=50, adjust=False).mean()plt.plot(df.ds, df.y, label='AMD')plt.plot(df.ds, exp1, label='AMD 20 Day EMA')plt.plot(df.ds, exp2, label='AMD 50 Day EMA')plt.legend(loc='upper left')plt.show()
Let’s use the same graph as above and examine our crossover concept from earlier. We can see that using this signal we could have predicted the price trend of AMD. When short-term crosses above long-term we get a buy signal. When short-term passes below the longer-term we get a sell signal.
You can see above how the stock went bullish for a long period of time following the bullish crossover and bearish for a long period of time following the bearish crossover.
To support my writing and get full access to all articles on Medium, visit https://posey.medium.com/membership
You can check out the code for moving averages here: https://github.com/Poseyy/TechnicalAnalysis
Let’s continue the conversation on Twitter!
www.investopedia.com
en.wikipedia.org
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.