Simple trading simulation
Question
Suppose you want to create a simple trading algorithm which purchases 1 share of SPY (an ETF which tracks the S&P 500) when the opening price is below $285.00 and sells the share when the opening price is above $290.00. At any given time you can only own 1 share of SPY.
Create a Python script that simulates the rules above for Jan 2, 2020 through May 1, 2020. You will need to keep track of your positions (e.g. buying and selling) in a dataframe and below are the requirements for the dataframe columns:
- buy_date: date the asset was purchased
- buy_price: price the asset was purchased for
- sell_date: the date the asset is sold
- sell_price: price the asset was sold
To help get you started, the code below installs yfinance to your Colab runtime and loads in the historial stock data. You can also make a copy of this Google Colab notebook to get started!
#import yahoo finance
pip install yfinance
#import packages
import logging
import sys
import pandas as pd
import datetime
from time import sleep, strftime, time
import math
import yfinance as yf
#get data from yahoo finance
data = yf.download("SPY", start="2020-01-02", end="2020-05-01").reset_index(drop=True)