forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto_price_tracker.py
More file actions
33 lines (26 loc) · 832 Bytes
/
Copy pathcrypto_price_tracker.py
File metadata and controls
33 lines (26 loc) · 832 Bytes
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
"""
Fetch the current price of a cryptocurrency in USD using CoinGecko API.
"""
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx2",
# ]
# ///
import httpx2
def crypto_price(coin: str = "bitcoin") -> float:
"""
Return the current price of a cryptocurrency in USD using CoinGecko API.
>>> isinstance(crypto_price("bitcoin"), float)
True
>>> isinstance(crypto_price("ethereum"), float)
True
"""
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd"
try:
json_response = httpx2.get(url, timeout=10).raise_for_status().json()
except httpx2.RequestError, ValueError, KeyError:
return 0.0
return float(json_response.get(coin, {}).get("usd", 0.0))
if __name__ == "__main__":
print(f"{crypto_price('bitcoin') = }")