DEV Community

Cover image for Develop a Dynamic Inflation Data Visualizer with Flask Python Matplot Pandas
IvanDev
IvanDev

Posted on • Edited on

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. SelectNew Terminal`.
  • For Windows using subsystem WSL:
  • Follow the previous steps from Linux/Mac.

Type the following command in the terminal:
bash
cd inflation-tracker

In the inflation-tracker type the following in the terminal:
bash
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:
bash
touch app.py .env

Step 2:Install libraries

bash
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:

FRED landing page

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:
FRED register
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"

FRED request or see API key

Then you have to explain why the request of data so as student this will be education purposes:

FRED why data requests

Finally, check the result I have mine it's secret so you have to use this one in the .env in the following steps:
FRED generated apikey

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:
imports python
app.py rest of the code:
python code

  1. Environment Variable Loading:
  2. 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.
  3. Flask App Initialization:
  4. app = Flask(__name__) initializes the Flask web app, preparing it to handle web requests.
  5. render_template() is used to render HTML templates, and request allows handing GET and POST request data from the form.
  6. Route Definition and Method Handling:
  7. @app.route('/', methods=['GET', 'POST']) defines a route at the route URL /. This route accepts both GET and POST requests.
  8. The index() function processes these requests, displaying a form on GET and handling user input on POST.
  9. Form Input(POST):
  10. When the form is submitted via POST, the start_year and end_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.
  11. Requests:
  12. This library handles making HTTP requests to external APIs. It fetches inflation data from the St. Lous Fed API requests.get().
  13. Handling API Response:
  14. If the request is successful response.status_code == 200, the inflation data is converted into a Pandas DataFrame df, allowing easier data manipulation.
  15. Data Processing and Normalization:
  16. Using Pandas library as pd extracts the inflation value for the Start year with a Data Science script:

python
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 the date column matches the start_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 fallback else 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) \* 100

  • It 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 selected start_yearand end_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 to end_year. The plot is saved as an image in the static folder static/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](http://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.html

<!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>
Enter fullscreen mode Exit fullscreen mode

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 and end_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 using `' 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 termianal, type:

bash
python3 inflation-tracker

It will run the Flask server on http//127.0.0.1:5000:
Run the app

Then, see the browser up and running:
Webpage Inflation calculator

Input the date ranges from the starting year to the end year and press the "Show Inflation Data" button to show the graph:
Input values and press button

See result image:
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

About the Author

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.

Top comments (0)