DEV Community

A0mineTV
A0mineTV

Posted on

Building an Interactive Budget Calculator with Streamlit πŸš€

Introduction

Managing a budget is a critical part of financial planning, and automating the process makes it even more convenient. In this tutorial, we will build an interactive budget calculator app using Streamlit. The app will allow users to:

  1. Input their monthly income.
  2. Add and track expenses.
  3. Display a dynamic summary of income, expenses, and the remaining balance.

By leveraging Streamlit's @st.fragment decorator, we will modularize the application for better maintainability and performance.

Features of the App

  1. Input Monthly Income: Users can enter and update their monthly income.
  2. Add Expenses: Track expenses with names and amounts.
  3. Summary Display: View the total income, total expenses, and remaining balance dynamically.
  4. Interactive Interface: Real-time updates to reflect changes in income or expenses.

The Code

Here’s the complete code for the budget calculator:

import streamlit as st

# Initialize session state variables
if "income" not in st.session_state:
    st.session_state.income = 0.0

if "expenses" not in st.session_state:
    st.session_state.expenses = []

@st.fragment
def income_input_fragment():
    """
        Fragment for entering monthly income.
    """
    with st.form(key="income_form"):
        income = st.number_input("Monthly Income (€)", min_value=0.0, step=100.0, value=st.session_state.income)
        submit_button = st.form_submit_button('Update')
        if submit_button:
            st.session_state.income = income
            st.success(f"Income updated: {income} €")
            st.rerun()

@st.fragment
def expense_input_fragment():
    """
        Fragment for adding an expense.
    """
    with st.form(key="expense_form"):
        expense_name = st.text_input('Expense Name')
        expense_amount = st.number_input('Expense Amount (€)', min_value=0.0, step=10.0)
        submit_button = st.form_submit_button('Add Expense')
        if submit_button:
            st.session_state.expenses.append({"name": expense_name, "amount": expense_amount})
            st.success(f"Expense added: {expense_name} ({expense_amount} €)")
            st.rerun()

@st.fragment
def summary_fragment():
    """
        Fragment to display the budget summary.
    """
    st.subheader("Budget Summary")
    total_expenses = sum(expense["amount"] for expense in st.session_state.expenses)
    balance = st.session_state.income - total_expenses

    st.metric('Monthly Income', f"{st.session_state.income} €")
    st.metric('Total Expenses', f'{total_expenses} €')
    st.metric('Remaining Balance', f'{balance} €', delta=None if balance >= 0 else f"{balance} €")

    st.subheader('Expense Details')
    if st.session_state.expenses:
        for expense in st.session_state.expenses:
            st.write(f"- {expense['name']}: {expense['amount']} €")
    else:
        st.info('No expenses recorded.')

# Main application
st.title('Monthly Budget Calculator')

st.header('1. Enter Income')
income_input_fragment()

st.header('2. Add an Expense')
expense_input_fragment()

st.header('3. Budget Summary')
summary_fragment()
Enter fullscreen mode Exit fullscreen mode

Code Breakdown

1. Session State Initialization

The app uses Streamlit’s st.session_state to store income and expenses persistently across user interactions. This ensures the state of the application remains consistent without manual data management.

if "income" not in st.session_state:
    st.session_state.income = 0.0

if "expenses" not in st.session_state:
    st.session_state.expenses = []
Enter fullscreen mode Exit fullscreen mode

2. Income Input Fragment

This fragment allows users to input or update their monthly income. The form refreshes the application (st.rerun()) to reflect changes immediately.

3. Expense Input Fragment

This fragment enables users to add expenses. Each expense includes a name and an amount, stored as a dictionary in the st.session_state.expenses list.

4. Summary Fragment

The summary fragment calculates:

  • Total expenses.
  • Remaining balance (income - total expenses).
  • Displays these metrics dynamically using st.metric.
  • Lists all recorded expenses or shows a message if none exist.

Features in Action

Dynamic Updates

When users add or update income/expenses, the app recalculates and displays the updated summary in real-time.

Intuitive Design

The app divides functionality into three sections:

  1. Input Income
  2. Add Expenses
  3. View Summary

Potential Improvements

  1. Expense Deletion:

    • Add an option to remove specific expenses from the list.
  2. Categorization:

    • Allow users to categorize expenses (e.g., Rent, Groceries, Entertainment).
  3. Visualizations:

    • Display expense distribution using charts (st.bar_chart, st.pie_chart).
  4. Export Data:

    • Enable exporting the summary as a CSV or PDF.

Conclusion

This app demonstrates how Streamlit can be used to create interactive and modular applications. By leveraging session state and fragments, it provides real-time updates and a clean user experience. Whether you’re a developer or just starting with Python, this project is a great introduction to building practical Streamlit apps.

Try it out and let us know how you enhanced it! πŸš€


Happy coding! πŸŽ‰

Top comments (0)