Hey there, fellow dev! Ready to dive into the world of crypto data? Let's build something cool with the CoinMarketCap API using Python. We'll be using the coinmarketcap
package to make our lives easier. Buckle up!
Before we jump in, make sure you've got:
First things first, let's get that package installed:
pip install coinmarketcap
Easy peasy, right?
Now, let's import what we need and set up our client:
from coinmarketcap import Market cmc = Market() cmc.cryptocurrency_map()
Boom! You're connected and ready to roll.
Let's fetch some data:
# Get the latest listings listings = cmc.cryptocurrency_listings_latest() # Get info on a specific coin (let's use Bitcoin as an example) bitcoin_data = cmc.cryptocurrency_info(symbol='BTC')
Just like that, you've got access to a treasure trove of crypto data!
Want to get fancy? Let's handle pagination and use some custom parameters:
# Get top 100 cryptocurrencies top_100 = cmc.cryptocurrency_listings_latest(limit=100) # Get historical data for Ethereum eth_historical = cmc.cryptocurrency_quotes_historical(symbol='ETH', time_start='2022-01-01', time_end='2022-12-31')
Always be a good API citizen:
import time try: data = cmc.cryptocurrency_listings_latest() except Exception as e: print(f"Oops! Something went wrong: {e}") time.sleep(60) # Be nice, respect rate limits
Let's make sense of all this data:
import pandas as pd df = pd.DataFrame(listings['data']) top_10_by_market_cap = df.sort_values('market_cap', ascending=False).head(10) print(top_10_by_market_cap[['name', 'symbol', 'market_cap']])
Let's put it all together:
def get_top_n_cryptos(n=10): data = cmc.cryptocurrency_listings_latest(limit=n) for coin in data['data']: print(f"{coin['name']} ({coin['symbol']}): ${coin['quote']['USD']['price']:.2f}") get_top_n_cryptos(5)
And there you have it! You've just built a CoinMarketCap API integration in Python. Pretty cool, huh? This is just the tip of the iceberg - there's so much more you can do with this API. Why not try building a real-time price tracker or a portfolio analyzer next?
Want to dig deeper? Check out these resources:
Happy coding, crypto enthusiast!