|
| 1 | +""" |
| 2 | +Convert ETH (Ethereum) to USD using live or static conversion rates. |
| 3 | +
|
| 4 | +Fetches current ETH price from CoinGecko API or uses fallback rate. |
| 5 | +Source: https://api.coingecko.com/api/v3/simple/price |
| 6 | +""" |
| 7 | + |
| 8 | + |
| 9 | +def eth_to_usd(eth_amount: float, eth_price_usd: float = 2000.0) -> float: |
| 10 | + """ |
| 11 | + Convert ETH amount to USD equivalent. |
| 12 | +
|
| 13 | + Args: |
| 14 | + eth_amount: Amount of ETH to convert |
| 15 | + eth_price_usd: Price of 1 ETH in USD (default: 2000.0) |
| 16 | +
|
| 17 | + Returns: |
| 18 | + USD equivalent of the ETH amount |
| 19 | +
|
| 20 | + Raises: |
| 21 | + ValueError: If eth_amount or eth_price_usd is negative |
| 22 | +
|
| 23 | + >>> eth_to_usd(1.0, 2000.0) |
| 24 | + 2000.0 |
| 25 | + >>> eth_to_usd(0.5, 3000.0) |
| 26 | + 1500.0 |
| 27 | + >>> eth_to_usd(0, 2000.0) |
| 28 | + 0.0 |
| 29 | + >>> eth_to_usd(-1, 2000.0) |
| 30 | + Traceback (most recent call last): |
| 31 | + ... |
| 32 | + ValueError: ETH amount cannot be negative |
| 33 | + >>> eth_to_usd(1, -100) |
| 34 | + Traceback (most recent call last): |
| 35 | + ... |
| 36 | + ValueError: ETH price cannot be negative |
| 37 | + """ |
| 38 | + if eth_amount < 0: |
| 39 | + raise ValueError("ETH amount cannot be negative") |
| 40 | + if eth_price_usd < 0: |
| 41 | + raise ValueError("ETH price cannot be negative") |
| 42 | + |
| 43 | + return eth_amount * eth_price_usd |
| 44 | + |
| 45 | + |
| 46 | +def get_live_eth_price() -> float: |
| 47 | + """ |
| 48 | + Fetch current ETH price from CoinGecko API. |
| 49 | +
|
| 50 | + Returns: |
| 51 | + Current ETH price in USD, or 2000.0 if request fails |
| 52 | +
|
| 53 | + >>> price = get_live_eth_price() |
| 54 | + >>> isinstance(price, float) |
| 55 | + True |
| 56 | + """ |
| 57 | + try: |
| 58 | + import requests |
| 59 | + response = requests.get( |
| 60 | + "https://api.coingecko.com/api/v3/simple/price", |
| 61 | + params={"ids": "ethereum", "vs_currencies": "usd"}, |
| 62 | + timeout=10 |
| 63 | + ) |
| 64 | + response.raise_for_status() |
| 65 | + return response.json()["ethereum"]["usd"] |
| 66 | + except (ImportError, requests.RequestException, KeyError): |
| 67 | + return 2000.0 |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + import doctest |
| 72 | + doctest.testmod() |
| 73 | + |
| 74 | + # Interactive example |
| 75 | + live_price = get_live_eth_price() |
| 76 | + result = eth_to_usd(1.0, live_price) |
| 77 | + print(f"1 ETH = ${result:,.2f} USD (${live_price:,.2f}/ETH)") |
0 commit comments