Have you ever wondered how currencies from different countries are valued over time? Imagine exploring the past and understanding how exchange rates have changed. Well, that’s exactly what we’ll delve into in this blog. We will be building a Historical Exchange Rates Calculator using the power of Python and the Fixer API. Historical exchange rates are crucial in global economics. Hence, affecting everything from travel expenses to international trade.
But how can we uncover the historical values of these rates? That’s where APIs come in – think of them as data sources that hold a treasure trove of information. With Python, we can create a tool that fetches this valuable data from APIs and transforms it into a format that’s easy to comprehend. In this guide, we will journey into exchange rates and APIs.
By the end, you’ll have a functional Historical Exchange Rates Calculator. Don’t worry if you’re new to coding – we’ll break down each step into bite-sized pieces. Hence, making it a breeze for beginner audiences to follow along. So, let’s embark on this exciting adventure!

What Are Historical Exchange Rates?
Historical exchange rates are past values that indicate the relative worth of one currency compared to another at specific points in time. Moreover, these rates provide insights into currency fluctuations, economic trends, and global events that shape financial landscapes. Furthermore, analyzing historical exchange rates allows us to uncover patterns, evaluate market performance, and make informed decisions.
These rates serve as a vital historical record. Hence, allowing us to understand the evolution of currency values. Moreover, they also allow us to understand their impact on various aspects of our interconnected world.
Why Should We Choose Python to Build a Historical Exchange Rates Calculator?
Python is a smart choice for building a Historical Exchange Rates Calculator due to its simplicity and versatility. With Python, you can write fewer lines of code. Hence, making it easier to understand and work with, especially if you’re new to coding. Moreover, its user-friendly nature means you can focus more on the calculator’s logic and less on complex syntax.
Python also offers powerful libraries like `requests` for fetching data from the Fixer API. Moreover, these tools make it a breeze to handle and display data meaningfully.
Another reason to pick Python is its wide community support. Furthermore, if you ever get stuck or need help, you’ll find many online tutorials, forums, and resources. Therefore, they can guide you through any challenges you may encounter.
Furthermore, Python works on platforms like Windows, macOS, and Linux. Therefore, you can build and run your calculator on various devices without hassle. Hence, this flexibility is essential, especially if using different computers for your projects.

What Is Fixer API?
Fixer is a simple yet powerful tool that offers both current and past foreign exchange rates. Moreover, its API structure is easy to grasp. Hence, it allows you to integrate it into your website quickly, often within 10 minutes.
Fixer draws data from more than 15 trusted financial sources, including the European Central Bank, to ensure stability and reliability. Moreover, this data is updated every 60 seconds, providing up-to-date information.
With Fixer, you gain access to various API endpoints. These endpoints cover a range of functionalities. Some examples are retrieving the latest rates, historical data, trends over time, fluctuations, and currency conversion. Moreover, you can fetch numerous currencies’ most recent exchange rates by writing just a few lines of code. Even better, you can get started with Fixer at no cost through its free plan or opt for one of the available paid plans.

Key Features:
- Ensures high-level security comparable to that of banks.
- Offers responsive technical support.
- Provides detailed and easy-to-follow documentation.
- Supports SSL encryption for added safety.
- Delivers accurate and reliable current and historical currency values.
- Presents data in a portable JSON format.
- Includes a user-friendly endpoint for effortless currency conversion.
How to Set Up the Project to Build a Historical Exchange Rates Calculator in Python?
Follow the below steps to set up the project for building a historical exchange rates calculator.
- Get an API key from Fixer API.
- Create a new directory using Command Prompt.
- Open it inside the Visual Studio Code.
- Create a new file and name it “app.py”
- Create a new folder in the same directory. Then, name it “templates.”
- Create a new index.html file and place it inside the templates.
- Next, create a styles.css file and place it inside the static folder. Then, you must create the static folder inside the same directory.
Let’s begin our coding now!

How to Build the Historical Exchange Rates Calculator?
Here is the code that you should write for each file.
app.py
Step 1: Import Necessary Modules
from flask import Flask, render_template, request
import requests
We import the required modules: `Flask` for building web applications, `render_template` for rendering HTML templates, and `request` for handling HTTP requests. Additionally, we import the `requests` module for making HTTP requests to external APIs.
Step 2: Create a Flask Application
app = Flask(__name__)
We created a Flask application instance named `app`.
Step 3: Define a Function to Get Exchange Rates
def get_exchange_rates(date, base_currency, target_currency):
url = f"http://data.fixer.io/api/{date}?access_key=YOURAPIKEY&base={base_currency}&symbols={target_currency}"
response = requests.get(url)
data = response.json()
if response.status_code == 200:
return data['rates'][target_currency]
else:
return None
```
We define a function `get_exchange_rates()` that takes three parameters: `date`, `base_currency`, and `target_currency`. Inside the function, we construct the API URL using the provided parameters. Make sure that you enter your API key. Then, we make an HTTP GET request to the URL using the `requests` module.
If the response status code is 200 (successful), we extract and return the exchange rate for the `target_currency`. Otherwise, we return `None`.
Step 4: Create a Route for the Main Page (“/”)
@app.route("/", methods=['GET', 'POST'])
def index():
# Code inside the function
We use a decorator (`@app.route(“/”)`) to define a route for the root URL (“/”) of the web application. We specify that this route supports both GET and POST methods. The associated function `index()` will handle requests to this route.
Step 5: Handling POST Requests and Currency Conversion
if request.method == 'POST':
base_currency = request.form['base_currency'].upper()
target_currency = request.form['target_currency'].upper()
date = request.form['date']
amount = float(request.form['amount']) # Convert amount to float
exchange_rate = get_exchange_rates(date, base_currency, target_currency)
if exchange_rate is not None:
converted_amount = amount * exchange_rate
result = f"{amount} {base_currency} on {date} = {converted_amount:.2f} {target_currency}"
else:
result = "Error fetching exchange rates."
return render_template('index.html', result=result)
```
Inside the `index()` function, we check if the HTTP request method is POST (indicating a form submission). Then, we extract the input values (`base_currency`, `target_currency`, `date`, and `amount`) from the submitted form data using `request.form`. Moreover, we convert the `amount` to a floating-point number using `float()`.
Next, we call the `get_exchange_rates()` function to fetch the exchange rate. If the exchange rate is obtained, we calculate the converted amount and format a result message. Otherwise, we display an error message.
Step 6: Rendering the Template
return render_template('index.html', result=result)
We render the HTML template named `index.html` and pass the `result` variable to it. The template will display the result on the webpage.
Step 7: Running the Application
if name == "__main__":
app.run(debug=True)
Finally, we ensure that the Flask application runs only if the script is executed directly (not imported as a module) using the `if name == “__main__”:` statement.
This code creates a Flask web application that allows users to input currency conversion details, fetches exchange rates from the Fixer API, performs the conversion and displays the result on a webpage.
index.html
Step 1: Document Structure and Metadata
<!DOCTYPE html>
<html>
<head>
<title>Historical Exchange Rates Calculator</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
`<!DOCTYPE html>`: Defines the document type as HTML5.
Then, `<html>`: The root element of the HTML document.
`<head>`: Contains metadata and resources related to the document.
Then, `<title>`: Sets the web page’s title, which appears in the browser tab.
`<link rel=”stylesheet” …>`: Links an external CSS stylesheet (`styles.css`) to style the page. The `url_for()` function generates the correct URL to the static CSS file.
Step 2: Body Content
<body>
<div class="calculator-container">
<h1>Historical Exchange Rates Calculator</h1>
<form method="POST">
<!-- Form elements -->
</form>
{% if result %}
<p>{{ result }}</p>
{% endif %}
</div>
</body>
</html>
`<body>` contains the visible content of the web page.
Next, `<div class=”calculator-container”>` is a container for structuring the calculator section.
`<h1>` displays the main heading of the page.
Then, `<form method=”POST”>` defines a form that uses the HTTP POST method to send data to the server.
Inside the form:
Form input elements (`<label>`, `<input>`) for a base currency, target currency, date, and amount.
`<input type=”submit” value=”Calculate”>` is a submit button for sending the form data.
`{% if result %}` is a template tag that checks if the `result` variable exists.
`<p>{{ result }}</p>` works in a way that If `result` exists, it displays the value within a paragraph element.
This HTML code sets up the structure of a web page for the Historical Exchange Rates Calculator. It includes a form where users can input currency conversion details and a space to display the result. The styling is controlled by an external CSS file (`styles.css`). When users submit the form, the data is sent to the server for processing, and the result is displayed on the page if available.
styles.css
You may copy-paste the code below into the CSS file or create your styles.
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
background-image: url('https://cdn.pixabay.com/photo/2022/07/12/12/29/euro-7317266_1280.jpg');
background-repeat: no-repeat, repeat;
background-size: cover;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.calculator-container {
background-color: #ffffff;
border-radius: 8px;
padding: 20px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
width: 350px;
}
h1 {
text-align: center;
margin-bottom: 20px;
}
form {
display: flex;
flex-direction: column;
}
label {
margin-bottom: 5px;
}
input[type="text"],
input[type="number"] { /* Added style for number input */
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="submit"] {
padding: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
p {
margin-top: 10px;
font-weight: bold;
}
This CSS code styles the appearance of the Historical Exchange Rates Calculator web page. It sets the font, background image, layout, colors, and spacing for various elements. Hence, making the calculator visually appealing and user-friendly.
Output

Conclusion
Crafting a Historical Exchange Rates Calculator in Python offers valuable insight into the dynamic world of foreign exchange. It helped us create a tool that empowers users to explore historical currency data. Hence, aiding informed financial decisions. From API integration and data retrieval to user interface design and data visualization, this project encapsulates key aspects of modern programming.
Building this calculator enhances our Python skills and equips us with a versatile tool for analyzing currency trends. Through this endeavor, we’ve embarked on a seamless journey that merges finance and technology, expanding our horizons in both domains.
FAQs
Where Can I Find Historical FX Rates?
You can find historical FX rates on financial data platforms, exchange rate websites, and APIs like Fixer.
What Does the Historical Exchange Rate Mean?
The Historical Exchange Rate signifies past currency values against another. Hence, revealing fluctuation trends for informed financial analysis.
When Was the Pound Strongest Against the Dollar?
The pound reached its strongest point against the dollar in [mention specific date or period.
What Was the Highest Dollar Rate Ever?
The highest dollar rate ever recorded surged to unprecedented levels in financial history.

Recent Comments