Python for Algorithmic Trading: Fetching Historical Price Data
Introduction
Today, I’m going to guide you through downloading price data for stocks or cryptocurrencies to a CSV file. This is especially useful if you want to conduct financial analysis in Excel or any other data visualization software.
Before we dive in, a quick note: we’ll be using the VectorBT Python module. If you’re an aspiring quant, financial analyst, or just someone keen on learning algorithmic trading, then VectorBT is a must-have in your toolkit. So if you haven’t yet familiarized yourself with the VBT Library, now is the perfect time!
Let’s get started.
1. Download Data
import vectorbtpro as vbt
exchange='NASDAQ'
symbol = "AAPL"
timeframe="1d" # examples: 1d, 4 hour, 1h/hourly, 15m, 1m
timezone= "US/Eastern"
data = vbt.TVData.fetch(
f'{exchange}:{symbol}',
timeframe=timeframe,
tz=timezone
)
In this step, we’ll download daily historical data from trading view which is a popular platform for traders. We start by defining the exchange and symbol for the asset which we’re interested in. For our example, I will be using ‘AAPL’ Stock which is listed on the ‘NASDAQ’ exchange. If you want to do crypto trading, you could swap these out for ‘BTCUSDT’ on the ‘Binance’ exchange just as easily.
2. Save Data to CSV
#save to csv
save_path = f"C://your path//{symbol}_{timeframe}.csv"
csv_saver = vbt.CSVDataSaver(data, save_kwargs=dict(path_or_buf=save_path))
init_save = True
csv_saver.save()
After downloading the data from the Trading View API, we can save it to a local CSV using the above CSVDataSaver class.
3. Continuous Data Update
csv_saver.update_every(1, "minute", init_save=init_save)
For a live algorithm, it’s essential to continuously update the CSV. This can be achieved with the update_every function in VectorBT. This can run as it’s own separate script apart from the live trading algorithm.
4. Pull Data
csv_saver = vbt.CSVDataSaver.load()
csv_saver.update()
To incorporate data into your live trading algorithm, use the load()
function from the CSVDataSaver class to import the CSV.
5. Putting it all together
import vectorbtpro as vbt
import os
import logging
logging.basicConfig(level=logging.INFO)
symbol = "MATICUSDT"
timeframe="1 day"
path = f"D://symbol data//{symbol}_{timeframe}.csv"
#check if running from main script
if __name__ == "__main__":
#Check if a csv file of the data already exists
if os.path.isfile(path):
#load csv file using CSVDataSaver
csv_saver = vbt.CSVDataSaver.load()
csv_saver.update()
init_save = False
else:
print('No data found, initiating data fetch')
data = vbt.BinanceData.fetch(
symbol,
timeframe=timeframe
)
csv_saver = vbt.CSVDataSaver(data, save_kwargs=dict(path_or_buf=path))
init_save = True
csv_saver.update_every(1, "minute", init_save=init_save)
csv_saver.save()
Above is an example of how to put it all together. The script checks if a csv already exists. If it does, it import’s the csv and then updates it. If it does not, then it makes an api call for all historical data then creates a new csv file.
Summary
In this article, we’ve walked through the process of fetching historical price data using the VectorBT Python module and saving it to a CSV file for further analysis. By utilizing VectorBT’s robust functionalities, not only can we effortlessly download and save data, but we can also continuously update it for live trading algorithms. With this foundation in place, you’re well on your way to developing more complex trading strategies and algorithms. Stay tuned for the next part of this series where we’ll dive deeper into crafting trading algorithms using this data.
Remember, the world of algorithmic trading is vast and ever-evolving. With the right tools in hand and a clear understanding of the processes, you can navigate this landscape with confidence. Happy trading!