Currency conversion tables are a common sight in airports and other places of international transit. In most cases, a long row of records containing two currencies and their conversion rate/exchange rate is on display. This format is difficult to follow, as well as feels monotonous. So how about giving a facelift to currency conversion visualization.
In this blog post, we show you how to generate a currency conversion chart in Python using the Labstack Currency API. This chart is in SVG format that makes it easy to present on the web and mobile apps and can also be projected on digital signage.
Your First Steps With Labstack Currency API
The Labstack Currency API is a simple, no-frills currency conversion API. It supports over 150 currencies, is fast and accurate. Let’s take a detailed look at the API capabilities, and then we show you how to build a currency conversion chart with it.
1. Signup for RapidAPI Account
To begin using the Labstack Currency API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.
2. Navigate to the Labstack Currency API Console
You can search for “Labstack Currency API” on the RapidAPI homepage, or access the API Console directly.
3. Subscribe to Labstack Currency API
Once you are in the API console, click on the “Pricing” tab to take a look at the subscription tiers available for Labstack Currency API.
Labstack Currency API has a freemium subscription model. Under the “Basic” plan, you get 400 API calls per month for free. Subscribe to this plan, and you are all set to explore the API further.
4. Test the API Endpoints
Head back to the “Endpoints” tab on API console and take a look at the supported endpoints on the left side panel.
The “GET Convert” endpoint is used for currency conversion between two currencies, identified by their three-character code.
The “GET List” endpoint returns all the currencies supported by the API.
Select the “GET Convert” endpoint and take a look at the default values of the required parameters.
This significance of these parameters is self-explanatory. The ‘to’ and ‘from’ parameters contain the currency code of the currencies between which the conversion is performed. In this case, the API converts from USD (US Dollars) to INR (Indian Rupee)
The ‘amount’ parameter contains the currency value. However, this does not seem to take any effect in the API response as of this writing.
Trigger the API request, and you should see an API response in the following format, containing the time of API invocation and the converted amount in the ‘to’ currency.
The actual converted amount varies depending on the exchange rate at the time of API invocation.
Make a note of the API response format. You are now ready to leverage it to build a currency conversion chart.
How to use the Currency API with Python
Build a Custom Currency Conversion Chart with Labstack Currency API
If you have ever wondered if currency conversion tables can be presented better, then here is an idea. Instead of a row-wise arrangement, if the currency conversion rates are presented in a two-dimensional matrix view, will it be more readable? We don’t know for sure, but we can give it a shot.
Using the SVG markup, it is easy to build a chart with the common graphic elements such as lines, shapes, and text to assemble a currency chart like this.
We will explain how to read this chart. But for now let’s move ahead to build a sample Python program to generate this SVG chart with the help of Labstack Currency API.
Prerequisites
Before writing the code, ensure that the following requirements are fulfilled for the development of the program code.
- Python 3 environment – You must have the Python3 (3.6 or later) installed on the computer where this program will be executed.
- drawSvg Library – This program depends on the drawSvg Python library, which is an SVG generation library. Follow the installation instructions in the repository link to install the library within your Python 3 environment.
Open your favorite code editor and follow along the steps below to build the program step by step.
Step 1: Library Imports and Global Declaration
We start the program with library imports. This program relies on three libraries, requests, drawSvg , and json. You already are aware of the drawSvg. The requests library is used for making API calls, and the json library is used for converting the API response in a string to a Python dictionary format. These are part of the Python 3 runtime environment. Hence you do not have to install them.
import requests import drawSvg as draw import json
Subsequently, define a few global variables as follows.
RAPIDAPI_HOST = "currency13.p.rapidapi.com" RAPIDAPI_KEY = "<YOUR_RAPIDAPI_KEY>" CELL_SIZE=100 LABEL_SPACING = 50 curr_list = ["USD","EUR","GBP","INR","AED"]
The RAPIDAPI_HOST and RAPIDAPI_KEY are global constants that contain the API URL and the API key. You have to replace the placeholder <YOUR_RAPIDAPI_KEY> with your RapidAPI subscription key.
The CELL_SIZE and LABEL_SPACING are two other constants that are used for the SVG rendering. You will get to know more about these subsequently.
The curr_list is a list that contains the currency code of five currencies that are displayed in the generated SVG chart.
Step 2: Define a Function For Drawing the Grid
As you saw in the chart, the data is presented in a square grid format, with cells having diagonal partitions. You have to define a function to create this grid structure, based on the number of currencies.
def drawSquareGrid(num): #Initialize the SVG grid grid_size = LABEL_SPACING + (CELL_SIZE * num) inner_grid_size = CELL_SIZE * num d = draw.Drawing(grid_size, grid_size, displayInline=True) d.append(draw.Rectangle(0,0,grid_size,grid_size, fill='white')) d.append(draw.Rectangle(LABEL_SPACING,0,inner_grid_size,inner_grid_size, fill='#f5f5f5')) #Draw Hor and Vertical Grid Lines for lin_no in range(1,num): d.append(draw.Line(LABEL_SPACING, lin_no * CELL_SIZE, grid_size, lin_no * CELL_SIZE,stroke='#dedede', stroke_width=1, fill='none')) d.append(draw.Line((lin_no * CELL_SIZE) + LABEL_SPACING, 0, (lin_no * CELL_SIZE) + LABEL_SPACING, inner_grid_size,stroke='#dedede', stroke_width=1, fill='none')) #Draw Inner Cells for hor_cell in range(0,num): for ver_cell in range(0,num): if(hor_cell + ver_cell) != (num - 1): d.append(draw.Line(LABEL_SPACING + ( CELL_SIZE* hor_cell), CELL_SIZE + (CELL_SIZE * ver_cell), LABEL_SPACING + CELL_SIZE + ( CELL_SIZE* hor_cell), ( CELL_SIZE* ver_cell),stroke='#cccccc', stroke_width=0.5, fill='none')) else: d.append(draw.Rectangle(LABEL_SPACING + (CELL_SIZE * hor_cell) , (CELL_SIZE * ver_cell) ,CELL_SIZE,CELL_SIZE, fill='red', fill_opacity=0.2)) #Draw Currency Labels for curr_pos in range(0, len(curr_list)): curr_x_pos = curr_pos + 1 curr_y_pos = len(curr_list) - curr_pos d.append(draw.Text(curr_list[curr_pos], 20, LABEL_SPACING + (curr_x_pos * CELL_SIZE ) - 50, inner_grid_size + 10) ) d.append(draw.Text(curr_list[curr_pos], 20, 5, (curr_y_pos * CELL_SIZE) - 90)) return d
This function drawSquareGrid( ) does many things. We can split it into four sub-steps.
First, it creates an instance of drawSvg Drawing object, with a background rectangle and an inner rectangle.
At this point, the rendered SVG would look like this.
In the second step, you add the horizontal and vertical lines to make square cells. LABEL_SPACING represents the left and top separation between the background and inner rectangle. The cell width is represented by CELL_SIZE, which is set to 100.
In the third step, you draw the diagonal lines inside the cells to split them and add a light red background to the invalid cells that match the same currency.
Finally, you add the currency text labels by locale on the top and left side of the grid.
Step 3: Define Another Function For Adding Currency Rates
As you can see, this chart uses a diagonal split to show the respective conversion rates between the two currencies, that match up on the top horizontal line and the left vertical line.
So you need a function to add the conversion rates to the left and right side of each cell so that the viewer can match up the currency conversion values between the currency in the top and left.
To achieve this, you define another function like this.
def addRate(cell_X, cell_Y, pos, rate, d): ref_X_point = LABEL_SPACING + ( (cell_X - 1) * CELL_SIZE) ref_Y_point = (len(curr_list) - cell_Y) * CELL_SIZE if(pos == "left"): d.append(draw.Text(rate, 15, ref_X_point + 20, ref_Y_point + 10)) else: d.append(draw.Text(rate, 15, ref_X_point + 40, ref_Y_point + 80))
This function adds the currency conversion rate value to either the left or right of a cell, identified by the row and column number. The row and column numbering start from the top left corner.
Step 4: Define Main Logic to Call the API and Populate the Cells
Now all the groundwork for chart display is complete. The only thing left is the addition of actual currency conversion rate figures.
So you define the main loop of the program to iterate over the currencies in curr_list to get the conversion rates and populate the chart using the addRate( ) function.
if __name__ == "__main__": headers = { 'x-rapidapi-host': RAPIDAPI_HOST, 'x-rapidapi-key': RAPIDAPI_KEY } chart = drawSquareGrid(len(curr_list)) for currency_from in range(0, len(curr_list)): for currency_to in range(0, len(curr_list)): if(currency_from < currency_to): url = "https://currency13.p.rapidapi.com/convert/1/" + curr_list[currency_from] + "/" + curr_list[currency_to] response = requests.request("GET", url, headers=headers) currency_value = str(round(json.loads(response.text)["amount"],3)) addRate(currency_to + 1, currency_from + 1, "left", currency_value, chart ) addRate(currency_from + 1, currency_to + 1, "right", currency_value, chart ) url = "https://currency13.p.rapidapi.com/convert/1/" + curr_list[currency_to] + "/" + curr_list[currency_from] response = requests.request("GET", url, headers=headers) currency_value = str(round(json.loads(response.text)["amount"],3)) addRate(currency_to + 1, currency_from + 1, "right", currency_value, chart ) addRate(currency_from + 1, currency_to + 1, "left", currency_value, chart ) chart.saveSvg('currencyChart.svg')
Since this is a two-dimensional chart, you run two iterations to retrieve the conversion rates between both the currencies and add the values to the two halves of the cells.
Finally the Drawing object is saved as an SVG file with the name ‘currencyChart.svg’.
Step 5: Run the Program and Generate Chart
Save the code as a python file and run it. You may get an error that reads something like “Failed to import CairoSVG”. CairoSVG is an add-on to drawSvg library for generating PNG files out of the SVG. Since we are not using PNG here, you can ignore it. The program will run and generate the ‘currencyChart.svg’ SVG file, and you can open it in any browser. This file is located in the same path as the python program file.
Presumably, this chart is easier to follow as it is easy to tally and cross-reference currency conversion rates if the number of currencies is large.
You can try this out by adding more currency codes to the curr_list variable and running the program again.
Your Turn to Spruce Up the Currency Chart
That’s it for the currency conversion chart. If you are building any visualization around currency conversion, then you can improvise this idea (such as building a time series chart or looking at historical rates).
You can further build upon this idea to spruce up the chart with more data points. The Labstack Currency API does not provide much information about history and trends about the currency rates. However, you can check out other Financial APIs hosted in RapidAPI to extract more information about currency rates and add to the chart.
If you have any queries, then please put your comments below. We will be back soon with yet another interesting use case with the RapidAPI hosted APIs.
Leave a Reply