diff --git a/DIRECTORY.md b/DIRECTORY.md index eaa48b893c66..0e3dd66a6bc6 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -219,9 +219,11 @@ * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) + * [Int To Negative Binary Base](conversions/int_to_negative_binary_base.py) * [Ipv4 Conversion](conversions/ipv4_conversion.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) + * [Negative Binary Base To Int](conversions/negative_binary_base_to_int.py) * [Octal To Binary](conversions/octal_to_binary.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Octal To Hexadecimal](conversions/octal_to_hexadecimal.py) @@ -1570,6 +1572,8 @@ * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) + * [Crypto Price](web_programming/crypto_price.py) + * [Crypto Price Tracker](web_programming/crypto_price_tracker.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) diff --git a/web_programming/crypto_price_tracker.py b/web_programming/crypto_price_tracker.py new file mode 100644 index 000000000000..514f352b5e6c --- /dev/null +++ b/web_programming/crypto_price_tracker.py @@ -0,0 +1,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') = }")