Skip to content

Instantly share code, notes, and snippets.

@yoshyoshi
Last active September 1, 2021 14:42
Show Gist options
  • Save yoshyoshi/5a35a23ac263747eabc70906fd037ff3 to your computer and use it in GitHub Desktop.
Save yoshyoshi/5a35a23ac263747eabc70906fd037ff3 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
@msmand
Copy link

msmand commented Jun 15, 2020

The code doesn't seem to be working for me either. The bar.time function doesn't seem to be valid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment