Skip to content

Commit 75a887c

Browse files
committed
Implemented ETH to USD script
1 parent 7530a41 commit 75a887c

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

conversions/crypto_price.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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)")

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ numpy
99
opencv-python
1010
pandas
1111
pillow
12+
requests
1213
rich
1314
scikit-learn
1415
sphinx-pyproject

0 commit comments

Comments
 (0)