paint-brush
Using Python to Download Historical Cryptocurrency Price Data from CoinGeckoby@jakemanger
3,728 reads
3,728 reads

Using Python to Download Historical Cryptocurrency Price Data from CoinGecko

by Jake MangerMarch 4th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Cryptocurrencies have skyrocketed in price since their inception. Bitcoin reached an all time high of $65,000 (November, 2021) coming from as little as $222 in January, 2015. To investigate these price trends, I thought it would be fun to see how I could download some historical price data using Python and plot it on my local computer.
featured image - Using Python to Download Historical Cryptocurrency Price Data from CoinGecko
Jake Manger HackerNoon profile picture

Build your blockchain idea with cryptocurrency price data.


A bitcoin price rollercoaster. GIF sourced from Tenor.



Cryptocurrencies have skyrocketed in price since their inception. Bitcoin, the world’s first cryptocurrency, reached an all-time high of $65,000 (November 2021), coming from as little as $222 in January 2015, or 0.02% of the price of a pizza in 2010.


Seriously, 0.02% of the price of a pizza. Lazlo Hanyecz bought two pizzas in 2010 for 10,000 BTC, which at near peak prices, is two pizzas for $650 million USD. Other, more recent cryptocurrencies such as Ethereum, Solana, and Dogecoin have had similarly ludicrous increases in value.


If you’re like me, you may have thought about how you can use cryptocurrency data to build a new blockchain-related project. Let’s say a product that tracks cryptocurrency prices. As a first step on this journey, I thought it would be fun to see how I could download some historical price data using Python and plot it on my local computer.


If you’re not aware, Python is a programming language commonly used to build websites and do data analysis and machine learning. It’s used by some huge companies. For example, Instagram started with and still uses python and the Django framework to run the backend of their app. If you are new to programming, don’t worry. You should be able to follow along with these step-by-step instructions. If you struggle or have any questions, please post them in the comments below.


Finding an API

For this task, we’ll need an API (an application programming interface). This allows two programs to talk to each other, such as your python program and the program of a data provider, like a cryptocurrency exchange.


Looking online, Binance is by far the most used cryptocurrency exchange, with a 24h trading volume of $17 Billion USD and 1388 trading pairs, according to CoinGecko.


Screenshot of crypto exchange trading volume listed by https://www.coingecko.com/.



However, Binance requires a long identity verification process before you can access its data.


Binance’s long verification process. Screenshot by Author.



Therefore, it’s probably best we go with a simpler data provider like CoinGecko for this process.


But first, let’s get our Python project set up.


Setting up the Python Project

Before we start downloading data from CoinGecko, we’ll need to set up our Python environment. I’ve covered this in more detail here. But briefly, to do this, we’ll need to:


  1. Have Python 3 installed. If you don’t already, visit https://www.python.org/ for installation instructions.

  2. Open your terminal or command line and create a new project folder

    mkdir crypto_data

  3. Change the directory to that new project folder

    cd crypto_data

  4. Create a new Python virtual environment

    python3 -m venv venv


Note, python3 is your installation of Python. If the version of Python you installed is called python, python3.7or python3.9, or anything else, then use that.


Setting up your Python project. GIF by Author.



  1. Activate your Python virtual environment.


(on Mac or Linux)


source venv/bin/activate


(on Windows)


venv\Scripts\activate


If you got stuck anywhere here, check out my past article that should make you a pro at setting up Python with virtual environments here.



Activating your virtual environment. GIF by Author.



We should now be ready to install our required dependencies.


Installing Dependencies

To download and use the Coingecko API, we’ll need to install the pycoingecko package. And to visualize our data, we’ll download the matplotlib package. We can do this by running the following command in our terminal or command prompt:


pip install pycoingecko matplotlib


Getting and Plotting Data

Now that we have our environment set up, it’s time to start collecting data. First, we’ll import the packages we installed into our Python script. Then, we’ll use the CoinGecko API to retrieve historical cryptocurrency price data. Finally, we’ll use matplotlib to visualize the data.


Here’s a sample code to retrieve Bitcoin price data from CoinGecko and plot it. Create a file called plot_btc.py and add this code to it using your favorite text editor (e.g., visual studio code, vim, or notepad… if you’re desperate).


import pycoingecko
import matplotlib.pyplot as plt
import datetime

# Initialize CoinGecko API client
coinGecko = pycoingecko.CoinGeckoAPI()
# Get historical price data for Bitcoin
btc_data = coinGecko.get_coin_market_chart_by_id('bitcoin', 'usd', '365days')
# Extract the dates and prices from the data
dates = [data[0] for data in btc_data['prices']]
# convert unix timestamp to datetime
dates = [
    datetime.datetime.fromtimestamp(date/1000)
    for date in dates
]
prices = [data[1] for data in btc_data['prices']]
# Plot the data
plt.plot(dates, prices)
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.title('Historical Bitcoin Price (USD)')
plt.show()


This code will retrieve a year’s worth of daily data for Bitcoin in USD and plot the price over time. With this data, we can try to explore the patterns and trends that drive the price of cryptocurrencies.



Creating the plot_btc.py file. GIF by Author.



Now, let’s run this code with the following command:

python plot_btc.py

and we should see the following beautiful plot!



Our Python script is complete and plotting! GIF by Author.



Congratulations! You just became an amateur cryptocurrency data analyst and developer! You can now use this data for whatever purpose you imagined.


If you’re interested in more than just cryptocurrency prices, consider checking out Chainspy, a website my friend and I are building. We aim to make blockchain data transparent and accessible through simple, user-friendly charts and APIs. Our site offers information on transaction speeds, usage, and applications of various cryptocurrencies, providing you with a comprehensive view of what’s happening on blockchains.


We’re also tracking the progress of our site’s development at Indiehackers. Consider giving it a look if you’re interested.


I hope this article was a bit of fun and educational. Thanks for reading!


Also published here.