• Thu. Jul 4th, 2024

How to Use Python to Query CoinGecko API

Python is one of the most ubiquitous, general-purpose programming languages today, and can be used to create a wide range of varying programs. In this guide, we’ll explore how to leverage Python to query CoinGecko API, and retrieve coin price data from the various endpoints:

  • Crypto price /simple/price
  • OHLC /coins/{id}/ohlc
  • Trending /search/trending
  • NFTs /nft/{id}

Let’s dive in!


Navigating CoinGecko API Documentation & Setting Up

CoinGecko API has a total of 50+ endpoints, of which 30+ are publicly accessible via our Demo API plan. This provides access to independently aggregated crypto data, such as historical and live prices, volume, exchange volumes, contract data, and NFT floor prices – all comprehensively outlined in their API documentation.

If any endpoint is of particular interest to you, simply click the down arrow next to it to reveal the potential parameters associated with that function.

The /simple/price endpoint effectively illustrates the functionality of the API. We can input various parameters concerning the coin of interest, the currency to compare it with, whether to include volume/market cap/etc. in our output, and the precision of each price value.

Once we hit ‘execute’, we get a cURL response as follows:

cURL is a command-line tool and library for making HTTP requests. This code language is used to make a GET request to the CoinGecko API, retrieving information about Ethereum (ETH)’s price vs USD. You can perform the same HTTP GET request using Python!

Open a Jupyter notebook, PyCharm, or another favored IDE, by simply typing in the name into the Mac command line ‘Terminal’, such as ‘Jupyter Notebook’. Prior to this, ensure you have Python downloaded, and pip, which is a Python package manager. This process can be mirrored on Windows.

Once you are on your Python script, we will need to import the requests library, which is a commonly used tool for making HTTP requests in Python. By using it, we can facilitate a similar process to that shown before.

import requests
url = ‘https://api.coingecko.com/api/v3/simple/price
params = {  
         ‘ids’: ‘ethereum’,
         ‘vs_currencies’: ‘USD’
}

response = requests.get(url, params = params)

 
In the code example below, 200 refers to a status code, indicating a successful HTTP request. Other status codes might be more familiar, such as code 404 (Not Found), 500 (Internal Server Error), 401 (Unauthorized), and so on. 

To retrieve simple price data, we’d then write:

if response.status_code == 200:
         data = response.json()
         Ethereum_price = data[‘ethereum’][‘usd’]
         print(f’The price of Ethereum in USD is ${Ethereum_price}’)
else:
         print(‘Failed to retrieve data from the API’)

💡 Pro-tip: Make sure you have the ‘requests’ library downloaded in your Python environment. You can install it using pip in your Terminal:

         pip install requests
 

How to Get Coin’s OHLC Data with an API

To pull Open, High, Low, Close (OHLC) data for a cryptocurrency, use the OHLC endpoint /coins/{id}/ohlc in CoinGecko API. The data pulled – the candle’s body – has an automatic data granularity for Demo plan users:

  • 1 – 2 days: 30 minutes
  • 3 – 30 days: 4 hours
  • 31 days and beyond: 4 days

Meanwhile, paid API users can enjoy the exclusive daily candle interval parameter, using the ‘interval=daily‘ parameter in your request. The ‘daily‘ interval is available for 1, 7, 14, 30, 90 and 180 days, updated on a 30 minute frequency.

We can utilize the pycoingecko library to pull from this endpoint as it initiates an API request distinct from the one made to the /simple/price endpoint and serves a unique purpose. 

The /coins/{id}/ohlc endpoint can utilize the cg.get_coin_ohlc_by_id method from the pycoingecko library. This method is specifically created to fetch OHLC price data for a given cryptocurrency, in this case Ethereum, over a specified number of days. As it is making a request to a different endpoint, we can use the pycoingecko library to facilitate this:

         from pycoingecko import CoinGeckoAPI
         cg = CoinGeckoAPI()
         ohlc = cg.get_coin_ohlc_by_id(id = “ethereum”, vs_currency = “usd”, days = “30”)
         print (ohlc)

Of course, the print method will, as designed, display JSON data returned by the API. 

In order to make it more palatable, we can utilize pandas DataFrames.


How to Turn Requests into Readable pandas DataFrame

To convert text data to a human-readable pandas DataFrame, first convert the response to a string and then extract key-value pairs as columns.

In the code below, the OHLC variable stores the JSON response data, which is essentially a list of OHLC data points. Each data point is represented as a dictionary. When you create a pandas DataFrame using pd.DataFrame(ohlc), pandas interprets each dictionary within the list as a row in the Dataframe, and extracts the key-value pairs as columns.

         import pandas as pd
         df = pd.DataFrame(ohlc)
 
As the output is still not properly legible, we will make a few further adjustments: labeling columns, converting the date to a pandas datetime object, and setting the date as the index.
         df.columns = [“date”, “open”, “high”, “low”, “close”]

💡Pro-tip: To reconfirm that these data points are accurate, we can return to the CoinGecko website and compare the information.

Let’s continue readjusting our DataFrame:

         df[“date”] = pd.to_datetime(df[“date”], unit = “ms”)
         df.set_index(‘date’, inplace = True)

The DataFrame is now complete, featuring OHLC data and accurate datetime stamps, which are all in accordance with the 4-hour automatic granularity for 30 day price history:


How to Fetch Cryptocurrency Price Data 

We can obtain all coins market data by using the /coins/markets CoinGecko API endpoint. The parameters allow us to specify:

  • The currency to compare it to (vs_currency – typically ‘usd’)
  • The ids of specific coins (if we want to narrow down our list)
  • The order
  • The number per page
  • The page number, etc.

Similarly to the /coins/{id}/ohlc endpoint, we can use the pycoingecko library, instead of the requests library (like we did with /simple/price).

parameters = {
         'vs_currency': 'usd',
         'order': 'market_cap_desc',
         'per_page': 100,
         'page': 1,
         'sparkline': False,
         'locale': 'en'
         }
coin_market_data = cg.get_coins_markets(**parameters)
print(coin_market_data)

However, to avoid getting indigestible data, turn the output into a pandas DataFrame as we did before.

To overcome the undue number of columns, we can next employ pandas index slicing!

         df = pd.DataFrame(coin_market_data)
         df = df.drop(['id', 'symbol', 'image', 'high_24h', 'low_24h', 'price_change_24h', 'price_change_percentage_24h',
         'market_cap_change_24h','market_cap_change_percentage_24h', 'fully_diluted_valuation', 'ath_date', 'ath_change_percentage',
         'atl_change_percentage', 'atl_date', 'roi'],  axis = 1)
         df

Continue to readjust the desired area of the DataFrame, dropping columns through ‘df.drop’, whittling it down to the state we want it in:


How to Get Trending Crypto Price Data via Python

Using the “requests” library, we will navigate to the /search/trending endpoint to retrieve data on the top 7 trending coins on CoinGecko, as searched by users in the last 24 hours, with the most popular being ordered first.

url = ‘https://api.coingecko.com/api/v3/search/trending’
headers = {
         ‘accept’: ‘application/json’
}
response = requests.get(url, headers = headers)

The ‘accept’ header here is set to ‘application/json’, indicating the client – your Python script – prefers to receive the response in JSON format, which is informed by the ‘header’ to the server. For example, if you prefer to receive the response in XML format, you can set the ‘accept’ header to ‘application/xml’. This can be mirrored for other formats like CSV, HTML, or other media (MIME) types.

Next, write a similar ‘if’ statement, depending on if the request was successful or not. However, as we cannot simply mold this request into a DataFrame, because the resultant arrays we are trying to convert have differing lengths.

Therefore, we need to initialize an empty list where we will store the data for each coin, create a for loop that iterates through the ‘coins’ section of our JSON data, defaulting to an empty list ([]) if the ‘coins’ does not exist. Thereafter, we’ll extract the ‘item’ dictionary for each coin, create an empty dictionary if it does not exist, and finally append a dictionary to our list for each coin. The dictionary then contains information regarding the coins ‘id’, ‘name’, ‘symbol’, ‘market_cap_rank’, and ‘score’. The ‘get’ method is used for each key to extract the corresponding value from the dictionary, assigning a default value ‘’ for empty strings or 0 for integers.

if response.status_code == 200:
         # Convert the JSON response to a Python dictionary
         data = response.json()

         # Extract relevant fields from the JSON data (coins section)
         coin_data = []
         for coin in data.get('coins', []):
         coin_item = coin.get('item', {})
         coin_data.append({
         'id': coin_item.get('id', ''),
         'name': coin_item.get('name', ''),
         'symbol': coin_item.get('symbol', ''),
         'market_cap_rank': coin_item.get('market_cap_rank', 0),
         'score': coin_item.get('score', 0)
     })

         # Create a DataFrame from the extracted data
         df = pd.DataFrame(coin_data)

         # Display the DataFrame
         df

else:

         print(f"API request failed with status code: {response.status_code}")

 Our constructed DataFrame should appear as follows:


How to Get NFT Price Data with API

The easiest way to get NFT price data is through the /nft/list and /nft/{id} CoinGecko API endpoints, where you can pull a list of NFT collections and respective data pertaining to that NFT collection.

This can be done with the following Python script:

# Request for list of NFTs
nfts_list = cg.get_nfts_list(per_page=100, page=1)
# View what NFTs are covered and choose one (e.g. Squiggly)
url = 'https://api.coingecko.com/api/v3/nfts/squiggly'
response = requests.get(url)
if response.status_code == 200:
         squiggly_nft = response.json()
         synthesized_data = {
         'id': squiggly_nft['id'],
         'name': squiggly_nft['name'],
         'symbol': squiggly_nft['symbol'],
         'image': squiggly_nft['image'],
         'description': squiggly_nft['description'],
         'native_currency': squiggly_nft['native_currency'],
         'floor_price': squiggly_nft['floor_price'],
         'market_cap': squiggly_nft['market_cap'],
         'volume_24h': squiggly_nft['volume_24h']
         }

         # Create a DataFrame from the synthesized data
         df = pd.DataFrame([synthesized_data])
         df = df.drop(['symbol', 'image', 'id'], axis = 1)
         df

else:

         print("Request failed with status code:", response.status_code)

Essentially, this requests for a list of NFT collections, allowing us to sift through and pick from the available JSON data. Once selected, we append the NFT name to the end of the url (i.e. ‘https://api.coingecko.com/api/v3/nfts/squiggly’). Once the response status is successful, simply construct a new flattened data dictionary, selecting desired data and pulling it from the JSON text, before creating a dataframe around our synthesized data!


Unlock Exclusive API Endpoints

Evidently from the above, CoinGecko API provides access to coin prices, NFT activity, trending coins, derivatives, and many others.  Although the data returned is in JSON format, one can easily employ the pandas data science library to convert the response into an easily legible structure. 

To unlock exclusive API endpoints and historical prices, developers, traders and project founders can consider subscribing to our Analyst API plan. The CoinGecko API currently has 50+ endpoints, tracks 10,000+ coins across 800+ exchanges and 3,000+ NFT collections serving billions of API calls each month. If you require a custom solution, fill in the form below to get in touch with our API sales team:


Looking for further API resources? Check out this tutorial that covers 5 popular crypto trading strategies and how you can backtest using historical crypto data.