<jupyter_start><jupyter_text><jupyter_code>#Describtion: This program uses the dual moving average crossover to determine when to buy and sell stock.
#Import the libraries
import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#Load the data
from google.colab import files
uploaded= files.upload()
#Store the data
TSLA = pd.read_excel('TSLA2020.xlsx')
#Show the data
TSLA
#Visualize the data
plt.figure(figsize=(25.5, 4.5))
plt.plot(TSLA['Adj Close'], label = 'TSLA')
plt.xlabel('Febr. 01, 2020 - Febr. 01, 2021')
plt.ylabel( 'Adj Close USD ($)')
plt.legend(loc='upper left')
plt.show()
#Create the simple moving average with a 10 day window
SMA10 = pd.DataFrame()
SMA10['Adj Close'] = TSLA['Adj Close'].rolling(window= 10).mean()
SMA10
#Create the simple moving average with a 30 day window
SMA30 = pd.DataFrame()
SMA30['Adj Close'] = TSLA['Adj Close'].rolling(window= 30).mean()
SMA30
#Visualize the data
plt.figure(figsize=(12.5, 4.5))
plt.plot(TSLA['Adj Close'], label = 'TSLA')
plt.plot(SMA10['Adj Close'], label = 'SMA10')
plt.plot(SMA30['Adj Close'], label = 'SMA30')
plt.xlabel('Febr. 01, 2020 - Febr. 01, 2021')
plt.ylabel('Adj Close USD ($)')
plt.legend(loc='upper left')
plt.show()
#Create a new data frame to store all the data
data = pd.DataFrame()
data['TSLA'] = TSLA['Adj Close']
data['SMA10'] = SMA10['Adj Close']
data['SMA30'] = SMA30['Adj Close']
data
#Create a function to signal when to buy and sell the asset/stock
def buy_sell(data):
  sigPriceBuy = []
  sigPriceSell = []
  flag = -1

  for i in range(len(data)):
    if data['SMA10'][i] > data['SMA30'][i]:
      if flag != 1:
        sigPriceBuy.append(data['TSLA'][i])
        sigPriceSell.append(np.nan)
        flag = 1
      else:
        sigPriceBuy.append(np.nan)
        sigPriceSell.append(np.nan)
        flag = 0
    elif data['SMA10'][i] < data['SMA30'][i]:
      if flag != 0:
            sigPriceBuy.append(np.nan)
            sigPriceSell.append(data['TSLA'][i])
      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]
#Show the data
data
#Visualize the data and strategy to buy and sell the stock
plt.figure(figsize=(18.6, 4.6))
plt.plot(data['TSLA'], label = 'TSLA', alpha = 0.35)
plt.plot(data['SMA10'], label = 'SMA10', alpha = 0.35)
plt.plot(data['SMA30'], label = 'SMA30', 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.title('TSLA Adj. Close History Buy & Sell Signals')
plt.xlabel('Febr. 01, 2020 - Febr. 01, 2021')
plt.ylabel('Adj Close USD ($)')
plt.legend(loc='upper left')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1577922077922078, 'fraction_numerical': 0.039935064935064934, 'mean_word_length': 4.075782537067545, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, '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': '235248', 'license': 'MIT', 'n_tokens_mistral': 1274, 'n_tokens_neox': 1136, 'n_words': 299, 'path': 'Trading_Algoritms.ipynb', 'repo_name': 'SuperGeekBrain/coal-exploration', 'size': '3080'}