Logo

dev-resources.site

for different kinds of informations.

Building an Interactive Budget Calculator with Streamlit ๐Ÿš€

Published at
12/13/2024
Categories
streamlit
python
webdev
Author
blamsa0mine
Categories
3 categories in total
streamlit
open
python
open
webdev
open
Author
11 person written this
blamsa0mine
open
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! ๐ŸŽ‰

streamlit Article's
30 articles in total
Favicon
Introducing GenAI Tweet Creator: Your AI-Powered Tweeting Assistant using Streamlit
Favicon
How to code a title in streamlit
Favicon
Interactive DataFrame Management with Streamlit Fragments ๐Ÿš€
Favicon
Streamlit Part 10: Page Navigation Simplified
Favicon
Streamlit Part 8: Status Elements
Favicon
IELTS Writing Task Generator
Favicon
Unlocking Knowledge!
Favicon
Build Your YouTube Video Transcriber with Streamlit & Youtube API's ๐Ÿš€
Favicon
Streamlit app
Favicon
Building an Interactive Budget Calculator with Streamlit ๐Ÿš€
Favicon
Building an Interactive Quiz App with Streamlit ๐Ÿš€
Favicon
Building a Streamlit Inventory Management App with Fragment Decorators ๐Ÿš€
Favicon
Building a Voice Transcription and Translation App with OpenAI Whisper and Streamlit
Favicon
Multi-Modality and Image Gen in a 1.3B Model!๐Ÿ”ฎ
Favicon
๐Ÿ–ผ๏ธ Build an Image Converter WebApp Using Python and Streamlit
Favicon
AI Agents: Transforming Ideas into Action, Collaboratively
Favicon
Simulating the Monty Hall problem using Streamlit
Favicon
Build a containerized AI Agent with watsonx.ai & CrewAI (and Streamlit) and Podman
Favicon
Streamlit Part 4: Mastering Media Elements - Logos, Images, Videos, and Audio
Favicon
Streamlit Part 7: Build a Chat Interface
Favicon
Stress Testing VLMs: Multi QnA and Description Tasks
Favicon
Building a Document Retrieval & Q&A System with OpenAI and Streamlit
Favicon
Streamlit Part 6: Mastering Layouts
Favicon
Building internal AI tools with Streamlit
Favicon
Streamlit Part 5: Mastering Data Visualization and Chart Types
Favicon
Making a Webapp is so EASY with Streamlit
Favicon
Building a Multi-Turn-Assistant Application using Llama, Claude and GPT4o
Favicon
Building a Document QA with Streamlit & OpenAI
Favicon
Building an ๐Ÿ OpenAI SWARM ๐Ÿ” Web Scraping and Content Analysis Streamlit Web App with ๐Ÿ‘ฅ Multi-Agent Systems
Favicon
Introduction to Using Generative AI Models: Create Your Own Chatbot ๐Ÿค–๐Ÿ’ฌ

Featured ones: