Use Python to Download Coinbase Price Data

This is a short tutorial article that explains and gives example for how to use Python to download historical OHLC (Open, High, Low, Close) data with the Coinbase API. (*Please note that the Coinbase API is intended to be used for personal usage - refer to their market data terms). In the below Python script, we will use Pandas, requests, and json libraries to create a simple function that will ultimately write a CSV file with the filename "Coinbase_PAIR_dailydata.csv".. So if we want BTC/USD, the resulting filename will be: Coinbase_BTCUSD_dailydata.csv - Go ahead and give it a try!

                    # First import the libraries that we need to use
                    import pandas as pd
                    import requests
                    import json

                    def fetch_daily_data(symbol):
                        pair_split = symbol.split('/')  # symbol must be in format XXX/XXX ie. BTC/EUR
                        symbol = pair_split[0] + '-' + pair_split[1]
                        url = f'https://api.pro.coinbase.com/products/{symbol}/candles?granularity=86400'
                        response = requests.get(url)
                        if response.status_code == 200:  # check to make sure the response from server is good
                            data = pd.DataFrame(json.loads(response.text), columns=['unix', 'low', 'high', 'open', 'close', 'volume'])
                            data['date'] = pd.to_datetime(data['unix'], unit='s')  # convert to a readable date
                            data['vol_fiat'] = data['volume'] * data['close']      # multiply the BTC volume by closing price to approximate fiat volume

                            # if we failed to get any data, print an error...otherwise write the file
                            if data is None:
                                print("Did not return any data from Coinbase for this symbol")
                                data.to_csv(f'Coinbase_{pair_split[0] + pair_split[1]}_dailydata.csv', index=False)
                            print("Did not receieve OK response from Coinbase API")

                    if __name__ == "__main__":
                        # we set which pair we want to retrieve data for
                        pair = "BTC/USD"


This script is extremely simple, and can be greatly enhanced or fitted to meet your personal needs. It can easily be modified to save the data into a database, or pull different time frames or pairs... If you have a custom data need and would like help setting up the proper code, feel free to reach out to us

Follow Us
Drop us your email to receive new risk postings