Last modified: Jan 10, 2023 By Alexander Williams

Currency conversion in python

In this post, I'll show you how to work with currency in python by using forex-python library.

1. forex-python installation

To install forex-python via pip, you need to follow this command.

pip install forex-python

3. list of USD exchange rates

In this example, we'll get a list of USD exchange rates.


from forex_python.converter import CurrencyRates

c = CurrencyRates()
c.get_rates('USD')

output:

{u'IDR': 13625.0, u'BGN': 1.7433, u'ILS': 3.8794, u'GBP': 0.68641, u'DKK': 6.6289, u'CAD': 1.3106, u'JPY': 110.36, u'HUF': 282.36, u'RON': 4.0162, u'MYR': 4.081, u'SEK': 8.3419, u'SGD': 1.3815, u'HKD': 7.7673, u'AUD': 1.3833, u'CHF': 0.99144, u'KRW': 1187.3, u'CNY': 6.5475, u'TRY': 2.9839, u'HRK': 6.6731, u'NZD': 1.4777, u'THB': 35.73, u'EUR': 0.89135, u'NOK': 8.3212, u'RUB': 66.774, u'INR': 67.473, u'MXN': 18.41, u'CZK': 24.089, u'BRL': 3.5473, u'PLN': 3.94, u'PHP': 46.775, u'ZAR': 15.747}

4. Convert USD to EURO

Now, we'll convert USD to EURO.


from forex_python.converter import CurrencyRates 

c = CurrencyRates()
Currency = c.get_rate('USD', 'EUR')  #convert USD to EURO
print(Currency)

Output

0.9048136084

To print the specified number of decimals, we need to use the road() built-function.


print(round(Currency, 3))

Output

0.905

5. Working with BITCOIN

The Forex-python library also supports bitcoin Currency.
Let's get bitcoin's price in USD.


from forex_python.bitcoin import BtcConverter
b = BtcConverter() # force_decimal=True to get Decimal rates
b.get_latest_price('USD')


output

533.913

as you can see, 1 BITCOIN = 533.913$

for more options, please visit forex-python