import streamlit as st import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates import seaborn as sns import os DATA_FILE = 'expenses.csv' 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: return pd.read_csv(DATA_FILE) except FileNotFoundError: 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) # Initialize session state if 'expenses' not in st.session_state: st.session_state['expenses'] = load_data() # Add categories as required (TO-DO: Add input to append to this list? Might be too complicated for 30 minutes) categories = ['Food', 'Transport', 'Bills', 'Entertainment', 'Other'] # Upload file from computer and not HuggingFace uploaded_file = st.file_uploader("Import Data") if uploaded_file is not None: # Check the file type based on the MIME type if uploaded_file.name.endswith('.csv'): st.session_state['expenses'] = pd.read_csv(uploaded_file) st.session_state['expenses']['Date'] = pd.to_datetime(st.session_state['expenses']['Date']) # Ensure 'Date' is datetime save_data(st.session_state['expenses']) # Ensures the HuggingFace storage contains this version st.success("CSV file successfully uploaded!") else: st.error("File type is not supported. Please upload a CSV file.") rerun_button = st.button("Rerun") if rerun_button: st.rerun() st.title("Expense Tracker") with st.form("expense_form"): amount = st.number_input("Amount", format="%0.2f", min_value=0.01) category = st.selectbox("Category", categories) description = st.text_input("Description") date = st.date_input("Date") submit = st.form_submit_button("Add Expense") if submit: new_expense = pd.DataFrame({ 'Date': [date], 'Category': [category], 'Amount': [amount], 'Description': [description] }) st.session_state['expenses'] = pd.concat([st.session_state['expenses'], new_expense], ignore_index=True) save_data(st.session_state['expenses']) # Save data after adding a new expense, maybe better to have button for saving data? st.success("Expense added successfully!") csv = st.session_state['expenses'].to_csv(index=False).encode("utf-8") st.download_button( label = "Download Expenses as CSV", data = csv, file_name = "expenses.csv", mime = "text/csv" ) if not st.session_state['expenses'].empty: st.subheader("Current Expenses") display_df = st.session_state['expenses'].copy() display_df['Date'] = display_df['Date'].astype(str) st.dataframe(display_df) else: st.write("No expenses yet.") viz_button = st.button("Visualise Data") if viz_button: if not st.session_state['expenses'].empty: st.subheader("Expense Summary") category_summary = st.session_state['expenses'].groupby('Category')['Amount'].sum().reset_index() fig, ax = plt.subplots(figsize=(10,6)) sns.barplot(y='Category', x='Amount', data=category_summary, ax=ax) # 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 # Adding labels to each bar for index, value in enumerate(category_summary['Amount']): ax.text(value + 0.05, index, f'{value:.2f}', va='center') st.pyplot(fig) # Expenses Over Time Line Chart with Title, Labels, and Point Labels st.subheader("Expenses Over Time") # Ensure 'Date' is a datetime st.session_state['expenses']['Date'] = pd.to_datetime(st.session_state['expenses']['Date']) # Create a new DataFrame for monthly aggregation monthly_expenses = st.session_state['expenses'].copy() monthly_expenses['Month_Year'] = monthly_expenses['Date'].dt.to_period('M') monthly_summary = monthly_expenses.groupby('Month_Year')['Amount'].sum().reset_index() monthly_summary['Month_Year'] = monthly_summary['Month_Year'].dt.to_timestamp() # Convert back to timestamp for plotting fig, ax = plt.subplots(figsize=(10,6)) ax.plot(monthly_summary['Month_Year'], monthly_summary['Amount'], marker='o') ax.set_title("Monthly Expenses Over Time", pad=20) # Title for the line chart ax.set_ylabel("Amount Spent (£)", labelpad=15) # Y-axis label # Formatting the x-axis to show Month-Year ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) plt.xticks(rotation=45) # Adding labels to each point for date, amount in zip(monthly_summary['Month_Year'], monthly_summary['Amount']): ax.text(date, amount + 0.05, f'{amount:.2f}', ha='right') st.pyplot(fig) else: st.write("No data to visualise.")