Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save darocha/42a6fcd229bd78fcc2dafb89d0e2c65a to your computer and use it in GitHub Desktop.
Save darocha/42a6fcd229bd78fcc2dafb89d0e2c65a to your computer and use it in GitHub Desktop.
download and store OHLCV data into a CSV
import alpaca_trade_api as tradeapi
api = tradeapi.REST(key_id=<your key id>,secret_key=<your secret key>)
storageLocation = "<your folder location>"
barTimeframe = "1H" # 1Min, 5Min, 15Min, 1H, 1D
assetsToDownload = ["SPY","MSFT","AAPL","NFLX"]
iteratorPos = 0 # Tracks position in list of symbols to download
assetListLen = len(assetsToDownload)
while iteratorPos < assetListLen:
symbol = assetsToDownload[iteratorPos]
dataFile = ""
lastDate = "2013-00-00T00:00:00.000Z" # ISO8601 Date
# Verifies if symbol file exists
try: # If file exists, reads the time of the last bar
dataFile = open(storageLocation + '{0}.csv'.format(symbol), 'a+')
lastDate = list(csv.DictReader(dataFile))[-1]["time"]
except: # If not, initialises new CSV file
dataFile = open(storageLocation + '{0}.csv'.format(symbol), 'w')
dataFile.write("time,open,high,low,close,volume\n")
returned_data = api.get_bars(symbol,barTimeframe,start_dt=lastDate).bars
# Reads, formats and stores the new bars
for bar in returned_data:
ret_time = str(bar.time)
ret_open = str(bar.open)
ret_high = str(bar.high)
ret_low = str(bar.low)
ret_close = str(bar.close)
ret_volume = str(bar.volume)
# Writes formatted line to CSV file
dataFile.write(ret_time + "," + ret_open + "," + ret_high + "," + ret_low + "," + ret_close + "," + ret_volume)
dataFile.close()
iteratorPos += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment