#!/usr/bin/env python3 """ Crypto Portfolio Tracker A simple script to track cryptocurrency prices and portfolio value. Fetches real-time data from CoinGecko API (no API key required). """ import json import urllib.request from datetime import datetime def fetch_prices(coins: list[str], currency: str = "usd") -> dict: """Fetch current prices for specified coins from CoinGecko.""" coin_ids = ",".join(coins) url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_ids}&vs_currencies={currency}&include_24hr_change=true" try: with urllib.request.urlopen(url, timeout=10) as response: return json.loads(response.read().decode()) except Exception as e: print(f"Error fetching prices: {e}") return {} def calculate_portfolio_value(holdings: dict, prices: dict, currency: str = "usd") -> dict: """Calculate total portfolio value and per-coin breakdown.""" breakdown = {} total = 0.0 for coin, amount in holdings.items(): if coin in prices and currency in prices[coin]: price = prices[coin][currency] value = amount * price change_24h = prices[coin].get(f"{currency}_24h_change", 0) breakdown[coin] = { "amount": amount, "price": price, "value": value, "change_24h": change_24h } total += value return {"breakdown": breakdown, "total": total} def format_currency(value: float, symbol: str = "$") -> str: """Format a number as currency.""" return f"{symbol}{value:,.2f}" def format_percent(value: float) -> str: """Format a number as percentage with color indicator.""" sign = "+" if value >= 0 else "" indicator = "📈" if value >= 0 else "📉" return f"{indicator} {sign}{value:.2f}%" def print_portfolio_report(portfolio: dict, currency_symbol: str = "$"): """Print a formatted portfolio report.""" print("\n" + "=" * 50) print(f" PORTFOLIO REPORT - {datetime.now().strftime('%Y-%m-%d %H:%M')}") print("=" * 50 + "\n") for coin, data in portfolio["breakdown"].items(): print(f" {coin.upper()}") print(f" Holdings: {data['amount']:.6f}") print(f" Price: {format_currency(data['price'], currency_symbol)}") print(f" Value: {format_currency(data['value'], currency_symbol)}") print(f" 24h: {format_percent(data['change_24h'])}") print() print("-" * 50) print(f" TOTAL VALUE: {format_currency(portfolio['total'], currency_symbol)}") print("=" * 50 + "\n") def main(): # Example portfolio - customize with your holdings my_holdings = { "bitcoin": 0.5, "ethereum": 2.0, "solana": 10.0, } print("Fetching latest prices...") prices = fetch_prices(list(my_holdings.keys())) if not prices: print("Failed to fetch prices. Check your connection.") return portfolio = calculate_portfolio_value(my_holdings, prices) print_portfolio_report(portfolio) if __name__ == "__main__": main()