<jupyter_start><jupyter_text><jupyter_code># Three Moving Average Crossover Strategy to determine when to buy and sell stock 
#Import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
from pandas_datareader import data
# Getting Data from Yahoo Finance
company = 'TSLA';
datasource = 'yahoo'
start = '2010-01-01'
end = '2020-06-01'
df = data.DataReader(company , datasource , start,end)

# Show the data
df.head()
#Visualize the data(Close)
plt.figure(figsize = (15,5))
plt.title('close price')
plt.plot(df['Close'])
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.show()
#Calculate the three moving Averages
# Short Moving Average : Exponential Moving Average
ShortEMA = df.Close.ewm(span = 5 , adjust = False).mean()

# Medium Exponential Moving Average
MiddleEMA = df.Close.ewm(span =  21 , adjust = False).mean()    # Should be betwen 5 and 61 

# Long Moving Average :
LongEMA = df.Close.ewm(span = 63, adjust = False).mean()

# Plot Closing price and Expoenential Moving Average
plt.figure(figsize = (25,10))
plt.title('close price')
plt.plot(df['Close'], label = 'Close Price' , color = 'blue')
plt.plot(ShortEMA, label ='Short/Fast EMA' , color = 'red')
plt.plot(MiddleEMA, label = 'Middle/ Medium EMA' , color = 'orange')
plt.plot(LongEMA ,label = 'Long/Slow EMA' , color ='green')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.show()
# Add exponential Moving Averages to dataset
df['Short'] = ShortEMA
df['Middle'] = MiddleEMA
df['Long'] = LongEMA
# Look at the DF
df.head()
# Function to buy and sell stock
def buy_sell(data):

  sell_list = []
  buy_list = []
  flag_long = False
  flag_short = False
  
  for i in range(0 , len(data)):

    # Buying stock
    if data['Middle'][i] < data['Long'][i] and data['Short'][i] < data['Middle'][i] and flag_long == False and flag_short == False:
      buy_list.append(data['Close'][i])
      sell_list.append(np.nan)
      flag_short = True

    #Selling stock
    elif flag_short == True and data['Short'][i] > data['Middle'][i]:
      sell_list.append(data['Close'][i])
      buy_list.append(np.nan)
      flag_short = False

    # Buying stock
    elif data['Middle'][i] > data['Long'][i] and data['Short'][i] > data['Middle'][i] and flag_long == False and flag_short == False:
      buy_list.append(data['Close'][i])
      sell_list.append(np.nan)
      flag_long = True

    #Selling stock
    elif flag_long == True and data['Short'][i] < data['Middle'][i]:
      sell_list.append(data['Close'][i])
      buy_list.append(np.nan)
      flag_long = False
    
    # If nothing matches
    else:
      buy_list.append(np.nan)
      sell_list.append(np.nan)
    
  return (buy_list , sell_list)
    
# Add buy and sell to the dataset
df['Buy'] = buy_sell(df)[0]
df['Sell'] = buy_sell(df)[1]
df['Buy'].isnull().sum()
df.shape
# Visualize stock buy and sell signals
plt.figure(figsize = (25,10))
plt.title('Buy and Sell Plot')
plt.plot(df['Close'], label = 'Close Price' , color = 'blue' , alpha = 0.35)
plt.plot(ShortEMA, label ='Short/Fast EMA' , color = 'red' , alpha = 0.35)
plt.plot(MiddleEMA, label = 'Middle/ Medium EMA' , color = 'orange', alpha = 0.35)
plt.plot(LongEMA ,label = 'Long/Slow EMA' , color ='green', alpha = 0.35)
plt.scatter(df.index , df['Buy'], color = 'green' , marker = '^' , alpha = 1)   # Buy Signal
plt.scatter(df.index , df['Sell'], color = 'red' , marker = 'v' , alpha = 1)    # Sell Signal
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1600113282356273, 'fraction_numerical': 0.014726706315491363, 'mean_word_length': 4.126269956458636, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '476806', 'license': 'MIT', 'n_tokens_mistral': 1342, 'n_tokens_neox': 1230, 'n_words': 331, 'path': 'Alg_Trading_3MA.ipynb', 'repo_name': 'ashwinram472/100-Days-Of-ML-Code', 'size': '3531'}