# Moving Averages Strategy Indicators with Python

Last Update: February 6, 2020

Strategy indicators consist of identifying trend-following or mean-reversion asset price patterns. Main indicators include single or multiple, lagging or leading technical indicators.

This topic is part of Quantitative Trading Analysis with Python course. Feel free to take a look at Course Curriculum.

This tutorial has an educational and informational purpose and doesn’t constitute any type of trading or investment advice. All content, including code and data, is presented for personal educational use exclusively and with no guarantee of exactness of completeness. Past performance doesn’t guarantee future results. Please read full Disclaimer.

An example of trend-following lagging strategy indicators is simple moving average which consists of asset prices overlay for identifying uptrends and downtrends.

1. Strategy indicator calculation.

$sma_{k}\left&space;(&space;c&space;\right&space;)_{t}=\frac{1}{k}\sum_{i=0}^{k-1}\left&space;(&space;c_{t-i}&space;\right&space;)$

Where $c_{t}$ = current period asset close prices, $sma_{k}\left&space;(&space;c&space;\right&space;)_{t}$ = current period close prices  $k$ periods simple moving average.

2. Python code example.

2.1. Import Python packages [1].

import pandas as pd
import matplotlib.pyplot as plt

2.2. Moving averages strategy indicators data reading.

• Data: S&P 500® index replicating ETF (ticker symbol: SPY) daily open, high, low, close, adjusted close prices and volume (2016).
SPY = pd.read_csv('Data//Moving-Averages-Strategy-Indicators-Data.txt', index_col='Date', parse_dates=True)

2.3. Moving averages strategy indicators calculation and chart.

• Moving averages strategy indicators number of periods not fixed and only included for educational purposes.
SPY['SMA(5)'] = pd.DataFrame.rolling(SPY['SPY.Close'], window=5).mean()
SPY['SMA(20)'] = pd.DataFrame.rolling(SPY['SPY.Close'], window=20).mean()
fig1, ax = plt.subplots()
ax.plot(SPY['SPY.Close'], label='SPY.Close')
ax.plot(SPY['SMA(5)'], label='SMA(5)')
ax.plot(SPY['SMA(20)'], label='SMA(20)')
ax.legend(loc='upper left')
plt.suptitle('SPY Close Prices SMA(5) & SMA(20) Strategy Indicators')
plt.show()
##### 3. References.

[1] Wes McKinney. “Data Structures for Statistical Computing in Python.” Proceedings of the 9th Python in Science Conference. 2010.

John D. Hunter. “Matplotlib: A 2D Graphics Environment.” Computing in Science & Engineering. 2007.

+