|
| 1 | +import requests |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +import datetime |
| 4 | + |
| 5 | +COINGECKO_API_URL = "https://api.coingecko.com/api/v3" |
| 6 | + |
| 7 | + |
| 8 | +def get_crypto_price(crypto_symbol): |
| 9 | + headers = {"accept": "application/json"} |
| 10 | + response = requests.get(f"{COINGECKO_API_URL}/simple/price", params={ |
| 11 | + 'ids': crypto_symbol, |
| 12 | + 'vs_currencies': 'usd', |
| 13 | + 'include_24hr_change': 'true' |
| 14 | + }, headers=headers) |
| 15 | + |
| 16 | + if response.status_code == 200: |
| 17 | + data = response.json() |
| 18 | + if crypto_symbol in data: |
| 19 | + price = data[crypto_symbol]['usd'] |
| 20 | + change_percentage = data[crypto_symbol]['usd_24h_change'] |
| 21 | + return price, change_percentage |
| 22 | + else: |
| 23 | + raise ValueError(f"Cryptocurrency '{crypto_symbol}' not found.") |
| 24 | + else: |
| 25 | + raise Exception(f"Failed to fetch data: {response.status_code} - {response.reason}") |
| 26 | + |
| 27 | + |
| 28 | +def get_historical_data(crypto_symbol, days): |
| 29 | + response = requests.get(f"{COINGECKO_API_URL}/coins/{crypto_symbol}/market_chart", params={ |
| 30 | + 'vs_currency': 'usd', |
| 31 | + 'days': days |
| 32 | + }) |
| 33 | + |
| 34 | + if response.status_code == 200: |
| 35 | + data = response.json() |
| 36 | + if 'prices' in data: |
| 37 | + return data['prices'] # Returns price data over the days |
| 38 | + else: |
| 39 | + raise ValueError(f"No historical data available for '{crypto_symbol}'.") |
| 40 | + else: |
| 41 | + raise Exception(f"Failed to fetch historical data: {response.status_code} - {response.reason}") |
| 42 | + |
| 43 | + |
| 44 | +def plot_historical_data(historical_data, crypto_symbol): |
| 45 | + dates = [datetime.datetime.fromtimestamp(item[0] / 1000) for item in historical_data] |
| 46 | + prices = [item[1] for item in historical_data] |
| 47 | + |
| 48 | + plt.figure(figsize=(10, 6)) |
| 49 | + plt.plot(dates, prices, marker='o', linestyle='-', color='b') |
| 50 | + plt.title(f'Historical Price Data for {crypto_symbol.capitalize()}') |
| 51 | + plt.xlabel('Date') |
| 52 | + plt.ylabel('Price (USD)') |
| 53 | + plt.xticks(rotation=45) |
| 54 | + plt.grid(True) |
| 55 | + plt.tight_layout() |
| 56 | + plt.show() |
| 57 | + |
| 58 | + |
| 59 | +def main(): |
| 60 | + crypto = input("Enter cryptocurrency symbol (eg. bitcoin, ethereum): ").lower() |
| 61 | + |
| 62 | + try: |
| 63 | + # Get real-time price and 24-hour change |
| 64 | + price, change = get_crypto_price(crypto) |
| 65 | + print(f"Current price of {crypto}: ${price}") |
| 66 | + print(f"24-hour change: {change:.2f}%") |
| 67 | + except ValueError as e: |
| 68 | + print(f"Error: {e}") |
| 69 | + return |
| 70 | + except Exception as e: |
| 71 | + print(f"Error fetching price data: {e}") |
| 72 | + return |
| 73 | + |
| 74 | + # Validate and get historical data |
| 75 | + while True: |
| 76 | + try: |
| 77 | + days = int(input("Enter the number of days for historical data (eg. 1, 7, 30): ")) |
| 78 | + if days <= 0: |
| 79 | + raise ValueError("The number of days must be a positive integer.") |
| 80 | + break |
| 81 | + except ValueError as e: |
| 82 | + print(f"Invalid input: {e}. Please enter a valid number.") |
| 83 | + |
| 84 | + try: |
| 85 | + historical_data = get_historical_data(crypto, days) |
| 86 | + print("Historical data retrieved successfully.") |
| 87 | + plot_historical_data(historical_data, crypto) |
| 88 | + except ValueError as e: |
| 89 | + print(f"Error: {e}") |
| 90 | + except Exception as e: |
| 91 | + print(f"Error fetching historical data: {e}") |
| 92 | + |
| 93 | + |
| 94 | +if __name__ == "__main__": |
| 95 | + main() |
0 commit comments