mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 21:45:27 +08:00
* Add crypto_price_tracker.py to fetch live crypto prices * Update crypto_price_tracker to use httpx2 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updating DIRECTORY.md * Correct JSON response handling in price tracker Fix incorrect variable reference for JSON response. --------- Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
34 lines
832 B
Python
34 lines
832 B
Python
"""
|
|
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') = }")
|