Skip to content

Commit 8472e26

Browse files
authored
Merge pull request #47 from aafaris/feature/crypto-tracker
add real-time crypto price tracker script
2 parents 90a36fe + a80aa96 commit 8472e26

File tree

4 files changed

+127
-0
lines changed

4 files changed

+127
-0
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+
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
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()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
requests==2.32.3
2+
matplotlib==3.9.2
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
python-3.9.20

0 commit comments

Comments
 (0)