Problem 7.1
Exchange Rate
Write a command-line program to find the currency exchange rate using exchangerate.host API (Please look at the "Convert currency" section of the API).
The program should take the currency symbol and a date as arguments and print the exchange rate of that symbol against USD on the specified date.
$ python exchange_rate.py INR 2021-01-01
73.092243
The base currency can be is changed from USD to another currency using optional flag -b
or --base
.
$ python exchange_rate.py -b EUR INR 2021-01-01
88.995799
The program should provide --help
option to display the available options and usage.
Hint: Use argparse
module to parse the arguments.
Solution
import argparse
import requests
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("-b", "--base", help="base currency", default="USD")
p.add_argument("target_currency", help="target currency")
p.add_argument("date", help="date")
return p.parse_args()
def exchange_rate(base, target, date):
params = {
"from": base,
"to": target,
"date": date
}
url = 'https://api.exchangerate.host/convert'
response = requests.get(url, params=params)
data = response.json()
return data['result']
def main():
args = parse_args()
d = exchange_rate(args.base, args.target_currency, args.date)
print(d)
if __name__ == "__main__":
main()