Looping through coin market cap

504 views Asked by At

Hey everyone I am trying to access the Coin Market Cap API and return the top 5000 slugs their price and there 24 hour change in volume. I want to save what is returned to a CSV file as well so I can add it to a data frame. I tried a few time to write a loop using the response variable but have had no luck. Any help will be great!

from inspect import Parameter
from requests import Request, Session
import json

url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest' # Coinmarketcap API url

headers = {
        'Accepts': 'application/json',
        'X-CMC_PRO_API_KEY': 'API KEY'
    } 

parameter = {'slug':**, 'convert': 'USD' }

session = Session()
session.headers.update(headers)

response = session.get(url, params=parameter)

for parameter in response:
    print(parameter)

print(response)
1

There are 1 answers

0
ouroboros1 On

Try something as follows:

import requests
import pandas as pd
import json

API_KEY = 'your_api_key_as_string'
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

HEADERS = {'Accepts': 'application/json',
           'X-CMC_PRO_API_KEY': API_KEY}

PARAMS = {'convert': 'USD',
          'limit': 5000}

resp = requests.get(url, headers=HEADERS, params=PARAMS)

def get_data(resp):
    data = json.loads(resp.content)['data']
    rows = list()

    # check appropriate keys, e.g.:
    # data[0].keys()
    # dict_keys(['..., 'slug', ..., 'quote'])

    # check keys for `quote`:
    # data[0]['quote'].keys() # always only 'USD'
    # data[0]['quote']['USD'].keys()
    # dict_keys([..., 'volume_24h', ..., 'market_cap', ..., 'last_updated'])
    
    for item in data:
        rows.append([
             item['slug'], 
             item['quote']['USD']['market_cap'],
             item['quote']['USD']['volume_24h'],
             item['quote']['USD']['last_updated']])

    df = pd.DataFrame(
        rows, columns=['slug','market_cap','volume_24h','last_updated'])

    # remove timezone from datetime64[ns, UTC] in `last_updated`
    df['last_updated'] = pd.to_datetime(df.last_updated).dt.tz_localize(None)
    df.index.name = 'id'
    return(df)

if resp.status_code == 200:
    df = get_data(resp)
    # write to csv
    df.to_csv('crypto_latests.csv')
else:
    # bad request, handle error
    print(resp.status_code)

Result:

print(df.head())

        slug    market_cap    volume_24h        last_updated
id                                                          
0    bitcoin  3.861454e+11  4.041023e+10 2022-09-15 09:45:00
1   ethereum  1.951680e+11  2.509653e+10 2022-09-15 09:45:00
2     tether  6.789316e+10  6.372894e+10 2022-09-15 09:45:00
3   usd-coin  5.075118e+10  7.255377e+09 2022-09-15 09:45:00
4        bnb  4.450807e+10  1.128343e+09 2022-09-15 09:45:00

print(df.shape)
# (5000, 4)