Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This Python script fetches real-time cryptocurrency data from CoinMarketCap and CryptoCompare APIs.
- # It calculates various indices (market cap index, volume index, total index) based on the retrieved data.
- # The script then generates various visualizations (pie charts, bar charts) to analyze the distribution of these indices among the top cryptocurrencies.
- # Finally, it exports the results to CSV and HTML files for further analysis.
- # Start with:
- # !pip install requests pandas urllib3 matplotlib logging tenacity cryptocompare pycoinmarketcap tabulate
- # Then copy and paste or run the code below:
- import requests
- import pandas as pd
- from urllib.parse import urlencode
- from datetime import datetime
- import matplotlib.pyplot as plt
- import logging
- from tenacity import retry, stop_after_attempt, wait_fixed
- # API configuration (Replace with your own API Keys)
- # To use these APIs, you will need to obtain your own API keys from the following services:
- # 1. CoinMarketCap
- # - Visit https://pro.coinmarketcap.com/account/signup
- # - Create a free account or choose a paid plan depending on your usage needs.
- # - Once registered, navigate to your API Keys section in your account settings.
- # - Generate a new API Key and copy it for later use.
- CMC_API_URL = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
- CMC_API_KEY = "YOUR_COINMARKETCAP_API_KEY" # Replace with your actual key
- CMC_HEADERS = {
- "Accepts": "application/json",
- "X-CMC_PRO_API_KEY": CMC_API_KEY,
- }
- CMC_PARAMS = {"limit": 100}
- # 2. CryptoCompare
- # - Visit https://www.cryptocompare.com/
- # - Navigate to your profile settings and locate the API Keys section.
- # - Generate a new API Key and copy it for later use.
- CRYPTOCOMPARE_API_URL = "https://min-api.cryptocompare.com/data/top/mktcapfull"
- CRYPTOCOMPARE_API_KEY = "YOUR_CRYPTOCOMPARE_API_KEY" # Replace with your actual key
- CRYPTOCOMPARE_HEADERS = {
- "Authorization": f"Apikey {CRYPTOCOMPARE_API_KEY}",
- }
- # Function to retrieve top coins from CryptoCompare and format the data
- def get_top_coins_cc(reliable_coins):
- """Fetches top cryptocurrencies from CryptoCompare API and formats the data.
- Args:
- reliable_coins (list): A list of reliable cryptocurrency symbols.
- Returns:
- pandas.DataFrame: A DataFrame containing formatted cryptocurrency data.
- """
- try:
- # Send a GET request to the CryptoCompare API
- response = requests.get(f"{CRYPTOCOMPARE_API_URL}?limit=100&tsym=USD", headers=CRYPTOCOMPARE_HEADERS)
- response.raise_for_status()
- data = response.json()
- # Filter coins based on the provided reliable_coins list and format the data
- coins = [format_cc_data(coin) for coin in data["Data"] if coin["CoinInfo"]["Name"] in reliable_coins and format_cc_data(coin) is not None]
- return pd.DataFrame(coins)
- except requests.exceptions.RequestException as e:
- logging.error(f"Error fetching data from CryptoCompare API: {e}")
- return None
- # Function to format cryptocurrency data
- def format_cc_data(coin):
- """Formats cryptocurrency data from CryptoCompare API.
- Args:
- coin (dict): A dictionary containing cryptocurrency data from the API.
- Returns:
- dict: A dictionary containing formatted cryptocurrency data.
- """
- try:
- # Extract and format price, volume, and market cap
- price = float(coin["RAW"]["USD"]["PRICE"])
- volume = float(coin["RAW"]["USD"]["TOTALVOLUME24H"])
- market_cap = float(coin["RAW"]["USD"]["MKTCAP"])
- # ... (rounding logic)
- return {
- "Nom": coin["CoinInfo"]["FullName"],
- "Symbole": coin["CoinInfo"]["Name"],
- "Prix USD": price,
- "Volume 24h USD": round(volume, 2),
- "Capitalisation boursière USD": round(market_cap, 2),
- }
- except ValueError as e:
- print(f"Warning: Invalid data format for {coin['CoinInfo']['Name']}: {e}")
- except KeyError as e:
- print(f"Warning: Missing data for {coin['CoinInfo']['Name']}: {e}")
- # Calculate indices
- def calculate_indices(df):
- """Calculates indices for a given DataFrame of cryptocurrency data.
- Args:
- df (pandas.DataFrame): The DataFrame containing cryptocurrency data.
- Returns:
- pandas.DataFrame: The DataFrame with additional columns for indices.
- """
- total_market_cap = df["Capitalisation boursière USD"].sum()
- total_volume = df["Volume 24h USD"].sum()
- df["Indice MC"] = round(df["Capitalisation boursière USD"] / total_market_cap, 4)
- df["Indice V"] = round(df["Volume 24h USD"] / total_volume, 4)
- df["Indice Total"] = round((0.7 * df["Indice MC"]) + (0.3 * df["Indice V"]), 4)
- return df
- # Fonction to record indexces historical
- historical_data = []
- # Main execution
- def main():
- # Define a list of reliable coins
- reliable_coins = ["BTC", "ETH", "USDT", "USDC", "BNB", "XRP", "BUSD", "ADA", "SOL", "TRON", "AVAX", "TON"] # Example list, replace with your desired coins
- # Retrieve data from CryptoCompare, passing the reliable_coins list
- top_coins_df = get_top_coins_cc(reliable_coins)
- if top_coins_df is None or top_coins_df.empty:
- print("No data available.")
- return
- # Calculate indices and add to historical data
- top_coins_df = calculate_indices(top_coins_df)
- top_coins_df = top_coins_df.sort_values("Indice Total", ascending=False)
- # Add current data to historical data
- current_datetime = datetime.now().strftime("%Y%m%d_%H%M%S")
- historical_data.append(top_coins_df[["Nom", "Symbole", "Indice V", "Indice Total"]])
- # Export results to CSV and HTML
- top_coins_df.to_csv(f"top_coins_{current_datetime}.csv", index=False)
- top_coins_df.to_html(f"top_coins_{current_datetime}.html", index=False)
- # Display top 10 coins by Total Index
- print("*****************************************************************")
- print("🔝 Top 10 cryptocurrencies by Total Index:")
- print(top_coins_df[["Nom", "Symbole", "Prix USD", "Indice Total"]].head(10).to_markdown(index=False))
- print("*****************************************************************")
- # Create a pie chart for Total Index distribution
- top_10 = top_coins_df.head(10)
- plt.figure(figsize=(5, 5))
- plt.pie(
- top_10["Indice Total"],
- labels=top_10["Nom"],
- autopct=lambda p: f'{p:.1f}%',
- startangle=140,
- colors=plt.cm.tab20.colors[:10]
- )
- plt.title("Total Index Distribution (Top 10 Cryptos)")
- plt.axis("equal")
- plt.show()
- # Display top 10 coins by Volume Index
- #sorted_by_v = top_coins_df.sort_values("Indice V", ascending=False)
- sorted_by_v = top_coins_df.sort_values("Volume 24h USD", ascending=False) # Sort by Volume 24h USD
- print("*****************************************************************")
- print("🔝 Top 10 cryptocurrencies by 24h Volume Index:")
- print(sorted_by_v[["Nom", "Symbole", "Prix USD", "Indice V", "Volume 24h USD"]].head(10).to_markdown(index=False))
- print("*****************************************************************")
- # Create a horizontal bar chart for Volume Index
- plt.figure(figsize=(6, 4))
- plt.barh(sorted_by_v["Nom"].head(10), sorted_by_v["Indice V"].head(10), color="teal")
- plt.xlabel("Volume Index (24h)")
- plt.ylabel("Cryptocurrencies")
- plt.title("Top 10 Cryptocurrencies by 24h Volume Index")
- plt.gca().invert_yaxis() # Invert y-axis to display top coins at the top
- plt.show()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement