Skip to content

Commit 0afa947

Browse files
Add crypto_price_tracker.py to fetch live crypto prices
1 parent e2a78d4 commit 0afa947

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
Fetch the current price of a cryptocurrency in USD using CoinGecko API.
3+
"""
4+
5+
import httpx
6+
7+
8+
def crypto_price(coin: str = "bitcoin") -> float:
9+
"""
10+
Return the current price of a cryptocurrency in USD using CoinGecko API.
11+
12+
>>> isinstance(crypto_price("bitcoin"), float)
13+
True
14+
>>> isinstance(crypto_price("ethereum"), float)
15+
True
16+
"""
17+
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd"
18+
try:
19+
response = httpx.get(url, timeout=10)
20+
response.raise_for_status()
21+
return float(response.json().get(coin, {}).get("usd", 0.0))
22+
except (httpx.RequestError, ValueError, KeyError):
23+
return 0.0
24+
25+
26+
if __name__ == "__main__":
27+
print(crypto_price("bitcoin"))

0 commit comments

Comments
 (0)