Stock Market Trading:
Write a python program which:
1. Load the daily stock prices for Apple Corporation (stock ticker AAPL) data from yahoo finance, from Jan 2nd, 2020 through Dec 31st, 2020. note: you will not include Jan 1st, 2020 since it’s a holiday (New Year's day)
2. Run a mean reversion trading strategy on the data.
3. Output the results of the strategy including the profits
# open input file file = open("./AAPL.txt") # stores prices for last 5 days last_five_days =  # keeps track of first buy price first_buy = None # current buy price and total profit buy = None total_profit = 0 average = 0 # read file line by line for line in file.readlines(): # read price and convert to float price = float(line) price = round(price, 2) # to round the price to 2 decimals print(price) # if price is less than 95% of 5 day average and we have not already bought the share if price < average * 0.95 and buy is None: print("buy at: " + str(price)) buy = price # buy it if first_buy is None: # if its first buy set it first_buy = price elif price > average * 1.05 and buy is not None: # if price is greater than 105% of 5 day average, sell the share print("sell at: " + str(price)) # calculate profit profit = round(price - buy, 2) print("trade profit: " + str(profit)) # add to total profit and set buy to None total_profit += profit buy = None # if we have data for last 5 days, remove the oldest data and add new price to end of list if len(last_five_days) == 5: last_five_days.pop(0) last_five_days.append(price) else: # add data to end of list till we have data for 5 days last_five_days.append(price) # calculate average of last 5 days in loop average = round(sum(last_five_days)/5, 2) # print out the total profit and percentage return print("---------------------------------------") print("Total profit:", round(total_profit, 2)) print("First buy:", first_buy) final_profit_percentage = round(( total_profit / first_buy ) * 100, 2) print("Percentage return:", final_profit_percentage, "%")