Tick Data for Backtesting and Algo Trading: Difference between revisions

From Volatility.RED
No edit summary
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
I noticed that many guides or lists of tick data sources were out of date, broken, or otherwise not working, so I decided to make an updated list with modern sources for use as a resource with the algo trading community. I will also keep this up to date as new sources appear and old sources break.
I noticed that many guides or lists of tick data sources were out of date, broken, or otherwise not working, so I decided to make an updated list with modern sources for use as a resource with the [[Algorithmic_Trading | algo trading]] community. I will also keep this up to date as new sources appear and old sources break.


Below are the guides for downloading tick or bar level data for various markets which can be used for backtesting and analysis.
Below are the guides for downloading tick or bar level data for various markets which can be used for backtesting and analysis.
Line 7: Line 7:
____TOC____
____TOC____


==Stock Daily Bar Data==
=='''Stock Daily Bar Data'''==


===Yahoo Finance===  
===Yahoo Finance===  


US and International stock exchanges - On a stock by stock basis, you can download decades of historical daily bar data by doing the following steps:
US and International stock exchanges - On a stock-by-stock basis, you can download decades of historical daily bar data by doing the following steps:


*Go to https://finance.yahoo.com
*Go to https://finance.yahoo.com
Line 26: Line 26:
===[https://pypi.org/project/yfinance/ yfinance Python Library]===
===[https://pypi.org/project/yfinance/ yfinance Python Library]===


  yfinance aimes to solve this problem by offering a reliable, threaded, and Pythonic way to download historical market data from Yahoo! finance.
  yfinance aims to solve this problem by offering a reliable, threaded, and Pythonic way to download historical market data from Yahoo! finance.


Jack from [https://fxgears.com/ FXGears.com] has provided a basic daily bar download script for yfinance in Python, but check out the yfinance docs for more advanced features:
Jack from [https://fxgears.com/ FXGears.com] has provided a basic daily bar download script for yfinance in Python, but check out the yfinance docs for more advanced features:
Line 56: Line 56:
Note: You will have to know the Yahoo! Finance symbology to download your target symbols. (It's sometimes not intuitive, "CAD=X" is USD/CAD for example.)
Note: You will have to know the Yahoo! Finance symbology to download your target symbols. (It's sometimes not intuitive, "CAD=X" is USD/CAD for example.)


==Forex [Tick Data]==
=='''Forex [Tick Data]'''==


Quality of data matters, and the below options are some of the better quality sources available for free.
Quality of data matters and the below options are some of the better quality sources available for free.


===[https://geni.us/Darwinex Darwinex]===
===[https://geni.us/Darwinex Darwinex]===
::Darwinex is easy but you'll need to have a live account. Anyone can [https://geni.us/Darwinex signup for an account (live)] and head over to this page here once logged in: [https://geni.us/DarwinexTickData Historical Tick Data Download]. From there, just click the '''"Request FTP Access"''' button to have your FTP login details generated for you. Darwinex provides tick level data all major and minor currency pairs, as well as index and commodity CFDs, with most of them going back to mid-late 2017. You don't need to deposit to have a live account at Darwinex, you just need to have a verified account with them, so there's little downside to enabling access to this high quality source of tick data. (As a side benefit, you can also get access to historical price data of their Darwin Exchange, so you can model investing in other traders and model their strategy returns, which is pretty cool.)
::Darwinex is easy but you'll need to have a live account. Anyone can [https://geni.us/Darwinex signup for an account (live)] and head over to this page here once logged in: [https://geni.us/DarwinexTickData Historical Tick Data Download]. From there, just click the '''"Request FTP Access"''' button to have your FTP login details generated for you. Darwinex provides tick level data for all major and minor [[currency]] pairs, as well as index and commodity CFDs, with most of them going back to mid-late 2017. You don't need to deposit to have a live account at Darwinex, you just need to have a verified account with them, so there's little downside to enabling access to this high-quality source of tick data. (As a side benefit, you can also get access to historical price data of their Darwin Exchange, so you can model investing in other [[Trader_Types | traders]] and model their [[Technical_Trading_Strategies | strategy]] returns, which is pretty cool.)


===[https://geni.us/Pepperstone Pepperstone] / Integral / [https://www.truefx.com/truefx-historical-downloads/ TrueFX]===
===[https://geni.us/Pepperstone Pepperstone] / Integral / [https://www.truefx.com/truefx-historical-downloads/ TrueFX]===
Line 67: Line 67:
https://www.truefx.com/truefx-historical-downloads/
https://www.truefx.com/truefx-historical-downloads/


::Pepperstone relies on price feeds and liquidity very similar to Integral's offering, so similar that for a while Pepperstone used to publish Integral's data on their own FTP for easy customer access. Unfortunately, they stopped offering this FTP access some time ago (thus why most online tutorials referencing them are out of date) and the source of data that Pepperstone currently recommends is Integral's TrueFX data service offering. [https://www.truefx.com/truefx-historical-downloads/ A free account at TrueFX.com'] will get you access to tick data on most major and minor currency pairs from the past year only (Currently only 2019 YTD is available for free.) I encouraged Pepperstone to bring back their historical data access to regain access to years prior to 2019 and if they ever open back up then I'll update this spot here with access info.​
::Pepperstone relies on price feeds and liquidity very similar to Integral's offering, so similar that for a while Pepperstone used to publish Integral's data on their own FTP for easy customer access. Unfortunately, they stopped offering this FTP access some time ago (thus why most online tutorials referencing them are out of date) and the source of data that Pepperstone currently recommends is Integral's TrueFX data service offering. [https://www.truefx.com/truefx-historical-downloads/ A free account at TrueFX.com'] will get you access to tick data on most major and minor [[currency]] pairs from the past year only (Currently only 2019 YTD is available for free.) I encouraged Pepperstone to bring back their historical data access to regain access to years prior to 2019 and if they ever open back up then I'll update this spot here with access info.​


==Crypto Minute Bar Data==
=='''Crypto Minute Bar Data'''==




===[https://geni.us/TickDataBinance Binance]===
===[https://geni.us/TickDataBinance Binance]===


One of the top exchanges by volume with easily one of the largest collections of crypto pairs to trade. Binance is very API friendly, and is structured in a way that even trading smaller amounts can be done efficiently. Recently, Binance opened up trading on leveraged products (spot, and futures,) as well as started offering options.
One of the top exchanges by volume with easily one of the largest collections of crypto pairs to [[Trading | trade]]. Binance is very API friendly and is structured in a way that even trading smaller amounts can be done efficiently. Recently, Binance opened up trading on leveraged products (spot, and futures,) as well as started offering options.




Line 84: Line 84:




On the following page, find the create field and enter any nick name you want:<br>
On the following page, find the Create field and enter any nickname you want:<br>
https://i.imgur.com/RPmtR41.png
https://i.imgur.com/RPmtR41.png


Line 90: Line 90:
Hit the create button. You'll likely have to authenticate or verify via email that you want to generate an API key, but once done you will see the generated API key itself, and the API secret code as well. Save these somewhere secure and safe.
Hit the create button. You'll likely have to authenticate or verify via email that you want to generate an API key, but once done you will see the generated API key itself, and the API secret code as well. Save these somewhere secure and safe.


Next up we need to setup Python on our system to do the leg work of downloading data. Head over to https://python.org and grab the latest version of Python 3 for your OS. Install said package.
Next up we need to set up Python on our system to do the leg work of downloading data. Head over to https://python.org and grab the latest version of Python 3 for your OS. Install said package.


Once installed we will add the python-binance and pandas packages to access the Binance API from within Python and to save the resulting data to a CSV file.
Once installed we will add the python-binance and pandas packages to access the Binance API from within Python and to save the resulting data to a CSV file.
Line 148: Line 148:




Done! Enjoy a few million lines of 1m data per symbol on any crypto currency pair that [https://geni.us/TickDataBinance binance] has listed! Enjoy!:
Done! Enjoy a few million lines of 1m data per symbol on any cryptocurrency pair that [https://geni.us/TickDataBinance binance] has listed! Enjoy!:


https://i.imgur.com/HWHxOyd.png
https://i.imgur.com/HWHxOyd.png
Line 154: Line 154:
===BitMEX (Crypto Futures)===
===BitMEX (Crypto Futures)===


BitMEX provides public access to their quote and trade (transaction) level data via a web/file server here:  
BitMEX provides public access to their quote and [[Trading | trade]] (transaction) level data via a web/file server here:  
https://public.bitmex.com/
https://public.bitmex.com/


However, this is for crypto Futures unique to their platform, not the underlying cryto currencies themselves or a fungible asset that's tradable on other exchanges. Be aware of this when designing any strategy that's "tick" or "price" sensitive.
However, this is for crypto Futures unique to their [[The_Best_and_Most_Popular_Forex_Platforms_for_Demo | platform]], not the underlying crypto currencies themselves or a fungible asset that's tradable on other exchanges. Be aware of this when designing any [[Technical_Trading_Strategies | strategy]] that's "tick" or "price" sensitive.
 
 
=='''Related Wikis'''==
 
Readers of '''Editing Tick Data for Backtesting and [[Algorithmic_Trading | Algo Trading]]''' also viewed:
 
* [[Algorithmic Trading]]
* [[Best_and_Worst_Times_to_Trade | Best and Worst Times to Trade]]
* [[Technical Trading Strategies]]
* [[Sentiment_Analysis#Volatility | Volatility]]
* [[Developing_your_Trading_Process | Developing your Trading Process]]

Latest revision as of 10:27, 6 October 2023

I noticed that many guides or lists of tick data sources were out of date, broken, or otherwise not working, so I decided to make an updated list with modern sources for use as a resource with the algo trading community. I will also keep this up to date as new sources appear and old sources break.

Below are the guides for downloading tick or bar level data for various markets which can be used for backtesting and analysis.

Note: Typical format for tick and bar data is in CVS files. You might need to adjust or re-arrange said files as needed to fit into your desired analytics and/or backtesting program.

__

__

Stock Daily Bar Data

Yahoo Finance

US and International stock exchanges - On a stock-by-stock basis, you can download decades of historical daily bar data by doing the following steps:

  • Go to https://finance.yahoo.com
  • In the search field, type in your desired symbol or company name and select the appropriate result
  • Click the 'Historical Data' tab
  • Set the date range to 'MAX'
  • Hit the 'Apply' button
  • Click the 'Download Data' link just below the 'Apply' button
  • Enjoy your daily bar data

Google Finance

Rest in peace.. :( Google nuked their finance site back to the stone age many years ago so this service is pretty useless now (Honestly Google, what were you thinking? Google Finance was awesome back in 2012 and prior.) Google also used to have an API but that too got turned off. I included an entry for Google here because many people will be searching around the net and find references to using Google Finance's API but be unsure why it's not working as expected.

yfinance Python Library

yfinance aims to solve this problem by offering a reliable, threaded, and Pythonic way to download historical market data from Yahoo! finance.

Jack from FXGears.com has provided a basic daily bar download script for yfinance in Python, but check out the yfinance docs for more advanced features:

Make sure you have yfinance installed. From your command line:

pip install yfinance
import yfinance as yf
import datetime
import os

# define start date, go back further if you need but not all years are available for all symbols.
start_date = '2020-01-01'

end_date = datetime.date.today() - datetime.timedelta(days=1)
end_date = end_date.strftime(format="%Y-%m-%d")

symbols = ['SPY', 'IBM', 'BAC']

for item in symbols:
    working_df = yf.download(item, start=start_date, end=end_date)
    working_df.reset_index(inplace=True)
    working_df.to_csv('{}_{}.csv'.format(item, end_date), index=False)

Note: You will have to know the Yahoo! Finance symbology to download your target symbols. (It's sometimes not intuitive, "CAD=X" is USD/CAD for example.)

Forex [Tick Data]

Quality of data matters and the below options are some of the better quality sources available for free.

Darwinex

Darwinex is easy but you'll need to have a live account. Anyone can signup for an account (live) and head over to this page here once logged in: Historical Tick Data Download. From there, just click the "Request FTP Access" button to have your FTP login details generated for you. Darwinex provides tick level data for all major and minor currency pairs, as well as index and commodity CFDs, with most of them going back to mid-late 2017. You don't need to deposit to have a live account at Darwinex, you just need to have a verified account with them, so there's little downside to enabling access to this high-quality source of tick data. (As a side benefit, you can also get access to historical price data of their Darwin Exchange, so you can model investing in other traders and model their strategy returns, which is pretty cool.)

Pepperstone / Integral / TrueFX

https://www.truefx.com/truefx-historical-downloads/

Pepperstone relies on price feeds and liquidity very similar to Integral's offering, so similar that for a while Pepperstone used to publish Integral's data on their own FTP for easy customer access. Unfortunately, they stopped offering this FTP access some time ago (thus why most online tutorials referencing them are out of date) and the source of data that Pepperstone currently recommends is Integral's TrueFX data service offering. A free account at TrueFX.com' will get you access to tick data on most major and minor currency pairs from the past year only (Currently only 2019 YTD is available for free.) I encouraged Pepperstone to bring back their historical data access to regain access to years prior to 2019 and if they ever open back up then I'll update this spot here with access info.​

Crypto Minute Bar Data

Binance

One of the top exchanges by volume with easily one of the largest collections of crypto pairs to trade. Binance is very API friendly and is structured in a way that even trading smaller amounts can be done efficiently. Recently, Binance opened up trading on leveraged products (spot, and futures,) as well as started offering options.


You're going to need an account, which is free to get started, so if you don't already have an account you can register here.


From your account page, then you'll need to generate API keys to access the API and pull down data:
PKtpYr9.png


On the following page, find the Create field and enter any nickname you want:
RPmtR41.png


Hit the create button. You'll likely have to authenticate or verify via email that you want to generate an API key, but once done you will see the generated API key itself, and the API secret code as well. Save these somewhere secure and safe.

Next up we need to set up Python on our system to do the leg work of downloading data. Head over to https://python.org and grab the latest version of Python 3 for your OS. Install said package.

Once installed we will add the python-binance and pandas packages to access the Binance API from within Python and to save the resulting data to a CSV file.

To do this, open a Open a CMD (Command Line) window as Administrator on Windows (or the appropriate terminal in Linux / OSX..) and run the following commands:

Install python-binance python library and pandas from your command line:

pip install python-binance
pip install pandas


Once that's done, copy the code below to a new python file and save it somewhere handy:

import pandas as pd
from binance.client import Client
import datetime

# YOUR API KEYS HERE
api_key = ""    #Enter your own API-key here
api_secret = "" #Enter your own API-secret here

bclient = Client(api_key=api_key, api_secret=api_secret)

start_date = datetime.datetime.strptime('1 Jan 2016', '%d %b %Y')
today = datetime.datetime.today()

def binanceBarExtractor(symbol):
    print('working...')
    filename = '{}_MinuteBars.csv'.format(symbol)

    klines = bclient.get_historical_klines(symbol, Client.KLINE_INTERVAL_1MINUTE, start_date.strftime("%d %b %Y %H:%M:%S"), today.strftime("%d %b %Y %H:%M:%S"), 1000)
    data = pd.DataFrame(klines, columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_av', 'trades', 'tb_base_av', 'tb_quote_av', 'ignore' ])
    data['timestamp'] = pd.to_datetime(data['timestamp'], unit='ms')

    data.set_index('timestamp', inplace=True)
    data.to_csv(filename)
    print('finished!')


if __name__ == '__main__':
    # Obviously replace BTCUSDT with whichever symbol you want from binance
    # Wherever you've saved this code is the same directory you will find the resulting CSV file
    binanceBarExtractor('BTCUSDT')


Where you see the api_key, and api_secret variables near the beginning of the file, you will add the generated API key and API secret from your binance account BETWEEN the quotes.


Finally, at the bottom on the last line, change the 'BTCUSDT' to whichever crypto pair you desire to extract from Binance... browse around Binance's exchange to see all your options.


Run the code... the script will write a CSV file to the same directory you saved the code in, and these files will be ~100-200mb in size depending on how far back their history goes. As for timing, for BTCUSDT it takes my connection about 10-12 minutes to grab minute bar data going all the way back to ~2017.. so don't hold your breath. This is because Binance rate limits their historical data requests.


Done! Enjoy a few million lines of 1m data per symbol on any cryptocurrency pair that binance has listed! Enjoy!:

HWHxOyd.png

BitMEX (Crypto Futures)

BitMEX provides public access to their quote and trade (transaction) level data via a web/file server here: https://public.bitmex.com/

However, this is for crypto Futures unique to their platform, not the underlying crypto currencies themselves or a fungible asset that's tradable on other exchanges. Be aware of this when designing any strategy that's "tick" or "price" sensitive.


Related Wikis

Readers of Editing Tick Data for Backtesting and Algo Trading also viewed: