File size: 5,153 Bytes
bea3054
0282c8a
 
ce4ea49
0282c8a
d0b2014
0282c8a
70983c9
71ed5f5
 
70983c9
 
 
71ed5f5
1e4ae0c
71ed5f5
e92de2f
71ed5f5
 
70983c9
 
 
71ed5f5
 
4d24001
71ed5f5
 
 
 
2fb3cdb
70983c9
 
 
 
568d365
e92de2f
568d365
 
498d547
 
 
70983c9
498d547
4d24001
568d365
4d24001
c4cdec2
c672be8
 
c4cdec2
71ed5f5
0282c8a
 
71ed5f5
6be623c
71ed5f5
 
 
 
 
 
d4472c1
71ed5f5
 
 
 
 
 
 
 
 
 
bc4da5c
1912d6a
 
 
 
 
 
 
 
 
 
 
0a9fa4c
dca75e9
 
 
0a9fa4c
 
1912d6a
 
 
 
bc4da5c
 
77b9587
bc4da5c
 
 
6a8b35a
7b4fb97
6a8b35a
 
7b4fb97
 
 
6a8b35a
7b4fb97
bc4da5c
c7c1a71
bc4da5c
7b4fb97
 
8d2602b
ce4ea49
 
 
 
 
 
 
 
8d2602b
6a8b35a
ce4ea49
 
5bfa5d8
7b4fb97
ce4ea49
 
 
 
7b4fb97
ce4ea49
6a8b35a
 
71ed5f5
20e874b
71ed5f5
1912d6a
 
498d547
 
71ed5f5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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.")