How to create an Income and Expense App in Streamlit

How to create an Income and Expense App in Streamlit

posted 3 min read

One fundamental concept in economics that we should impart to our children is the relationship between income and expenses. Income refers to the money we earn and accumulate, while expenses represent the money we spend or let go of.

We are going to create an income and expense web application or app using the Streamlit framework. With a little bit of learning, Streamlit converts our Python script into a web app which can be run locally or in the cloud for sharing.

Streamlit is briefly introduced in my other article how to build a contact web app using streamlit.

Building an Income and Expense App

  • We have an app title at the top "Income and Expense App"
  • The body is composed of three tabs namely "Dashboard", "Income", and "Expense".
  • The Dashboard tab contains the Net Worth sub-header, Income table and Expense table.

income and expense dashboard

  • The Income tab contains a form where users input their income.
  • The expense tab contains a form where users input their expenses.

income tab

All the income and expense inputs are saved in a csv file. The same csv file will be read to calculate the net worth.

Requirements

You need to create a requirements.txt file and write streamlit on it.

requirements.txt

streamlit

Open your terminal, or powershell and install the requirements with pip.

pip install -r requirements.txt

Code

streamlit_app.py

"""Income and expense App"""

import streamlit as st
import pandas as pd

INCOME_CSV_FILE = 'income.csv'
EXPENSE_CSV_FILE = 'expense.csv'

def get_income_df():
    try:
        return pd.read_csv(INCOME_CSV_FILE)
    except FileNotFoundError:
        return pd.DataFrame(columns=['Date', 'Amount', 'Note'])

def get_expense_df():
    try:
        return pd.read_csv(EXPENSE_CSV_FILE)
    except FileNotFoundError:
        return pd.DataFrame(columns=['Date', 'Amount', 'Note'])

st.markdown('# Income and Expense App')

dashboard, income, expense = st.tabs(['DASHBOARD', 'INCOME', 'EXPENSE'])

with dashboard:
    df_income = get_income_df()
    df_expense = get_expense_df()

    total_income = df_income['Amount'].sum()
    total_expense = df_expense['Amount'].sum()

    net = total_income - total_expense

    color = 'red' if net < 0 else 'green'
    st.markdown(f'''# Net Worth: {net}''', unsafe_allow_html=True)

    col1, col2 = st.columns(2)

    with col1:
        st.write('Income')
        st.dataframe(get_income_df(), height=150)

    with col2:
        st.write('Expense')
        st.dataframe(get_expense_df(),height=150)

with income:
    df = get_income_df()

    with st.form('income'):
        date = st.date_input('Date')
        amount = st.number_input('Amount', value=0.0)
        note = st.text_input('Note')
        submit = st.form_submit_button('Save', type='primary')

    if submit:
        data = {'Date': date, 'Amount': amount, 'Note': note}
        df = pd.concat([df, pd.DataFrame([data])], ignore_index=True)
        df.to_csv(INCOME_CSV_FILE, index=False)
        st.rerun()

    st.dataframe(df)


with expense:
    df = get_expense_df()

    with st.form('expense'):
        date = st.date_input('Date')
        amount = st.number_input('Amount', value=0.0)
        note = st.text_input('Note')
        submit = st.form_submit_button('Save', type='primary')

    if submit:
        data = {'Date': date, 'Amount': amount, 'Note': note}
        df = pd.concat([df, pd.DataFrame([data])], ignore_index=True)
        df.to_csv(EXPENSE_CSV_FILE, index=False)
        st.rerun()

    st.dataframe(df)

We use the pandas library to create dataframes and manipulate data. We also use it to save data to csv file. The csv files are saved in the same folder where the main script streamlit_app.py is located.

Run the application

Open your terminal and change to a directory where streamlit_app.py is located.

streamlit run streamlit_app.py

Then visit the url "http://localhost:8501" in your browser.

Code Maintenance

The code is also stored on gitlab, which makes it easier to manage updates.

Summary

Developing a web application with Streamlit is relatively straightforward, given that user input forms are readily available. Furthermore, the values retrieved from input widgets are as accessible as they would be in a Python script.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

How to create a Contact Web App using streamlit

Brando - Nov 13, 2023

How to read a file and search specific word locations in Python

Brando - Nov 8, 2023

How to fix the Taberror: inconsistent use of tabs and spaces

prince yadav - Sep 12, 2023

How to Fix the OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow Error in Python

Cornel Chirchir - Nov 7, 2023

How to Fix the TypeError: cannot use a string pattern on a bytes-like object Error in Python

Cornel Chirchir - Oct 29, 2023
chevron_left