import alpaca_trade_api as tradeapi api = tradeapi.REST(key_id=,secret_key=) storageLocation = "" 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