ExpenseTracker / app.py
ClarzW's picture
Update app.py
45c3566 verified
Raw History Blame Contribute Delete
6.06 kB
# PART 1
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Front End Design
st.title("Expense Tracker")
# PART 2
# Define the path for reading CSV file
DATA_FILE = 'expenses.csv'
# Functions
def load_data():
'''
Reads the CSV file saved within HuggingFace storage. If not found, then creates a dataframe to be used for storing expense data
'''
try:
# Attempt to load CSV file
return pd.read_csv(DATA_FILE)
except FileNotFoundError:
# Return empty DataFrame with specified columns if file is not found
return pd.DataFrame(columns=['Date', 'Category', 'Amount', 'Description'])
def save_data(df):
'''
Saves the expenses dataframe to HuggingFace storage
'''
df.to_csv(DATA_FILE, index=False)
# List of categories for the expense tracker
categories = ['Groceries', 'Transport', 'Bills', 'Takeout', 'Entertainment', 'Other']
# Initialize session state
if 'expenses' not in st.session_state:
st.session_state['expenses'] = load_data()
# Adding expense
with st.form("expense_form"):
# Input for entering expense amount, with min value of 1 pence
amount = st.number_input("Amount", format="%0.2f", min_value=0.01)
# Dropdown for selecting an expense category from a predefined list 'categories'
category = st.selectbox("Category", categories)
# Text input for a brief description of the expense
description = st.text_input("Description")
# Input for selecting the date of expense
date = st.date_input("Date")
# Button to submit the form
submit = st.form_submit_button("Add Expense")
if submit:
# Create a new DataFrame for the submitted expense details
new_expense = pd.DataFrame({
'Date': [date],
'Category': [category],
'Amount': [amount],
'Description': [description]
})
# Append new expense into existing 'expenses' DataFrame in session_state
st.session_state['expenses'] = pd.concat([st.session_state['expenses'], new_expense], ignore_index=True)
# Save the updated 'expenses' DataFrame to HuggingFace storage after adding new expense
save_data(st.session_state['expenses'])
# Display a success message after expense is added
st.success("Expense added successfully!")
# Check if there are any expenses in session state
if not st.session_state['expenses'].empty:
st.subheader("Current Expenses")
# Create a copy of the expenses DataFrame to avoid modifying the original
display_df = st.session_state['expenses'].copy()
# Convert 'Date' column to string format for better display
display_df['Date'] = display_df['Date'].astype(str)
# Show the DataFrame in a table format
st.dataframe(display_df)
else:
# Message displayed when there are no expenses
st.write("No expenses yet.")
# PART 4
if 'file_processed' not in st.session_state:
st.session_state['file_processed'] = False
# Upload file from user's computer
uploaded_file = st.file_uploader("Import Expense Data", type="csv")
# Checks if a file is uploaded and if it hasn't already been processed
if uploaded_file is not None and not st.session_state['file_processed']:
try:
# Read the uploaded CSV file into a DataFrame
new_data = pd.read_csv(uploaded_file)
# Expected column names to validate the structure of CSV
expected_columns = ['Date', 'Category', 'Amount', 'Description']
# Check if the uploaded CSV has the required columns
if list(new_data.columns) == expected_columns:
# Append new data into existing 'expenses' DataFrame in session_state
st.session_state['expenses'] = pd.concat([st.session_state['expenses'], new_data], ignore_index=True)
# Save the updated 'expenses' DataFrame to HuggingFace storage
save_data(st.session_state['expenses'])
# Display a success message to the user after successful upload
st.success("CSV file successfully uploaded!")
# Mark the file as processed, so that when page refreshes this block of code does not run again
st.session_state['file_processed'] = True
else:
#Show an error if the CSV columns do not match the expected format
st.error(f"Invalid CSV format. Expected columns: {expected_columns}")
except Exception as e:
# Handle any errors in reading the CSV file
st.error(f"Error uploading file: {e}")
# PART 5
# Button to trigger data visualisation
viz_button = st.button("Visualise Data")
if viz_button:
# Check again if there are any expenses before visualising
if not st.session_state['expenses'].empty:
# Display a summary of expenses by category
st.subheader("Expense Summary")
# Group by 'Category' and sum the 'Amount'
category_summary = st.session_state['expenses'].groupby('Category')['Amount'].sum().reset_index()
# Generate a colour palette with Seaborn
palette = sns.color_palette("colorblind", len(category_summary))
# deep, muted, bright, dark, colorblind, coolwarm
# Create a bar plot for total expenses by Category
fig, ax = plt.subplots(figsize=(10,6))
sns.barplot(y='Category', x='Amount', data=category_summary, ax=ax, palette=palette) # Horizontal bar plot
ax.set_title("Total Expenses by Category", pad=20) # Title for the bar plot
ax.set_xlabel("Amount Spent (£)", labelpad=15) # X-axis label
# Remove the Y-Axis label
ax.set_ylabel('')
# Adding labels to each bar
for index, value in enumerate(category_summary['Amount']):
ax.text(value + 0.05, index, f'{value:.2f}', va='center')
# Show the plot
st.pyplot(fig)
else:
# Message displayed when there is no data to visualise
st.write("No data to visualise.")