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:
- Input their monthly income.
- Add and track expenses.
- 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
- Input Monthly Income: Users can enter and update their monthly income.
- Add Expenses: Track expenses with names and amounts.
- Summary Display: View the total income, total expenses, and remaining balance dynamically.
- 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()
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 = []
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:
- Input Income
- Add Expenses
- View Summary
Potential Improvements
-
Expense Deletion:
- Add an option to remove specific expenses from the list.
-
Categorization:
- Allow users to categorize expenses (e.g., Rent, Groceries, Entertainment).
-
Visualizations:
- Display expense distribution using charts (
st.bar_chart
,st.pie_chart
).
- Display expense distribution using charts (
-
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)