Friday, 22 September 2023

Currency Conversion with ``forex_python.converter``

I wrote a script that converts currencies based on the current exchange rate. It seems to work fine, except when trying to convert EUR to USD, as it never gets the exchange rate correctly. For example, it tells me 1000 EUR are worth 64 USD, whereas the reality would be around 950...The actual exchange rate is 1.06 but forex mistakes it for 0.06

How can I fix it?

Here is my code:

Module 1:

from forex_python.converter import CurrencyRates


def exchange_rate(c1,c2, time):
    c = CurrencyRates()
    return c.get_rate(c1,c2, time)

Module 2:

from currency_rates import exchange_rate
from datetime import datetime


# List of available currencies
list_of_currencies = ["USD", "EUR", "GBP", "ILS", "DKK", "CAD", "IDR", "BGN",
    "JPY", "HUF", "RON", "MYR", "SEK", "SGD", "HKD", "AUD", "CHF", "KRW", "CNY", "TRY", "HRK", "NZD", "THB", "LTL", "NOK", "RUB",
    "INR", "MXN", "CZK", "BRL", "PLN", "PHP", "ZAR"]


# Get user input for currency 1, amount and currency 2
c1 = input(f"""Which currency would you like to convert from?\n {list_of_currencies}\n""")

if c1 not in list_of_currencies:
    print("Invalid answer.")

value_c1 = input("How much of that currency?\n")

c2 = input(f"""Which currency would you like to convert to? \n {list_of_currencies}\n""")

if c2 not in list_of_currencies:
    print("Invalid answer.")


# Calculate result based on exchange rate
# Get current time
now = datetime.now()

rate = exchange_rate(c1,c2, now)

result = float(rate) * float(value_c1)


# Print result
print(f"{value_c1} {c1} are worth {result} {c2}.")

Something needs to be done with the rate itself. But adding 1 when it's below 1 is not a solution as some other exchange rates might be below 1 for real.



from Currency Conversion with ``forex_python.converter``

No comments:

Post a Comment