Develop a Dynamic Inflation Data Visualizer with Flask Python Matplot Pandas
Introduction
At this time, when many places in the world have inflation, and everybody is talking about it, I decided to do an inflation calculator. First, let me explain what inflation is.
I love economics, but as you know, I am a software developer. So, I will have the following reference from a well-known book in economics:
"In the XVI century, gold and silver deposits in the American Continent were discovered and exploited, and enormous quantities of the precious metals were transported to Europe. The result of this increase in the quantity of money was a general tendency for prices in Europe to move upward. In the same way, today, when a government increases the amount fo paper money, the result is that the purchasing power of the unit of currency begins to fall, and prices begin to rise. This is called inflation". As you can see, it is an excellent explanation from a great writer in economics.
Excerpted from "Economic Policy book by Ludwid Von Mises, (4th Conference, pg: 32)
Now it's time to work on the program that will show us the U.S. inflation relative calculator:
Requirements:
In the program, a user inputs a determined starting year and end year, with boundaries from 1947 to 2024 or the current year.
I will take a FRED (Federal Reserve Bank of St. Louis) API from the USA that gathers all economics data from the USA. You can also utilize public data from your country, but I'm using the US public economics data for educational purposes.
Once I connect to the API, the program will generate a PNG to show the data.
Setting Up the Environment
Prerequisites:
Basic Python language
Code editor
Basic command line
Step 1: Setting Up the Project
- Install Python here. From the Python page, download the latest stable version of Python. Once you've downloaded the installation file, execute it, install it on your computer, and follow all recommended prompts. Clone the repository and move to it:
Code: inflation-tracker-app
Your project's path:
/home/your-username/Projects/my_project
(Linux)
/Users/your-username/Projects/my_project
(Mac)
Open VS Code at the top of the bar and press
Terminal in the dropdown box. Select
New Terminal`.For Windows using subsystem WSL:
Follow the previous steps from Linux/Mac.
Type the following command in the terminal:
cd inflation-tracker
In the inflation-tracker
type the following in the terminal:
mkdir static templates
This will create two directories: static
to store assets PNG image and templates
where I code the HTML code to show UI.
I will create the following two files: app.py
as the entry point for the application to work and the .env
file to store sensitive information like the API secret key that I will use in this project:
touch app.py .env
Step 2:Install libraries
pip install Flask requests pandas matplotlib dotenv
So, those were quite too many libraries, but they will ensure that the program works like charm magic. Here, it was installed In Flask
to render the index.html
file, requests
to resolve or read the given URL path, a famous Data Science Python library pandas
for data manipulation analysis, handling structured data such as tables, spreadsheets, and time series, matplotlib.pyplot
to plot to have an output to visualize data in graphs, and finally load_dotenv
to load .env
sensitive secret key.
Before writing the code, you need to get the API key to retrieve the information from FRED:
Sign Up for an account with just your email and set a password in the right upper corner where it reads My Account:
Then register as shown in tabs select "Create New Account" with your email and password or you can use with Google but for the moment is not enable that feature:
After that just press "Okay" button to follow to the dashboard:
Now that you are in the dashboard see the button "Request or view your API keys"
Then you have to explain why the request of data so as student this will be education purposes:
After that, check the result API key:
Finally, check the result I have mine it's secret so you have to use this one in the .env
in the following steps:
Remember that I've created the .env
file paste key like this:
API_KEY=paste-here-your-key-without-any-other-symbol
So, for now in this part I'm done with the .env
secure secret key.
Step 3: Write the code
Import the libraries:
from flask import Flask, render_template, request
import requests
import pandas as pd
import matplotlib.pyplot as plt
import os
from dotenv import load_dotenv
app.py rest of the code:
load_dotenv()
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
plot_url = None
if request.method == 'POST':
start_year = int(request.form['start_year'])
end_year = int(request.form['end_year'])
API_KEY = os.getenv("API_KEY")
url = f"https://api.stlouisfed.org/fred/series/observations?series_id=CPIAUCSL&api_key={API_KEY}&file_type=json"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
df = pd.DataFrame(data['observations'])
df['value'] = df['value'].astype(float)
df['date'] = pd.to_datetime(df['date'])
inflation_start_year = df[df['date'].dt.year == start_year]['value'].values[0] if not df[df['date'].dt.year == start_year].empty else 0
df['normalized_inflation'] = ((df['value'] - inflation_start_year) / inflation_start_year) * 100
df_filtered = df[(df['date'].dt.year >= start_year) & (df['date'].dt.year <= end_year)]
average_normalized_inflation = df_filtered['normalized_inflation'].mean()
print(f"Average Normalized Inflation Rate from {start_year} to {end_year}: {average_normalized_inflation:.2f}%")
plt.figure(figsize=(10, 6))
plt.plot(df_filtered['date'], df_filtered['normalized_inflation'], label='Normalized Inflation Rate', color='blue')
plt.axhline(0, color='red', linestyle='--', label='0% Inflation')
plt.xlabel('Year')
plt.ylabel('Normalized Inflation (%)')
plt.title(f'Normalized U.S. Inflation ({start_year} - {end_year})')
plt.legend()
plt.grid()
plt.xticks(rotation=45)
plt.tight_layout()
plot_path = 'static/inflation_plot.png'
plt.savefig(plot_path)
plt.close()
plot_url = plot_path
else:
print(f"Error fetching data: {response.status_code} - {response.text}")
return render_template('index.html', plot_url=plot_url)
if __name__ == '__main__':
app.run(debug=True)
- Environment Variable Loading:
load_dotenv()
loads environment variables from a.env
file into the program, allowing the app to access sensitive data (like API keys) without hardcoding them.
- Flask App Initialization:
app = Flask(__name__)
initializes the Flask web app, preparing it to handle web requests.render_template()
is used to render HTML templates, andrequest
allows handing GET and POST request data from the form.
- Route Definition and Method Handling:
@app.route('/', methods=['GET', 'POST'])
defines a route at the route URL/
. This route accepts bothGET
andPOST
requests.The
index()
function processes these requests, displaying a form onGET
and handling user input onPOST
.
- Form Input(POST):
- When the form is submitted via
POST
, thestart_year
andend_year
are fetched from the user's input and converted into integers for further processing. It defines the date range for the inflation data the user wants to see.
Requests:
- This library handles making HTTP requests to external APIs. It fetches inflation data from the St. Lous Fed API
requests.get()
.
- This library handles making HTTP requests to external APIs. It fetches inflation data from the St. Lous Fed API
Handling API Response:
- If the request is successful
response.status_code == 200
, the inflation data is converted into a Pandas DataFramedf
, allowing easier data manipulation.
- Data Processing and Normalization: Using Pandas library as
pd
extracts the inflation value for the Start year with a Data Science script:
inflation_start_year = df[df['date'].dt.year == start_year]['value'].values[0] if not df[df['date'].dt.year == start_year].empty else 0
This line looks for the inflation value in the DataFrame for the
start_year
provided by the user.df[df['date'].dt.year == start_year]
: It filters the DataFrame to select rows where thedate
column matches thestart_year
.['value'].values[0]
: It extracts the inflation value for that year (first math).If the filtered result is empty (no data for that year), it assigns
0
as a fallbackelse 0
.Normalization means expressing inflation values relative to the inflation in the
start_year
.The inflation value for the
start_year
is retrieved, and the data is normalized relative to that year. The data normalization is: normalized_inflation=((value-inflation_start_year)/inflation_start_year) * 100It makes comparing inflation changes over time easier by expressing them as percentages relative to the starting year.
- Data Filtering for Specific Years:
- The DataFrame is filtered
df_filtered
only to include rows between the user's selectedstart_year
andend_year
.
- Calculating Average Inflation:
- The average normalized inflation rate for the selected period is calculated and printed out.
- Plotting the Data:
- A line chart is created using Matplotlib to visualize the normalized inflation rate over the selected time period
start_year
toend_year
. The plot is saved as an image in thestatic
folderstatic/inflaction_plot.png
.
- Rendering the Template:
- After processing the data and saving the plot, the template
index.html is rendered and displays the plot image if the
POST` request is successful.
Running the App:
app.run
(debug=True)
starts the Flask app in debug mode, which allows easy error tracking and automatic reloading when changes are made to the code.
Code Flow:
The app collects start and end years from a user-submitted form.
It fetches inflation data using the API and processes it with Pandas.
A graph of the normalized inflation rate is plotted and displayed on the web page.
UI index.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>U.S. Inflation Over Time</title>
</head>
<body>
<h1>U.S. Inflation Calculator</h1>
<h2>Instructions:</h2>
<p>Input the begining year from 1947 and ahead. For example, 1947 to 2024, or 2000 to 2024,</p>
<p>The output will be the calculation relative to the end year to substract start year.</p>
<p>2008 to 2012, you can place whatever year from 1947 to 2024 boundaries:</p>
<form method="POST" action="/">
<label for="start_year">Start Year:</label>
<input type="number" id="start_year" name="start_year" required>
<label for="start_year">End Year:</label>
<input type="number" id="end_year" name="end_year" required>
<input type="submit" value="Show Inflation Data">
</form>
{ if plot_url }
<h2>Inflation Plot</h2>
<img src="{{ plot_url }}" alt="Inflation Plot">
{ endif }
</body>
</html>
HTML Structure
Basic webpage.
It uses the element
form
to provide a form where the users can input text or a URL.It uses the POST method to send input to the Flask app, such as
start_year
andend_year
.The form submits data via POST to the root URL
action="/"
The dynamic content section within
{% if plot_url %}
checks if a plot image is available and displays it usingimg
tag when the plot URL exits.
In this way, the page dynamically shows a graph generated by the backend.
Step 4: Test the app
In the terminal, type:
python3 inflation-tracker
It will run the Flask server on http//127.0.0.1:5000
:
Then, see the browser up and running:
Input the date ranges from the starting year to the end year and press the "Show Inflation Data" button to show the graph:
Result image:
If you have any problems, you can check the code from my repo in the header of this page. If you like my code, please give it a star on Github or follow me here. I would really appreciate it.
Summarize
I believe you learned how to handle data with the Python "Pandas" library in this lesson. We also use the Flask library to build our backend and connect it with the UI template index.html
. Furthermore, I used API from FRED to get fresh data from US economics and explain what is indeed inflation so we understand how the concept works. Besides that, I use matplotlib
to plot the results in our UI. Finally, I secure the API key in a .env
file to avoid vulnerabilities once we work with repositories.
Conclusion
The flexibility of this app also opens up possibilities for future enhancements, such as adding more datasets or customizing the visualizations. This guide helps others see how easy it can be to use public economic data in meaningful and educational ways. You can also retrieve that public data from your country: check the Central Bank public API or the financial institution for research in your country, and just change the endpoint URL and replace it.
References
Subscribe to my newsletter
Read articles from Ivan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ivan
Ivan
Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on X, Github, and LinkedIn for more insights and updates.