Advertisement
dravitch

Top10cryptoIndex

Nov 26th, 2024
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.59 KB | Cryptocurrency | 0 0
  1. # This Python script fetches real-time cryptocurrency data from CoinMarketCap and CryptoCompare APIs.
  2. # It calculates various indices (market cap index, volume index, total index) based on the retrieved data.
  3. # The script then generates various visualizations (pie charts, bar charts) to analyze the distribution of these indices among the top cryptocurrencies.
  4. # Finally, it exports the results to CSV and HTML files for further analysis.
  5.  
  6. # Start with:
  7. # !pip install requests pandas urllib3 matplotlib logging tenacity cryptocompare pycoinmarketcap tabulate
  8. # Then copy and paste or run the code below:
  9. import requests
  10. import pandas as pd
  11. from urllib.parse import urlencode
  12. from datetime import datetime
  13. import matplotlib.pyplot as plt
  14. import logging
  15. from tenacity import retry, stop_after_attempt, wait_fixed
  16.  
  17. # API configuration (Replace with your own API Keys)
  18.  
  19. # To use these APIs, you will need to obtain your own API keys from the following services:
  20.  
  21. # 1. CoinMarketCap
  22. #   - Visit https://pro.coinmarketcap.com/account/signup
  23. #   - Create a free account or choose a paid plan depending on your usage needs.
  24. #   - Once registered, navigate to your API Keys section in your account settings.
  25. #   - Generate a new API Key and copy it for later use.
  26.  
  27. CMC_API_URL = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
  28. CMC_API_KEY = "YOUR_COINMARKETCAP_API_KEY"  # Replace with your actual key
  29. CMC_HEADERS = {
  30.     "Accepts": "application/json",
  31.     "X-CMC_PRO_API_KEY": CMC_API_KEY,
  32. }
  33. CMC_PARAMS = {"limit": 100}
  34.  
  35. # 2. CryptoCompare
  36. #   - Visit https://www.cryptocompare.com/
  37. #   - Navigate to your profile settings and locate the API Keys section.
  38. #   - Generate a new API Key and copy it for later use.
  39.  
  40. CRYPTOCOMPARE_API_URL = "https://min-api.cryptocompare.com/data/top/mktcapfull"
  41. CRYPTOCOMPARE_API_KEY = "YOUR_CRYPTOCOMPARE_API_KEY"  # Replace with your actual key
  42. CRYPTOCOMPARE_HEADERS = {
  43.     "Authorization": f"Apikey {CRYPTOCOMPARE_API_KEY}",
  44. }
  45.  
  46.  
  47. # Function to retrieve top coins from CryptoCompare and format the data
  48. def get_top_coins_cc(reliable_coins):
  49.     """Fetches top cryptocurrencies from CryptoCompare API and formats the data.
  50.  
  51.    Args:
  52.        reliable_coins (list): A list of reliable cryptocurrency symbols.
  53.  
  54.    Returns:
  55.        pandas.DataFrame: A DataFrame containing formatted cryptocurrency data.
  56.    """
  57.     try:
  58.         # Send a GET request to the CryptoCompare API
  59.         response = requests.get(f"{CRYPTOCOMPARE_API_URL}?limit=100&tsym=USD", headers=CRYPTOCOMPARE_HEADERS)
  60.         response.raise_for_status()
  61.         data = response.json()
  62.  
  63.         # Filter coins based on the provided reliable_coins list and format the data
  64.         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]
  65.         return pd.DataFrame(coins)
  66.     except requests.exceptions.RequestException as e:
  67.         logging.error(f"Error fetching data from CryptoCompare API: {e}")
  68.         return None
  69.  
  70. # Function to format cryptocurrency data
  71. def format_cc_data(coin):
  72.     """Formats cryptocurrency data from CryptoCompare API.
  73.  
  74.    Args:
  75.        coin (dict): A dictionary containing cryptocurrency data from the API.
  76.  
  77.    Returns:
  78.        dict: A dictionary containing formatted cryptocurrency data.
  79.    """
  80.     try:
  81.         # Extract and format price, volume, and market cap
  82.         price = float(coin["RAW"]["USD"]["PRICE"])
  83.         volume = float(coin["RAW"]["USD"]["TOTALVOLUME24H"])
  84.         market_cap = float(coin["RAW"]["USD"]["MKTCAP"])
  85.         # ... (rounding logic)
  86.  
  87.         return {
  88.             "Nom": coin["CoinInfo"]["FullName"],
  89.             "Symbole": coin["CoinInfo"]["Name"],
  90.             "Prix USD": price,
  91.             "Volume 24h USD": round(volume, 2),
  92.             "Capitalisation boursière USD": round(market_cap, 2),
  93.         }
  94.     except ValueError as e:
  95.         print(f"Warning: Invalid data format for {coin['CoinInfo']['Name']}: {e}")
  96.     except KeyError as e:
  97.         print(f"Warning: Missing data for {coin['CoinInfo']['Name']}: {e}")
  98.  
  99. # Calculate indices
  100. def calculate_indices(df):
  101.     """Calculates indices for a given DataFrame of cryptocurrency data.
  102.  
  103.    Args:
  104.        df (pandas.DataFrame): The DataFrame containing cryptocurrency data.
  105.  
  106.    Returns:
  107.        pandas.DataFrame: The DataFrame with additional columns for indices.
  108.    """
  109.     total_market_cap = df["Capitalisation boursière USD"].sum()
  110.     total_volume = df["Volume 24h USD"].sum()
  111.     df["Indice MC"] = round(df["Capitalisation boursière USD"] / total_market_cap, 4)
  112.     df["Indice V"] = round(df["Volume 24h USD"] / total_volume, 4)
  113.     df["Indice Total"] = round((0.7 * df["Indice MC"]) + (0.3 * df["Indice V"]), 4)
  114.     return df
  115.  
  116. # Fonction to record indexces historical
  117. historical_data = []
  118.  
  119. # Main execution
  120. def main():
  121.     # Define a list of reliable coins
  122.     reliable_coins = ["BTC", "ETH", "USDT", "USDC", "BNB", "XRP", "BUSD", "ADA", "SOL", "TRON", "AVAX", "TON"] # Example list, replace with your desired coins
  123.  
  124.     # Retrieve data from CryptoCompare, passing the reliable_coins list
  125.     top_coins_df = get_top_coins_cc(reliable_coins)
  126.  
  127.     if top_coins_df is None or top_coins_df.empty:
  128.         print("No data available.")
  129.         return
  130.  
  131.     # Calculate indices and add to historical data
  132.     top_coins_df = calculate_indices(top_coins_df)
  133.     top_coins_df = top_coins_df.sort_values("Indice Total", ascending=False)
  134.  
  135.     # Add current data to historical data
  136.     current_datetime = datetime.now().strftime("%Y%m%d_%H%M%S")
  137.     historical_data.append(top_coins_df[["Nom", "Symbole", "Indice V", "Indice Total"]])
  138.  
  139.     # Export results to CSV and HTML
  140.     top_coins_df.to_csv(f"top_coins_{current_datetime}.csv", index=False)
  141.     top_coins_df.to_html(f"top_coins_{current_datetime}.html", index=False)
  142.  
  143.     # Display top 10 coins by Total Index
  144.     print("*****************************************************************")
  145.     print("🔝 Top 10 cryptocurrencies by Total Index:")
  146.     print(top_coins_df[["Nom", "Symbole", "Prix USD", "Indice Total"]].head(10).to_markdown(index=False))
  147.     print("*****************************************************************")
  148.  
  149.     # Create a pie chart for Total Index distribution
  150.     top_10 = top_coins_df.head(10)
  151.     plt.figure(figsize=(5, 5))
  152.     plt.pie(
  153.         top_10["Indice Total"],
  154.         labels=top_10["Nom"],
  155.         autopct=lambda p: f'{p:.1f}%',
  156.         startangle=140,
  157.         colors=plt.cm.tab20.colors[:10]
  158.     )
  159.     plt.title("Total Index Distribution (Top 10 Cryptos)")
  160.     plt.axis("equal")
  161.     plt.show()
  162.  
  163.     # Display top 10 coins by Volume Index
  164.     #sorted_by_v = top_coins_df.sort_values("Indice V", ascending=False)
  165.     sorted_by_v = top_coins_df.sort_values("Volume 24h USD", ascending=False)  # Sort by Volume 24h USD
  166.  
  167.     print("*****************************************************************")
  168.     print("🔝 Top 10 cryptocurrencies by 24h Volume Index:")
  169.     print(sorted_by_v[["Nom", "Symbole", "Prix USD", "Indice V", "Volume 24h USD"]].head(10).to_markdown(index=False))
  170.     print("*****************************************************************")
  171.  
  172.     # Create a horizontal bar chart for Volume Index
  173.     plt.figure(figsize=(6, 4))
  174.     plt.barh(sorted_by_v["Nom"].head(10), sorted_by_v["Indice V"].head(10), color="teal")
  175.     plt.xlabel("Volume Index (24h)")
  176.     plt.ylabel("Cryptocurrencies")
  177.     plt.title("Top 10 Cryptocurrencies by 24h Volume Index")
  178.     plt.gca().invert_yaxis()  # Invert y-axis to display top coins at the top
  179.     plt.show()
  180.  
  181. if __name__ == "__main__":
  182.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement