Skip to content

Commit 1e755d2

Browse files
committed
add currency converter tutorial
1 parent c2671e4 commit 1e755d2

File tree

8 files changed

+191
-0
lines changed

8 files changed

+191
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
115115
-[How to Extract YouTube Comments in Python](https://www.thepythoncode.com/article/extract-youtube-comments-in-python). ([code](web-scraping/youtube-comments-extractor))
116116
-[Automated Browser Testing with Edge and Selenium in Python](https://www.thepythoncode.com/article/automated-browser-testing-with-edge-and-selenium-in-python). ([code](web-scraping/selenium-edge-browser))
117117
-[How to Automate Login using Selenium in Python](https://www.thepythoncode.com/article/automate-login-to-websites-using-selenium-in-python). ([code](web-scraping/automate-login))
118+
-[How to Make a Currency Converter in Python](https://www.thepythoncode.com/article/make-a-currency-converter-in-python). ([code](web-scraping/currency-converter))
118119

119120
-### [Python Standard Library](https://www.thepythoncode.com/topic/python-standard-library)
120121
-[How to Transfer Files in the Network using Sockets in Python](https://www.thepythoncode.com/article/send-receive-files-using-sockets-python). ([code](general/transfer-files/))
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# [How to Make a Currency Converter in Python](https://www.thepythoncode.com/article/make-a-currency-converter-in-python)
2+
To run the scripts:
3+
-`pip3 install -r requirements.txt`
4+
- Here is an example: To convert 1000 EUR to USD by scraping Yahoo Finance:
5+
```
6+
$ python currency_converter_yahoofin.py EUR USD 1000
7+
```
8+
Output:
9+
```
10+
Last updated datetime: 2022-02-02 12:37:39
11+
1000.0 EUR = 1132.6310634613037 USD
12+
```
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
importrequests
2+
fromdateutil.parserimportparse
3+
4+
defget_all_exchange_rates_erapi(src):
5+
url=f"https://open.er-api.com/v6/latest/{src}"
6+
# request the open ExchangeRate API and convert to Python dict using .json()
7+
data=requests.get(url).json()
8+
ifdata["result"] =="success":
9+
# request successful
10+
# get the last updated datetime
11+
last_updated_datetime=parse(data["time_last_update_utc"])
12+
# get the exchange rates
13+
exchange_rates=data["rates"]
14+
returnlast_updated_datetime, exchange_rates
15+
16+
17+
18+
defconvert_currency_erapi(src, dst, amount):
19+
# get all the exchange rates
20+
last_updated_datetime, exchange_rates=get_all_exchange_rates_erapi(src)
21+
# convert by simply getting the target currency exchange rate and multiply by the amount
22+
returnlast_updated_datetime, exchange_rates[dst] *amount
23+
24+
25+
if__name__=="__main__":
26+
importsys
27+
source_currency=sys.argv[1]
28+
destination_currency=sys.argv[2]
29+
amount=float(sys.argv[3])
30+
last_updated_datetime, exchange_rate=convert_currency_erapi(source_currency, destination_currency, amount)
31+
print("Last updated datetime:", last_updated_datetime)
32+
print(f"{amount}{source_currency} = {exchange_rate}{destination_currency}")
33+
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
importrequests
2+
fromdatetimeimportdate, datetime
3+
4+
API_KEY="8c3dce10dc5fdb6ec1f555a1504b1373"
5+
# API_KEY = "<YOUR_API_KEY_HERE>"
6+
7+
8+
defconvert_currency_fixerapi_free(src, dst, amount):
9+
"""converts `amount` from the `src` currency to `dst` using the free account"""
10+
url=f"http://data.fixer.io/api/latest?access_key={API_KEY}&symbols={src},{dst}&format=1"
11+
data=requests.get(url).json()
12+
ifdata["success"]:
13+
# request successful
14+
rates=data["rates"]
15+
# since we have the rate for our currency to src and dst, we can get exchange rate between both
16+
# using below calculation
17+
exchange_rate=1/rates[src] *rates[dst]
18+
last_updated_datetime=datetime.fromtimestamp(data["timestamp"])
19+
returnlast_updated_datetime, exchange_rate*amount
20+
21+
22+
defconvert_currency_fixerapi(src, dst, amount):
23+
"""converts `amount` from the `src` currency to `dst`, requires upgraded account"""
24+
url=f"https://data.fixer.io/api/convert?access_key={API_KEY}&from={src}&to={dst}&amount={amount}"
25+
data=requests.get(url).json()
26+
ifdata["success"]:
27+
# request successful
28+
# get the latest datetime
29+
last_updated_datetime=datetime.fromtimestamp(data["info"]["timestamp"])
30+
# get the result based on the latest price
31+
result=data["result"]
32+
returnlast_updated_datetime, result
33+
34+
35+
36+
if__name__=="__main__":
37+
importsys
38+
source_currency=sys.argv[1]
39+
destination_currency=sys.argv[2]
40+
amount=float(sys.argv[3])
41+
# free account
42+
last_updated_datetime, exchange_rate=convert_currency_fixerapi_free(source_currency, destination_currency, amount)
43+
# upgraded account, uncomment if you have one
44+
# last_updated_datetime, exchange_rate = convert_currency_fixerapi(source_currency, destination_currency, amount)
45+
print("Last updated datetime:", last_updated_datetime)
46+
print(f"{amount}{source_currency} = {exchange_rate}{destination_currency}")
47+
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
importrequests
2+
frombs4importBeautifulSoupasbs
3+
importre
4+
fromdateutil.parserimportparse
5+
6+
defconvert_currency_xe(src, dst, amount):
7+
defget_digits(text):
8+
"""Returns the digits and dots only from an input `text` as a float
9+
Args:
10+
text (str): Target text to parse
11+
"""
12+
new_text=""
13+
forcintext:
14+
ifc.isdigit() orc==".":
15+
new_text+=c
16+
returnfloat(new_text)
17+
18+
url=f"https://www.xe.com/currencyconverter/convert/?Amount={amount}&From={src}&To={dst}"
19+
content=requests.get(url).content
20+
soup=bs(content, "html.parser")
21+
exchange_rate_html=soup.find_all("p")[2]
22+
# get the last updated datetime
23+
last_updated_datetime=parse(re.search(r"Last updated (.+)", exchange_rate_html.parent.parent.find_all("div")[-2].text).group()[12:])
24+
returnlast_updated_datetime, get_digits(exchange_rate_html.text)
25+
26+
27+
if__name__=="__main__":
28+
importsys
29+
source_currency=sys.argv[1]
30+
destination_currency=sys.argv[2]
31+
amount=float(sys.argv[3])
32+
last_updated_datetime, exchange_rate=convert_currency_xe(source_currency, destination_currency, amount)
33+
print("Last updated datetime:", last_updated_datetime)
34+
print(f"{amount}{source_currency} = {exchange_rate}{destination_currency}")
35+
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
importrequests
2+
frombs4importBeautifulSoupasbs
3+
fromdateutil.parserimportparse
4+
frompprintimportpprint
5+
6+
7+
defget_exchange_list_xrates(currency, amount=1):
8+
# make the request to x-rates.com to get current exchange rates for common currencies
9+
content=requests.get(f"https://www.x-rates.com/table/?from={currency}&amount={amount}").content
10+
# initialize beautifulsoup
11+
soup=bs(content, "html.parser")
12+
# get the last updated time
13+
price_datetime=parse(soup.find_all("span", attrs={"class": "ratesTimestamp"})[1].text)
14+
# get the exchange rates tables
15+
exchange_tables=soup.find_all("table")
16+
exchange_rates={}
17+
forexchange_tableinexchange_tables:
18+
fortrinexchange_table.find_all("tr"):
19+
# for each row in the table
20+
tds=tr.find_all("td")
21+
iftds:
22+
currency=tds[0].text
23+
# get the exchange rate
24+
exchange_rate=float(tds[1].text)
25+
exchange_rates[currency] =exchange_rate
26+
returnprice_datetime, exchange_rates
27+
28+
29+
if__name__=="__main__":
30+
importsys
31+
source_currency=sys.argv[1]
32+
amount=float(sys.argv[2])
33+
price_datetime, exchange_rates=get_exchange_list_xrates(source_currency, amount)
34+
print("Last updated:", price_datetime)
35+
pprint(exchange_rates)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
importyahoo_fin.stock_infoassi
2+
fromdatetimeimportdatetime, timedelta
3+
4+
defconvert_currency_yahoofin(src, dst, amount):
5+
# construct the currency pair symbol
6+
symbol=f"{src}{dst}=X"
7+
# extract minute data of the recent 2 days
8+
latest_data=si.get_data(symbol, interval="1m", start_date=datetime.now() -timedelta(days=2))
9+
# get the latest datetime
10+
last_updated_datetime=latest_data.index[-1].to_pydatetime()
11+
# get the latest price
12+
latest_price=latest_data.iloc[-1].close
13+
# return the latest datetime with the converted amount
14+
returnlast_updated_datetime, latest_price*amount
15+
16+
17+
if__name__=="__main__":
18+
importsys
19+
source_currency=sys.argv[1]
20+
destination_currency=sys.argv[2]
21+
amount=float(sys.argv[3])
22+
last_updated_datetime, exchange_rate=convert_currency_yahoofin(source_currency, destination_currency, amount)
23+
print("Last updated datetime:", last_updated_datetime)
24+
print(f"{amount}{source_currency} = {exchange_rate}{destination_currency}")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
python-dateutil
2+
requests
3+
bs4
4+
yahoo_fin

0 commit comments

Comments
(0)