How I Created a Currency Converter App Using Streamlit

4/5 - (3 votes)

Learning programming allows you to create and design beautiful, exciting, and interactive applications. If you choose Python as your preferred language, many project ideas are waiting for you. From building web applications to creating games, there are projects for everyone.

πŸ’‘ Project Description: In this tutorial, we will use Streamlit to create a simple currency converter app. The purpose is to get real-time currency information, and convert your base currency to a target currency. As an additional feature, we will create a Machine Learning prediction app that aims to predict the rates of any pair of selected currencies.

You can find the follow-up tutorial that predicts currency pairs based on a Random Forest classifier here.

A Few Words Before We Start

This is one of Python projects for beginners. Hence, nothing is required from you other than a basic knowledge of Python.

Creating a currency converter app is a familiar project among Python programmers. It is mostly designed using Tkinter. You can also write the script and get the result in your terminal. We want to use Streamlit, a web framework popular among data scientists, to create the application so that others with little or no knowledge of programming can use it.

And if you are new to Streamlit, this is another way to learn how it works. At the end of this tutorial, you should be able to create a similar app using Streamlit or any Python web framework of your choice.

Getting Your API key

In this tutorial, we will use an API to fetch data from ExchangeRateAPI3. You are required to create an account to get your API key.

Defining the Main Function

To get started, create a folder and an app.py file inside the folder. This will be our main file. Then, write the following code:

import streamlit as st
from currencyConverter import currency_converter


def main():
    st.sidebar.header('Currency Converter and Predictor App')
    op = st.sidebar.selectbox('Select an option', ['convert', 'predict'])
    if op == 'convert':
        currency_converter()
    else:
        pass


if __name__ == '__main__':
    main()

The main() function is a simple one. We start by importing the Streamlit module, and another Python file that we are yet to create. The file will be created in the current folder. We conclude by using the special __name__ variable to call the function. Without calling the function, it will not run on Streamlit local server.

Inside the main() function, we use st.sidebar.selectbox to display two options for our users to select. The two options are the app’s features: convert, convert currency pairs, and predict, predict currency rates. Note that by using sidebar, it will be displayed on the left-hand side of the Streamlit dashboard.

When the first option is selected, the currency_converter() function will be called. We use the pass keyword to prevent the app from throwing errors as we are not going to code the second feature in this tutorial.

The App’s First Feature

The app’s first feature is the convert option. Once it’s selected, a callback function, currency_converter() will be executed. Create another file currencyConverter.py and write the following:

import streamlit as st
import requests



def currency_converter():
    st.header('Currency Converter')
    try:
        key = st.text_input('Enter your API key')
        return get_country_code(key)
    except:
        st.error('Please enter your API Key')

In the above script, we import the requests module, an important tool for fetching data from web pages. In the currency_converter() function, we use the try keyword to run the code provided the API key is entered. If no key is entered, we use the except keyword to raise an error. We then pass the key to another function, get_country_code().

Here is the function:

def get_country_code(key):
    url = f'https://v6.exchangerate-api.com/v6/{key}/codes'
    res = requests.get(url).json()
    country = res['supported_codes']

    code = []
    for i in country:
        code.append(i[0])

    base = st.selectbox('Enter the base currency', code)
    target = st.selectbox('Enter the target currency', code)
    amount = st.number_input('Enter the amount')
    if base != target:
        if st.button('Convert'):
            converter(base, target, amount, key)

We use the requests module to fetch data using the API from ExchangeRateAPI. Then, we convert it to JSON. It contains a lot of information but we return only what we need, the data with the country code.

The country code appears like this:

[['AED', 'UAE Dirham'],
 ['AFN', 'Afghan Afghani'],
 ['ALL', 'Albanian Lek'],
 ['AMD', 'Armenian Dram'],
 ['ANG', 'Netherlands Antillian Guilder'],
 ['AOA', 'Angolan Kwanza'],
…
]

So, we loop over the returned result and append only the country code to the code variable. Once that is taken care of, we add it to the selectbox widgets for users to select.

We make sure that the button will only appear if the base currency is not the same as the target currency. Once the button is clicked, another callback function will be executed.

def converter(base, target, amount, key):
    url = f'https://v6.exchangerate-api.com/v6/{key}/pair/{base}/{target}/{amount}'
    res = requests.get(url).json()
    base_code = res['base_code']
    target_code = res['target_code']
    rate = res['conversion_rate']
    result = res['conversion_result']
    st.text(f'Base_currency: {base_code} \
     \nTarget Currency: {target_code} \
     \nConversion Rate: {rate} \
     \nConversion Amount: {result}')

This function is quite similar to the previous one but with four parameters. It takes in the information passed to it, that is, the base currency, target currency, amount and key and display only the information we need. That’s how I designed the currency converter app.

Conclusion

No doubt, you have benefitted a lot from this beginner project tutorial. You have seen how we use an API to get real-time currency information and display it on Streamlit app.

In the following part two of this project, I will show you how I added a machine learning prediction feature that predicts what the currency rate of a currency pair will be:

πŸ’‘ Recommended: How I Created a Currency Prediction App Using Streamlit

Check out my GitHub page for the full code, and the app already running on Streamlit Cloud.