Advertisement
dravitch

Top10cryptoIndex-Custom

Nov 28th, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.91 KB | None | 0 0
  1. """
  2. Cryptocurrency Portfolio Allocation and Analysis Tool
  3.  
  4. DISCLAIMER: THIS SCRIPT IS PROVIDED FOR EDUCATIONAL PURPOSES ONLY.
  5. IT IS NOT FINANCIAL ADVICE. CRYPTOCURRENCY INVESTMENTS ARE HIGHLY
  6. VOLATILE AND CARRY SIGNIFICANT RISK. ALWAYS CONDUCT YOUR OWN RESEARCH
  7. AND CONSULT WITH A QUALIFIED FINANCIAL ADVISOR BEFORE MAKING ANY
  8. INVESTMENT DECISIONS.
  9.  
  10. Description:
  11. This script allows users to:
  12. - Retrieve current cryptocurrency market data from CoinGecko API
  13. - Select multiple cryptocurrencies to analyze
  14. - Calculate portfolio allocation based on market capitalization and trading volume on the last 24h
  15. - Display investment insights and potential portfolio distributions
  16.  
  17. Key Features:
  18. - Fetches real-time crypto market data
  19. - Interactive cryptocurrency selection
  20. - Portfolio allocation calculation
  21. - Market cap and volume-based indexing
  22.  
  23. Dependencies:
  24. - requests
  25. - pandas
  26. - logging
  27. """
  28.  
  29. import os
  30. import requests
  31. import pandas as pd
  32. import logging
  33. from typing import List, Dict, Optional
  34.  
  35. # Logging configuration
  36. logging.basicConfig(
  37.     level=logging.INFO,
  38.     format='%(asctime)s - %(levelname)s: %(message)s'
  39. )
  40.  
  41. # Configuration
  42. COINGECKO_API_URL = "https://api.coingecko.com/api/v3"
  43.  
  44. def get_crypto_market_data(num_coins: int = 100) -> Optional[List[Dict]]:
  45.     """
  46.    Fetch top cryptocurrencies by market capitalization from CoinGecko API.
  47.    
  48.    Args:
  49.        num_coins (int): Number of top cryptocurrencies to retrieve. Defaults to 10.
  50.    
  51.    Returns:
  52.        Optional[List[Dict]]: List of cryptocurrency market data or None if request fails
  53.    """
  54.     try:
  55.         url = f"{COINGECKO_API_URL}/coins/markets"
  56.         params = {
  57.             "vs_currency": "usd",
  58.             "order": "market_cap_desc",
  59.             "per_page": num_coins,
  60.             "page": 1,
  61.             "sparkline": False
  62.         }
  63.        
  64.         response = requests.get(url, params=params, timeout=10)
  65.         response.raise_for_status()
  66.        
  67.         return response.json()
  68.     except requests.RequestException as e:
  69.         logging.error(f"Error fetching crypto market data: {e}")
  70.         return None
  71.  
  72. def get_selected_cryptocurrencies(cryptos: List[Dict]) -> List[Dict]:
  73.     """
  74.    Interactively select cryptocurrencies for analysis.
  75.    
  76.    Args:
  77.        cryptos (List[Dict]): List of cryptocurrency market data
  78.    
  79.    Returns:
  80.        List[Dict]: List of selected cryptocurrencies
  81.    """
  82.     print("Available Cryptocurrencies:")
  83.     for i, crypto in enumerate(cryptos, start=1):
  84.         print(f"{i}. {crypto['name']} ({crypto['symbol'].upper()})")
  85.  
  86.     # Number of cryptocurrencies selection
  87.     while True:
  88.         try:
  89.             n = int(input("\nHow many cryptocurrencies do you want to analyze? (1-10): "))
  90.             if 1 <= n <= 10:
  91.                 break
  92.             print("Please enter a number between 1 and 10.")
  93.         except ValueError:
  94.             print("Invalid input. Please enter an integer.")
  95.  
  96.     # Cryptocurrency selection
  97.     selected_indices = set()
  98.     selected_coins = []
  99.     while len(selected_indices) < n:
  100.         try:
  101.             num = int(input(f"Enter the number of a cryptocurrency (1-{len(cryptos)}): "))
  102.             if 1 <= num <= len(cryptos):
  103.                 if num in selected_indices:
  104.                     print("You have already selected this cryptocurrency. Choose another.")
  105.                 else:
  106.                     selected_indices.add(num)
  107.                     selected_coins.append(cryptos[num - 1])
  108.             else:
  109.                 print(f"Please enter a number between 1 and {len(cryptos)}.")
  110.         except ValueError:
  111.             print("Invalid input. Please enter a number.")
  112.  
  113.     return selected_coins
  114.  
  115. def calculate_portfolio_allocation(selected_coins: List[Dict], initial_investment: float) -> None:
  116.     """
  117.    Calculate and display portfolio allocation based on market cap and volume.
  118.    
  119.    Args:
  120.        selected_coins (List[Dict]): Selected cryptocurrencies
  121.        initial_investment (float): Initial investment amount in USD
  122.    """
  123.     # Market Cap Allocation
  124.     total_market_cap = sum(coin["market_cap"] for coin in selected_coins)
  125.     market_cap_index = [coin["market_cap"] / total_market_cap for coin in selected_coins]
  126.     market_cap_allocation = [round(index * initial_investment, 2) for index in market_cap_index]
  127.  
  128.     # Volume-based Index
  129.     total_volume = sum(coin["total_volume"] for coin in selected_coins)
  130.     volume_index = [coin["total_volume"] / total_volume for coin in selected_coins]
  131.  
  132.     # Display Market Cap Based Allocation
  133.     print("\n" + "*" * 65)
  134.     print(" Market Cap Based Index:")
  135.     df_market = pd.DataFrame({
  136.         "Name": [coin["name"].capitalize() for coin in selected_coins],
  137.         "Symbol": [coin["symbol"].upper() for coin in selected_coins],
  138.         "Price (USD)": [coin["current_price"] for coin in selected_coins],
  139.         "Market Cap Index": market_cap_index,
  140.         "Allocation (USD)": market_cap_allocation
  141.     })
  142.     print(df_market.to_markdown(index=False, colalign=("left", "left", "left", "right", "right")))
  143.     print("*" * 65)
  144.  
  145.     # Display Volume-based Index
  146.     print("\n" + "*" * 65)
  147.     print(" 24h Volume Based Index:")
  148.     df_volume = pd.DataFrame({
  149.         "Name": [coin["name"].capitalize() for coin in selected_coins],
  150.         "Symbol": [coin["symbol"].upper() for coin in selected_coins],
  151.         "Price (USD)": [coin["current_price"] for coin in selected_coins],
  152.         "Volume Index": volume_index,
  153.         "24h Volume (USD)": [coin["total_volume"] for coin in selected_coins]
  154.     })
  155.     print(df_volume.to_markdown(index=False, colalign=("left", "left", "left", "right", "right")))
  156.     print("*" * 65)
  157.  
  158. def get_initial_investment() -> float:
  159.     """
  160.    Prompt user for initial investment amount.
  161.    
  162.    Returns:
  163.        float: Initial investment amount in USD
  164.    """
  165.     while True:
  166.         try:
  167.             amount = float(input("\nEnter your initial investment amount (in USD): "))
  168.             if amount > 0:
  169.                 return amount
  170.             print("Please enter an amount greater than 0.")
  171.         except ValueError:
  172.             print("Invalid input. Please enter a valid amount.")
  173.  
  174. def main():
  175.     """
  176.    Main function to orchestrate cryptocurrency portfolio analysis.
  177.    """
  178.     try:
  179.         # Fetch cryptocurrency market data
  180.         cryptos = get_crypto_market_data()
  181.         if not cryptos:
  182.             print("Unable to retrieve cryptocurrency market data.")
  183.             return
  184.  
  185.         # Select cryptocurrencies
  186.         selected_coins = get_selected_cryptocurrencies(cryptos)
  187.  
  188.         # Get initial investment
  189.         initial_investment = get_initial_investment()
  190.  
  191.         # Calculate and display portfolio allocation
  192.         calculate_portfolio_allocation(selected_coins, initial_investment)
  193.  
  194.     except Exception as e:
  195.         logging.error(f"An unexpected error occurred: {e}")
  196.  
  197. if __name__ == "__main__":
  198.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement