forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_crypto_prices.py
More file actions
47 lines (38 loc) · 1.41 KB
/
fetch_crypto_prices.py
File metadata and controls
47 lines (38 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Fetch current cryptocurrency prices using the CoinGecko API.
This script uses the 'httpx' library as per the repository's preference.
"""
from __future__ import annotations
import httpx
def fetch_crypto_price(coin_id: str = "bitcoin") -> dict[str, dict[str, float]]:
"""
Fetch the current price of a cryptocurrency in USD.
:param coin_id: The ID of the coin (e.g., 'bitcoin', 'ethereum', 'dogecoin')
:return: A dictionary containing the price data.
>>> # Note: Actual API call results may vary over time.
>>> isinstance(fetch_crypto_price("bitcoin"), dict)
True
>>> "bitcoin" in fetch_crypto_price("bitcoin")
True
"""
url = (
f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
)
with httpx.Client() as client:
response = client.get(url)
if response.status_code != 200:
raise ValueError(
f"Could not fetch price for {coin_id}. Status code: {response.status_code}"
)
data = response.json()
if not data:
raise ValueError(f"Invalid coin ID: {coin_id}")
return data
if __name__ == "__main__":
try:
coin = "bitcoin"
price_data = fetch_crypto_price(coin)
price = price_data[coin]["usd"]
print(f"The current price of {coin.capitalize()} is ${price:,.2f} USD")
except Exception as e:
print(f"Error: {e}")