# Algorithmic Stock Trading Strategy Using Python
# compare the simple moving average wi th a 30/100 day to determine the buy/sell price
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
AAPL = web.DataReader('AAPL', data_source='yahoo', start='2012-01-01', end='2021-04-25')
AAPL
High | Low | Open | Close | Volume | Adj Close | |
---|---|---|---|---|---|---|
Date | ||||||
2012-01-03 | 14.732143 | 14.607143 | 14.621429 | 14.686786 | 302220800.0 | 12.650659 |
2012-01-04 | 14.810000 | 14.617143 | 14.642857 | 14.765714 | 260022000.0 | 12.718646 |
2012-01-05 | 14.948214 | 14.738214 | 14.819643 | 14.929643 | 271269600.0 | 12.859850 |
2012-01-06 | 15.098214 | 14.972143 | 14.991786 | 15.085714 | 318292800.0 | 12.994284 |
2012-01-09 | 15.276786 | 15.048214 | 15.196429 | 15.061786 | 394024400.0 | 12.973674 |
… | … | … | … | … | … | … |
2021-04-19 | 135.470001 | 133.339996 | 133.509995 | 134.839996 | 94264200.0 | 134.839996 |
2021-04-20 | 135.529999 | 131.809998 | 135.020004 | 133.110001 | 94812300.0 | 133.110001 |
2021-04-21 | 133.750000 | 131.300003 | 132.360001 | 133.500000 | 68847100.0 | 133.500000 |
2021-04-22 | 134.149994 | 131.410004 | 133.039993 | 131.940002 | 84566500.0 | 131.940002 |
2021-04-23 | 135.119995 | 132.160004 | 132.160004 | 134.320007 | 78657500.0 | 134.320007 |
2342 rows × 6 columns
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(AAPL['Adj Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD$', fontsize=18)
plt.show()
# create the simple moving average with a 30 day window
SMA30 = pd.DataFrame()
SMA30['Adj Close'] = AAPL['Adj Close'].rolling(window=30).mean()
SMA30
Adj Close | |
---|---|
Date | |
2012-01-03 | NaN |
2012-01-04 | NaN |
2012-01-05 | NaN |
2012-01-06 | NaN |
2012-01-09 | NaN |
… | … |
2021-04-19 | 125.136333 |
2021-04-20 | 125.694666 |
2021-04-21 | 126.108333 |
2021-04-22 | 126.507000 |
2021-04-23 | 126.919000 |
2342 rows × 1 columns
# create the simple moving average with a 100 day window
SMA100 = pd.DataFrame()
SMA100['Adj Close'] = AAPL['Adj Close'].rolling(window=100).mean()
SMA100
Adj Close | |
---|---|
Date | |
2012-01-03 | NaN |
2012-01-04 | NaN |
2012-01-05 | NaN |
2012-01-06 | NaN |
2012-01-09 | NaN |
… | … |
2021-04-19 | 127.688672 |
2021-04-20 | 127.882971 |
2021-04-21 | 128.067989 |
2021-04-22 | 128.228820 |
2021-04-23 | 128.407860 |
2342 rows × 1 columns
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(AAPL['Adj Close'], label = 'AAPL')
plt.plot(SMA30['Adj Close'], label = 'SMA30')
plt.plot(SMA100['Adj Close'], label = 'SMA100')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD$', fontsize=18)
plt.legend(loc='upper left')
plt.show()
# create a new data frame to store all the data
data = pd.DataFrame()
data['AAPL'] = AAPL['Adj Close']
data['SMA30'] = SMA30['Adj Close']
data['SMA100'] = SMA100['Adj Close']
data
AAPL | SMA30 | SMA100 | |
---|---|---|---|
Date | |||
2012-01-03 | 12.650659 | NaN | NaN |
2012-01-04 | 12.718646 | NaN | NaN |
2012-01-05 | 12.859850 | NaN | NaN |
2012-01-06 | 12.994284 | NaN | NaN |
2012-01-09 | 12.973674 | NaN | NaN |
… | … | … | … |
2021-04-19 | 134.839996 | 125.136333 | 127.688672 |
2021-04-20 | 133.110001 | 125.694666 | 127.882971 |
2021-04-21 | 133.500000 | 126.108333 | 128.067989 |
2021-04-22 | 131.940002 | 126.507000 | 128.228820 |
2021-04-23 | 134.320007 | 126.919000 | 128.407860 |
2342 rows × 3 columns
#create a function to signal when to buy and sell
def buy_sell(data):
sigPriceBuy = []
sigPriceSell = []
flag = -1
for i in range(len(data)):
if data['SMA30'][i] > data['SMA100'][i]:
if flag != 1:
sigPriceBuy.append(data['AAPL'][i])
sigPriceSell.append(np.nan)
flag = 1
else:
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
elif data['SMA30'][i] < data['SMA100'][i]:
if flag != 0:
sigPriceBuy.append(np.nan)
sigPriceSell.append(data['AAPL'][i])
flag = 0
else:
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
else:
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
return(sigPriceBuy, sigPriceSell)
#store the buy and sell data into a variable
buy_sell = buy_sell(data)
data['Buy_Signal_Price'] = buy_sell[0]
data['Sell_Signal_Price'] = buy_sell[1]
data
AAPL | SMA30 | SMA100 | Buy_Signal_Price | Sell_Signal_Price | |
---|---|---|---|---|---|
Date | |||||
2012-01-03 | 12.650659 | NaN | NaN | NaN | NaN |
2012-01-04 | 12.718646 | NaN | NaN | NaN | NaN |
2012-01-05 | 12.859850 | NaN | NaN | NaN | NaN |
2012-01-06 | 12.994284 | NaN | NaN | NaN | NaN |
2012-01-09 | 12.973674 | NaN | NaN | NaN | NaN |
… | … | … | … | … | … |
2021-04-19 | 134.839996 | 125.136333 | 127.688672 | NaN | NaN |
2021-04-20 | 133.110001 | 125.694666 | 127.882971 | NaN | NaN |
2021-04-21 | 133.500000 | 126.108333 | 128.067989 | NaN | NaN |
2021-04-22 | 131.940002 | 126.507000 | 128.228820 | NaN | NaN |
2021-04-23 | 134.320007 | 126.919000 | 128.407860 | NaN | NaN |
2342 rows × 5 columns
#visualize the data and the strategy to buy and sell
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(data['AAPL'], label = 'AAPL', alpha = 0.35)
plt.plot(data['SMA30'], label = 'SMA30', alpha = 0.35)
plt.plot(data['SMA100'], label = 'SMA100', alpha = 0.35)
plt.scatter(data.index, data['Buy_Signal_Price'], label = 'Buy', marker = '^', color = 'green')
plt.scatter(data.index, data['Sell_Signal_Price'], label = 'Sell', marker = 'v', color = 'red')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD$', fontsize=18)
plt.legend(loc='upper left')
plt.show()