|
| 1 | +import requests |
| 2 | + |
| 3 | +COINGECKO_API_URL = "https://api.coingecko.com/api/v3" |
| 4 | + |
| 5 | + |
| 6 | +def get_crypto_price(crypto_symbol): |
| 7 | + headers = {"accept": "application/json"} |
| 8 | + response = requests.get(f"{COINGECKO_API_URL}/simple/price", params={ |
| 9 | + 'ids': crypto_symbol, |
| 10 | + 'vs_currencies': 'usd', |
| 11 | + 'include_24hr_change': 'true' |
| 12 | + }, headers=headers) |
| 13 | + |
| 14 | + if response.status_code == 200: |
| 15 | + data = response.json() |
| 16 | + price = data[crypto_symbol]['usd'] |
| 17 | + change_percentage = data[crypto_symbol]['usd_24h_change'] |
| 18 | + return price, change_percentage |
| 19 | + else: |
| 20 | + return None |
| 21 | + |
| 22 | + |
| 23 | +def get_historical_data(crypto_symbol, days): |
| 24 | + response = requests.get(f"{COINGECKO_API_URL}/coins/{crypto_symbol}/market_chart", params={ |
| 25 | + 'vs_currency': 'usd', |
| 26 | + 'days': days |
| 27 | + }) |
| 28 | + if response.status_code == 200: |
| 29 | + return response.json()['prices'] # Returns price data over the days |
| 30 | + else: |
| 31 | + return None |
| 32 | + |
| 33 | + |
| 34 | +def main(): |
| 35 | + print("You may refer to https://api.coingecko.com/api/v3/coins/list for the coins list") |
| 36 | + crypto = input("Enter cryptocurrency symbol (e.g. bitcoin, ethereum): ").lower() |
| 37 | + price, change = get_crypto_price(crypto) |
| 38 | + |
| 39 | + if price: |
| 40 | + print(f"Current price of {crypto}: ${price}") |
| 41 | + print(f"24-hour change: {change:.2f}%") |
| 42 | + |
| 43 | + # Get historical data |
| 44 | + days = input("Enter the number of days for historical data: ") |
| 45 | + historical_data = get_historical_data(crypto, days) |
| 46 | + if historical_data: |
| 47 | + print(historical_data) |
| 48 | + print("Historical data retrieved successfully.") |
| 49 | + # You may process historical_data further (e.g., plot or analyze it) |
| 50 | + else: |
| 51 | + print("Invalid cryptocurrency symbol or failed API request.") |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + main() |
0 commit comments