This is not investment advice.
Moving averages (MAs) are basic, yet very powerful tool in technical analysis. Stock price typically finds support/resistance in vicinity of various significant moving averages.
Moving averages are especially useful when stock is in developed uptrend or downtrend.
We distinguish 2 types of MAs:
Simple moving average applies equal weight to all datapoints, on the other hand exponencial moving average gives more importance to recent price action.
In this article we will be computing both simple and exponencial moving averages for 50, 100, 150 and 200 point window.
Script is intended to be eventually part of a trading bot.
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('retina')
#optional installations:
#!pip install yfinance --upgrade --no-cache-dir
#!pip3 install yfinance --upgrade --no-cache-dir
#!pip install pandas_datareader
#!pip3 install pandas_datareader
import sys
import os
# ___library_import_statements___
import pandas as pd
# for pandas_datareader, otherwise it might have issues, sometimes there is some version mismatch
pd.core.common.is_list_like = pd.api.types.is_list_like
# make pandas to print dataframes nicely
pd.set_option('expand_frame_repr', False)
import pandas_datareader.data as web
import numpy as np
import matplotlib.pyplot as plt
import datetime
import time
#newest yahoo API
import yfinance as yahoo_finance
# ___variables___
# ------------------------------------------------------------------------------
#ticker = 'AAPL'
#ticker = 'SPY'
#ticker = 'QQQ'
ticker = 'TSLA'
start_time = datetime.datetime(2017, 10, 1)
#end_time = datetime.datetime(2019, 1, 20)
end_time = datetime.datetime.now().date().isoformat() # today
# __function_definitions__
# ------------------------------------------------------------------------------
def get_data(ticker):
# yahoo gives only daily historical data
attempts = 0
connected = False
while not connected:
try:
ticker_df = web.get_data_yahoo(ticker, start=start_time, end=end_time)
connected = True
print('connected to yahoo')
except Exception as e:
print("type error: " + str(e))
time.sleep( 5 )
attempts += 1
if attempts >= 10:
connected = True
pass
# use numerical integer index instead of date
ticker_df = ticker_df.reset_index()
#print(ticker_df.head(5))
return ticker_df
def computeSMA(data, window):
# simple moving average
sma = data.rolling(window=window).mean()
return sma
def computeEMA(data, span):
# simple moving average
ema = data.ewm(span=span, adjust=False).mean()
return ema
def construct_df(ticker):
#get data from yahoo API
df = get_data(ticker)
# compute both types of moving averages
for i in range(50, 250, 50):
#print(i)
df['SMA_{}'.format(i)] = computeSMA(df['Adj Close'], i)
for i in range(50, 250, 50):
#print(i)
df['EMA_{}'.format(i)] = computeEMA(df['Adj Close'], i)
return df
df = construct_df(ticker)
df.tail()
def plot_data_SMA(df):
plt.figure(figsize=(15,5))
plt.title('Price chart (Adj Close)')
plt.plot(df['Date'], df['Adj Close'])
for i in range(50, 250, 50):
plt.plot(df['Date'], df['SMA_{}'.format(i)])
plt.legend(loc='best')
plt.show()
def plot_data_EMA(df):
plt.figure(figsize=(15,5))
plt.title('Price chart (Adj Close)')
plt.plot(df['Date'], df['Adj Close'])
for i in range(50, 250, 50):
plt.plot(df['Date'], df['EMA_{}'.format(i)])
plt.legend(loc='best')
plt.show()
plot_data_SMA(df)
plot_data_EMA(df)
From the plots we can see that Tesla (TSLA) stock found support pretty much exactly on 50 and 200 simple moving average.