Build a Streamlit Income and Expense Tracker With a Sankey Chart
A Streamlit app with two views. A form saves each month’s income and expenses to a database, and a second view draws the month as an interactive Plotly Sankey chart: every income stream flows into a total and out to each expense. The code below stores the data in SQLite.
Update (November 2026): The video stores the data in Deta Base, which is offline. I rewrote the database file for SQLite and swapped the option-menu package for Streamlit’s built-in segmented control. The rest is unchanged. Tested with Streamlit 1.67 and Plotly 7.2.
Table of contents
What the app does
The Data Entry view is a form: pick a month and a year, type the amounts for each income and expense category, add a comment, and save. The Data Visualization view lists every saved period. Pick one and the app shows three metrics (total income, total expense, remaining budget) and the Sankey chart:

The categories and the currency are plain lists at the top of the script, so you can adapt the tracker to your own budget without touching the rest of the code.
Install and project layout
You need Streamlit for the app and Plotly for the chart. SQLite is part of Python’s standard library.
pip install streamlit plotly
Create a folder with two files: database.py for everything that touches the data, and app.py for the interface. Keeping the database code in its own file is what made the switch away from Deta a one-file change.
The database file
Deta Base stored each month as one record with a key such as 2026_January. The same shape fits one SQLite table: the period as the primary key, and the income and expense dictionaries stored as JSON text. The three functions the app calls stay exactly as they were in the video.
import json
import sqlite3
DB_FILE = "monthly_reports.db"
def _connect():
con = sqlite3.connect(DB_FILE)
con.execute(
"CREATE TABLE IF NOT EXISTS reports ("
"period TEXT PRIMARY KEY, incomes TEXT, expenses TEXT, comment TEXT)"
)
return con
def insert_period(period, incomes, expenses, comment):
"""Saves one period. Saving the same period again overwrites it."""
with _connect() as con:
con.execute(
"INSERT OR REPLACE INTO reports VALUES (?, ?, ?, ?)",
(period, json.dumps(incomes), json.dumps(expenses), comment),
)
def fetch_all_periods():
"""Returns the keys of all saved periods, newest first."""
with _connect() as con:
rows = con.execute("SELECT period FROM reports ORDER BY period DESC").fetchall()
return [row[0] for row in rows]
def get_period(period):
"""Returns one period as a dict, or None if it does not exist."""
with _connect() as con:
row = con.execute(
"SELECT incomes, expenses, comment FROM reports WHERE period = ?", (period,)
).fetchone()
if row is None:
return None
return {"incomes": json.loads(row[0]), "expenses": json.loads(row[1]), "comment": row[2]}
The database file is created on first use. The question marks are placeholders, so user input never becomes part of the SQL text. For more SQL than this, see combining SQL and Python for analysis and reports.
The app code
The whole interface fits in one file. The form uses st.form, so Streamlit waits for the Save button instead of rerunning on every keystroke. Each category gets a number input inside an expander. The widgets have keys, so after submitting I read every value from st.session_state in one dictionary comprehension. This is the complete app.py:
import calendar
from datetime import datetime
import plotly.graph_objects as go
import streamlit as st
import database as db
# -------------- SETTINGS --------------
incomes = ["Salary", "Blog", "Other Income"]
expenses = ["Rent", "Utilities", "Groceries", "Car", "Other Expenses", "Saving"]
currency = "USD"
page_title = "Income and Expense Tracker"
page_icon = ":money_with_wings:"
# --------------------------------------
st.set_page_config(page_title=page_title, page_icon=page_icon, layout="centered")
st.title(page_title + " " + page_icon)
years = [datetime.today().year, datetime.today().year + 1]
months = list(calendar.month_name[1:])
selected = st.segmented_control(
"View", ["Data Entry", "Data Visualization"], default="Data Entry",
label_visibility="collapsed",
)
if selected == "Data Entry":
st.header(f"Data Entry in {currency}")
with st.form("entry_form", clear_on_submit=True):
col1, col2 = st.columns(2)
col1.selectbox("Select Month:", months, key="month")
col2.selectbox("Select Year:", years, key="year")
with st.expander("Income"):
for income in incomes:
st.number_input(f"{income}:", min_value=0, format="%i", step=10, key=income)
with st.expander("Expenses"):
for expense in expenses:
st.number_input(f"{expense}:", min_value=0, format="%i", step=10, key=expense)
with st.expander("Comment"):
comment = st.text_area("Comment", placeholder="Enter a comment here ...",
label_visibility="collapsed")
submitted = st.form_submit_button("Save Data")
if submitted:
period = f"{st.session_state['year']}_{st.session_state['month']}"
income_values = {income: st.session_state[income] for income in incomes}
expense_values = {expense: st.session_state[expense] for expense in expenses}
db.insert_period(period, income_values, expense_values, comment)
st.success("Data saved!")
if selected == "Data Visualization":
st.header("Data Visualization")
with st.form("saved_periods"):
period = st.selectbox("Select Period:", db.fetch_all_periods())
submitted = st.form_submit_button("Plot Period")
if submitted and period:
period_data = db.get_period(period)
income_values = period_data["incomes"]
expense_values = period_data["expenses"]
total_income = sum(income_values.values())
total_expense = sum(expense_values.values())
col1, col2, col3 = st.columns(3)
col1.metric("Total Income", f"{total_income} {currency}")
col2.metric("Total Expense", f"{total_expense} {currency}")
col3.metric("Remaining Budget", f"{total_income - total_expense} {currency}")
st.text(f"Comment: {period_data['comment']}")
# Sankey: every income flows into "Total Income", which flows out to every expense
label = list(income_values) + ["Total Income"] + list(expense_values)
source = list(range(len(income_values))) + [len(income_values)] * len(expense_values)
target = [len(income_values)] * len(income_values) + [
label.index(expense) for expense in expense_values
]
value = list(income_values.values()) + list(expense_values.values())
link = dict(source=source, target=target, value=value)
node = dict(label=label, pad=20, thickness=30, color="#4C9BE8")
fig = go.Figure(go.Sankey(link=link, node=node))
fig.update_layout(margin=dict(l=0, r=0, t=5, b=5))
st.plotly_chart(fig)
Run it with streamlit run app.py. I tested it by saving a month with fictional numbers and plotting it; the result is the screenshot above.
How the Sankey chart works
A Plotly Sankey chart needs nodes and links. The nodes are the labels: the income categories, one node called Total Income, then the expense categories. Each link has a source node index, a target node index and a value:
- Every income links from its own index to the Total Income node, with the income amount as the value.
- The Total Income node links to each expense node, with the expense amount as the value.
With three incomes, Total Income is node 3, so the sources are [0, 1, 2, 3, 3, 3, ...] and the targets [3, 3, 3, 4, 5, 6, ...]. The code builds those lists from the dictionaries, so adding a category to the settings lists is enough. If the expenses add up to less than the income, the Total Income bar is taller than its outflows and the gap is your remaining budget. Hover over a link to see its amount.
Navigation and styling
The video uses the streamlit-option-menu package for a horizontal menu with icons. Streamlit has since added st.segmented_control, a row of buttons where one is selected, so the code above needs no extra package.
If you prefer the icons, install streamlit-option-menu and replace the selected = ... line with the option_menu call; nothing else changes. The package is covered in adding a navigation menu to Streamlit.
The video also hides the Streamlit menu, header and footer with a short CSS block. Colors go into the theme section of .streamlit/config.toml, with keys such as primaryColor and backgroundColor. The CSS snippet and what still applies in current versions are in hiding the Streamlit menu and header.
Deploying the app
Locally, the data survives because the SQLite file sits next to your script. On Streamlit Community Cloud or a free Render service the disk is temporary, so the file disappears when the app restarts. That is the problem Deta solved in the video.
For a deployed tracker, keep the same three functions in database.py and point them at a hosted database, for example a Postgres instance from a provider with a free tier. Keep its connection string in .streamlit/secrets.toml rather than in the code. For small amounts of data, a Google Sheet works too; see connecting Streamlit to Google Sheets.
Troubleshooting
If the period list stays empty, no month has been saved yet. The selectbox only shows periods that are in the database, so save at least one month first.
If you did save one and the list is still empty, start Streamlit from the folder that contains monthly_reports.db. The path in database.py is relative, so starting the app from another folder creates a second, empty database there. Saving the same month twice overwrites the first entry on purpose, so a correction replaces the old numbers.
