Implementing Moving Averages in Python

Source: UnsplashThe 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.

Simple Moving Average Equation…Source: InvestopediaThe 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.

Exponential Moving Average Equation…Source: InvestopediaCertain 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.

Implementing in PythonWe 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.



ds, df.


show()Using PyEX to plot AMDNext, 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.



mean()rolling_mean2 = df.





ds, df.

y, label='AMD')plt.


ds, rolling_mean, label='AMD 20 Day SMA', color='orange')plt.


ds, rolling_mean2, label='AMD 50 Day SMA', color='magenta')plt.

legend(loc='upper left')plt.

show()20 & 50 Day SMAs Plotted Using MatplotlibNext, 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.


ewm(span=20, adjust=False).

mean()exp2 = df.


ewm(span=50, adjust=False).



ds, df.

y, label='AMD')plt.


ds, exp1, label='AMD 20 Day EMA')plt.


ds, exp2, label='AMD 50 Day EMA')plt.

legend(loc='upper left')plt.

show()20 & 50 Day EMAs Plotted Using MatplotlibLet’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.

Bullish Crossover in Green, Bearish Crossover in RedYou 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.

You can check out the code for moving averages here: https://github.

com/Poseyy/TechnicalAnalysisReferencesMoving Average – MAA moving average (MA) is a widely used indicator in technical analysis that helps smooth out price action by filtering…www.


comMoving average – WikipediaIn statistics, a moving average ( rolling average or running average) is a calculation to analyze data points by…en.


org.. More details

Leave a Reply