Skip to content

Commit

Permalink
add currency converter tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
x4nth055 committed Feb 2, 2022
1 parent c2671e4 commit 1e755d2
Show file tree
Hide file tree
Showing 8 changed files with 191 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
- [How to Extract YouTube Comments in Python](https://www.thepythoncode.com/article/extract-youtube-comments-in-python). ([code](web-scraping/youtube-comments-extractor))
- [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))
- [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))
- [How to Make a Currency Converter in Python](https://www.thepythoncode.com/article/make-a-currency-converter-in-python). ([code](web-scraping/currency-converter))

- ### [Python Standard Library](https://www.thepythoncode.com/topic/python-standard-library)
- [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/))
Expand Down
12 changes: 12 additions & 0 deletions web-scraping/currency-converter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# [How to Make a Currency Converter in Python](https://www.thepythoncode.com/article/make-a-currency-converter-in-python)
To run the scripts:
- `pip3 install -r requirements.txt`
- Here is an example: To convert 1000 EUR to USD by scraping Yahoo Finance:
```
$ python currency_converter_yahoofin.py EUR USD 1000
```
Output:
```
Last updated datetime: 2022-02-02 12:37:39
1000.0 EUR = 1132.6310634613037 USD
```
33 changes: 33 additions & 0 deletions web-scraping/currency-converter/currency_converter_erapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import requests
from dateutil.parser import parse

def get_all_exchange_rates_erapi(src):
url = f"https://open.er-api.com/v6/latest/{src}"
# request the open ExchangeRate API and convert to Python dict using .json()
data = requests.get(url).json()
if data["result"] == "success":
# request successful
# get the last updated datetime
last_updated_datetime = parse(data["time_last_update_utc"])
# get the exchange rates
exchange_rates = data["rates"]
return last_updated_datetime, exchange_rates



def convert_currency_erapi(src, dst, amount):
# get all the exchange rates
last_updated_datetime, exchange_rates = get_all_exchange_rates_erapi(src)
# convert by simply getting the target currency exchange rate and multiply by the amount
return last_updated_datetime, exchange_rates[dst] * amount


if __name__ == "__main__":
import sys
source_currency = sys.argv[1]
destination_currency = sys.argv[2]
amount = float(sys.argv[3])
last_updated_datetime, exchange_rate = convert_currency_erapi(source_currency, destination_currency, amount)
print("Last updated datetime:", last_updated_datetime)
print(f"{amount} {source_currency} = {exchange_rate} {destination_currency}")

47 changes: 47 additions & 0 deletions web-scraping/currency-converter/currency_converter_fixerapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import requests
from datetime import date, datetime

API_KEY = "8c3dce10dc5fdb6ec1f555a1504b1373"
# API_KEY = "<YOUR_API_KEY_HERE>"


def convert_currency_fixerapi_free(src, dst, amount):
"""converts `amount` from the `src` currency to `dst` using the free account"""
url = f"http://data.fixer.io/api/latest?access_key={API_KEY}&symbols={src},{dst}&format=1"
data = requests.get(url).json()
if data["success"]:
# request successful
rates = data["rates"]
# since we have the rate for our currency to src and dst, we can get exchange rate between both
# using below calculation
exchange_rate = 1 / rates[src] * rates[dst]
last_updated_datetime = datetime.fromtimestamp(data["timestamp"])
return last_updated_datetime, exchange_rate * amount


def convert_currency_fixerapi(src, dst, amount):
"""converts `amount` from the `src` currency to `dst`, requires upgraded account"""
url = f"https://data.fixer.io/api/convert?access_key={API_KEY}&from={src}&to={dst}&amount={amount}"
data = requests.get(url).json()
if data["success"]:
# request successful
# get the latest datetime
last_updated_datetime = datetime.fromtimestamp(data["info"]["timestamp"])
# get the result based on the latest price
result = data["result"]
return last_updated_datetime, result



if __name__ == "__main__":
import sys
source_currency = sys.argv[1]
destination_currency = sys.argv[2]
amount = float(sys.argv[3])
# free account
last_updated_datetime, exchange_rate = convert_currency_fixerapi_free(source_currency, destination_currency, amount)
# upgraded account, uncomment if you have one
# last_updated_datetime, exchange_rate = convert_currency_fixerapi(source_currency, destination_currency, amount)
print("Last updated datetime:", last_updated_datetime)
print(f"{amount} {source_currency} = {exchange_rate} {destination_currency}")

35 changes: 35 additions & 0 deletions web-scraping/currency-converter/currency_converter_xe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import requests
from bs4 import BeautifulSoup as bs
import re
from dateutil.parser import parse

def convert_currency_xe(src, dst, amount):
def get_digits(text):
"""Returns the digits and dots only from an input `text` as a float
Args:
text (str): Target text to parse
"""
new_text = ""
for c in text:
if c.isdigit() or c == ".":
new_text += c
return float(new_text)

url = f"https://www.xe.com/currencyconverter/convert/?Amount={amount}&From={src}&To={dst}"
content = requests.get(url).content
soup = bs(content, "html.parser")
exchange_rate_html = soup.find_all("p")[2]
# get the last updated datetime
last_updated_datetime = parse(re.search(r"Last updated (.+)", exchange_rate_html.parent.parent.find_all("div")[-2].text).group()[12:])
return last_updated_datetime, get_digits(exchange_rate_html.text)


if __name__ == "__main__":
import sys
source_currency = sys.argv[1]
destination_currency = sys.argv[2]
amount = float(sys.argv[3])
last_updated_datetime, exchange_rate = convert_currency_xe(source_currency, destination_currency, amount)
print("Last updated datetime:", last_updated_datetime)
print(f"{amount} {source_currency} = {exchange_rate} {destination_currency}")

35 changes: 35 additions & 0 deletions web-scraping/currency-converter/currency_converter_xrates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import requests
from bs4 import BeautifulSoup as bs
from dateutil.parser import parse
from pprint import pprint


def get_exchange_list_xrates(currency, amount=1):
# make the request to x-rates.com to get current exchange rates for common currencies
content = requests.get(f"https://www.x-rates.com/table/?from={currency}&amount={amount}").content
# initialize beautifulsoup
soup = bs(content, "html.parser")
# get the last updated time
price_datetime = parse(soup.find_all("span", attrs={"class": "ratesTimestamp"})[1].text)
# get the exchange rates tables
exchange_tables = soup.find_all("table")
exchange_rates = {}
for exchange_table in exchange_tables:
for tr in exchange_table.find_all("tr"):
# for each row in the table
tds = tr.find_all("td")
if tds:
currency = tds[0].text
# get the exchange rate
exchange_rate = float(tds[1].text)
exchange_rates[currency] = exchange_rate
return price_datetime, exchange_rates


if __name__ == "__main__":
import sys
source_currency = sys.argv[1]
amount = float(sys.argv[2])
price_datetime, exchange_rates = get_exchange_list_xrates(source_currency, amount)
print("Last updated:", price_datetime)
pprint(exchange_rates)
24 changes: 24 additions & 0 deletions web-scraping/currency-converter/currency_converter_yahoofin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import yahoo_fin.stock_info as si
from datetime import datetime, timedelta

def convert_currency_yahoofin(src, dst, amount):
# construct the currency pair symbol
symbol = f"{src}{dst}=X"
# extract minute data of the recent 2 days
latest_data = si.get_data(symbol, interval="1m", start_date=datetime.now() - timedelta(days=2))
# get the latest datetime
last_updated_datetime = latest_data.index[-1].to_pydatetime()
# get the latest price
latest_price = latest_data.iloc[-1].close
# return the latest datetime with the converted amount
return last_updated_datetime, latest_price * amount


if __name__ == "__main__":
import sys
source_currency = sys.argv[1]
destination_currency = sys.argv[2]
amount = float(sys.argv[3])
last_updated_datetime, exchange_rate = convert_currency_yahoofin(source_currency, destination_currency, amount)
print("Last updated datetime:", last_updated_datetime)
print(f"{amount} {source_currency} = {exchange_rate} {destination_currency}")
4 changes: 4 additions & 0 deletions web-scraping/currency-converter/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
python-dateutil
requests
bs4
yahoo_fin

0 comments on commit 1e755d2

Please sign in to comment.