Skip to content

Commit 7f01337

Browse files
committed
update script with input validation, error handling, data visual and readme
1 parent 9cc2f61 commit 7f01337

File tree

3 files changed

+89
-19
lines changed

3 files changed

+89
-19
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Cryptocurrency Price Tracker with CoinGecko API
2+
3+
## Project Overview
4+
5+
The **Real-Time Cryptocurrency Price Tracker** is a Python script that allows users to retrieve real-time cryptocurrency prices, percentage price changes, and historical price data using the CoinGecko public API. The script also offers a simple visualization of historical price trends. Refer to [CoinGecko API](https://docs.coingecko.com/v3.0.1/reference/introduction) and [CoinGecko Coins List](https://api.coingecko.com/api/v3/coins/list) for more information.
6+
7+
## Features
8+
9+
- **Real-Time Price Retrieval**: Input the name of a cryptocurrency (eg. bitcoin) to retrieve its current price in USD
10+
- **24-Hour Price Change**: Displays the 24-hour percentage change in price for the selected cryptocurrency
11+
- **Historical Price Data**: Retrieve historical price data for a specified number of days (eg. 1 day, 7 days, or 30 days) and visualize it in a chart
12+
- **Data Visualization**: Uses matplotlib to generate a line chart displaying the historical price data
13+
14+
15+
## Technologies Used
16+
17+
- **Python**: The core programming language used to build the script
18+
- **CoinGecko API**: A free API used to fetch cryptocurrency prices, percentage changes, and historical data
19+
- **Requests**: A Python library for making HTTP requests to the CoinGecko API
20+
- **Matplotlib**: A Python library used to visualize historical cryptocurrency price data in a line chart format
21+
- **Datetime**: Python datetime module is used to convert and handle timestamps when retrieving historical price data
22+
23+
## Prerequisites
24+
25+
Before running the application, ensure you have the following:
26+
27+
- [Python 3.x](https://www.python.org/downloads/) installed on your system
28+
- `requests` and `matplotlib` libraries are installed. Refer to `requirements.txt` for a specific version
29+

Real-Time Cryptocurrency Price Tracker/main.py

Lines changed: 58 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import requests
2+
import matplotlib.pyplot as plt
3+
import datetime
24

35
COINGECKO_API_URL = "https://api.coingecko.com/api/v3"
46

@@ -13,42 +15,80 @@ def get_crypto_price(crypto_symbol):
1315

1416
if response.status_code == 200:
1517
data = response.json()
16-
price = data[crypto_symbol]['usd']
17-
change_percentage = data[crypto_symbol]['usd_24h_change']
18-
return price, change_percentage
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.")
1924
else:
20-
return None
25+
raise Exception(f"Failed to fetch data: {response.status_code} - {response.reason}")
2126

2227

2328
def get_historical_data(crypto_symbol, days):
2429
response = requests.get(f"{COINGECKO_API_URL}/coins/{crypto_symbol}/market_chart", params={
2530
'vs_currency': 'usd',
2631
'days': days
2732
})
33+
2834
if response.status_code == 200:
29-
return response.json()['prices'] # Returns price data over the days
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}'.")
3040
else:
31-
return None
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()
3257

3358

3459
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)
60+
crypto = input("Enter cryptocurrency symbol (eg. bitcoin, ethereum): ").lower()
3861

39-
if price:
62+
try:
63+
# Get real-time price and 24-hour change
64+
price, change = get_crypto_price(crypto)
4065
print(f"Current price of {crypto}: ${price}")
4166
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.")
4283

43-
# Get historical data
44-
days = input("Enter the number of days for historical data: ")
84+
try:
4585
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.")
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}")
5292

5393

5494
if __name__ == "__main__":
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
requests==2.32.3
1+
requests==2.32.3
2+
matplotlib==3.9.2

0 commit comments

Comments
 (0)