Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Cryptocurrency Portfolio Allocation and Analysis Tool
- DISCLAIMER: THIS SCRIPT IS PROVIDED FOR EDUCATIONAL PURPOSES ONLY.
- IT IS NOT FINANCIAL ADVICE. CRYPTOCURRENCY INVESTMENTS ARE HIGHLY
- VOLATILE AND CARRY SIGNIFICANT RISK. ALWAYS CONDUCT YOUR OWN RESEARCH
- AND CONSULT WITH A QUALIFIED FINANCIAL ADVISOR BEFORE MAKING ANY
- INVESTMENT DECISIONS.
- Description:
- This script allows users to:
- - Retrieve current cryptocurrency market data from CoinGecko API
- - Select multiple cryptocurrencies to analyze
- - Calculate portfolio allocation based on market capitalization and trading volume on the last 24h
- - Display investment insights and potential portfolio distributions
- Key Features:
- - Fetches real-time crypto market data
- - Interactive cryptocurrency selection
- - Portfolio allocation calculation
- - Market cap and volume-based indexing
- Dependencies:
- - requests
- - pandas
- - logging
- """
- import os
- import requests
- import pandas as pd
- import logging
- from typing import List, Dict, Optional
- # Logging configuration
- logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(levelname)s: %(message)s'
- )
- # Configuration
- COINGECKO_API_URL = "https://api.coingecko.com/api/v3"
- def get_crypto_market_data(num_coins: int = 100) -> Optional[List[Dict]]:
- """
- Fetch top cryptocurrencies by market capitalization from CoinGecko API.
- Args:
- num_coins (int): Number of top cryptocurrencies to retrieve. Defaults to 10.
- Returns:
- Optional[List[Dict]]: List of cryptocurrency market data or None if request fails
- """
- try:
- url = f"{COINGECKO_API_URL}/coins/markets"
- params = {
- "vs_currency": "usd",
- "order": "market_cap_desc",
- "per_page": num_coins,
- "page": 1,
- "sparkline": False
- }
- response = requests.get(url, params=params, timeout=10)
- response.raise_for_status()
- return response.json()
- except requests.RequestException as e:
- logging.error(f"Error fetching crypto market data: {e}")
- return None
- def get_selected_cryptocurrencies(cryptos: List[Dict]) -> List[Dict]:
- """
- Interactively select cryptocurrencies for analysis.
- Args:
- cryptos (List[Dict]): List of cryptocurrency market data
- Returns:
- List[Dict]: List of selected cryptocurrencies
- """
- print("Available Cryptocurrencies:")
- for i, crypto in enumerate(cryptos, start=1):
- print(f"{i}. {crypto['name']} ({crypto['symbol'].upper()})")
- # Number of cryptocurrencies selection
- while True:
- try:
- n = int(input("\nHow many cryptocurrencies do you want to analyze? (1-10): "))
- if 1 <= n <= 10:
- break
- print("Please enter a number between 1 and 10.")
- except ValueError:
- print("Invalid input. Please enter an integer.")
- # Cryptocurrency selection
- selected_indices = set()
- selected_coins = []
- while len(selected_indices) < n:
- try:
- num = int(input(f"Enter the number of a cryptocurrency (1-{len(cryptos)}): "))
- if 1 <= num <= len(cryptos):
- if num in selected_indices:
- print("You have already selected this cryptocurrency. Choose another.")
- else:
- selected_indices.add(num)
- selected_coins.append(cryptos[num - 1])
- else:
- print(f"Please enter a number between 1 and {len(cryptos)}.")
- except ValueError:
- print("Invalid input. Please enter a number.")
- return selected_coins
- def calculate_portfolio_allocation(selected_coins: List[Dict], initial_investment: float) -> None:
- """
- Calculate and display portfolio allocation based on market cap and volume.
- Args:
- selected_coins (List[Dict]): Selected cryptocurrencies
- initial_investment (float): Initial investment amount in USD
- """
- # Market Cap Allocation
- total_market_cap = sum(coin["market_cap"] for coin in selected_coins)
- market_cap_index = [coin["market_cap"] / total_market_cap for coin in selected_coins]
- market_cap_allocation = [round(index * initial_investment, 2) for index in market_cap_index]
- # Volume-based Index
- total_volume = sum(coin["total_volume"] for coin in selected_coins)
- volume_index = [coin["total_volume"] / total_volume for coin in selected_coins]
- # Display Market Cap Based Allocation
- print("\n" + "*" * 65)
- print(" Market Cap Based Index:")
- df_market = pd.DataFrame({
- "Name": [coin["name"].capitalize() for coin in selected_coins],
- "Symbol": [coin["symbol"].upper() for coin in selected_coins],
- "Price (USD)": [coin["current_price"] for coin in selected_coins],
- "Market Cap Index": market_cap_index,
- "Allocation (USD)": market_cap_allocation
- })
- print(df_market.to_markdown(index=False, colalign=("left", "left", "left", "right", "right")))
- print("*" * 65)
- # Display Volume-based Index
- print("\n" + "*" * 65)
- print(" 24h Volume Based Index:")
- df_volume = pd.DataFrame({
- "Name": [coin["name"].capitalize() for coin in selected_coins],
- "Symbol": [coin["symbol"].upper() for coin in selected_coins],
- "Price (USD)": [coin["current_price"] for coin in selected_coins],
- "Volume Index": volume_index,
- "24h Volume (USD)": [coin["total_volume"] for coin in selected_coins]
- })
- print(df_volume.to_markdown(index=False, colalign=("left", "left", "left", "right", "right")))
- print("*" * 65)
- def get_initial_investment() -> float:
- """
- Prompt user for initial investment amount.
- Returns:
- float: Initial investment amount in USD
- """
- while True:
- try:
- amount = float(input("\nEnter your initial investment amount (in USD): "))
- if amount > 0:
- return amount
- print("Please enter an amount greater than 0.")
- except ValueError:
- print("Invalid input. Please enter a valid amount.")
- def main():
- """
- Main function to orchestrate cryptocurrency portfolio analysis.
- """
- try:
- # Fetch cryptocurrency market data
- cryptos = get_crypto_market_data()
- if not cryptos:
- print("Unable to retrieve cryptocurrency market data.")
- return
- # Select cryptocurrencies
- selected_coins = get_selected_cryptocurrencies(cryptos)
- # Get initial investment
- initial_investment = get_initial_investment()
- # Calculate and display portfolio allocation
- calculate_portfolio_allocation(selected_coins, initial_investment)
- except Exception as e:
- logging.error(f"An unexpected error occurred: {e}")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement