File size: 6,055 Bytes
ea092b2
bea3054
0282c8a
 
 
be99ccf
ea092b2
 
 
 
 
0282c8a
ea092b2
 
f2bbca4
70983c9
71ed5f5
45c3566
f2bbca4
71ed5f5
70983c9
 
 
71ed5f5
f2bbca4
1e4ae0c
71ed5f5
f2bbca4
e92de2f
71ed5f5
f2bbca4
71ed5f5
70983c9
 
 
71ed5f5
f2bbca4
71ed5f5
f2bbca4
b22966e
0bf6dd7
4d24001
71ed5f5
 
 
 
45c3566
b5cdbe6
d8b4b29
 
 
 
 
 
 
3f0f952
d8b4b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5cdbe6
 
 
d8b4b29
b5cdbe6
 
ea092b2
b5cdbe6
 
ea092b2
b5cdbe6
 
ea092b2
b5cdbe6
 
 
e92de2f
f2bbca4
 
 
b5cdbe6
 
 
 
69d8976
f2bbca4
b5cdbe6
 
4d24001
45c3566
b5cdbe6
 
 
 
 
 
 
 
 
4002895
b5cdbe6
 
ea092b2
b5cdbe6
 
71ed5f5
b5cdbe6
 
f2bbca4
b5cdbe6
 
f2bbca4
b5cdbe6
 
f2bbca4
b5cdbe6
 
 
f2bbca4
b5cdbe6
 
 
1912d6a
b5cdbe6
f2bbca4
ea092b2
 
b5cdbe6
f2bbca4
1912d6a
 
 
f2bbca4
bc4da5c
f2bbca4
 
bc4da5c
f2bbca4
 
bc4da5c
f2bbca4
7252795
2ef0be6
b5cdbe6
b57228e
f2bbca4
6a8b35a
b57228e
6a8b35a
 
b57228e
 
 
7b4fb97
 
 
6a8b35a
f2bbca4
 
bc4da5c
c7c1a71
b5cdbe6
1912d6a
f2bbca4
1912d6a
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# 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.")