forked from techwithtim/AutomateFinancesWithPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
140 lines (111 loc) · 5.38 KB
/
main.py
File metadata and controls
140 lines (111 loc) · 5.38 KB
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
import streamlit as st
import pandas as pd
import plotly.express as px
import json
import os
st.set_page_config(page_title="Simple Finance App", page_icon="💰", layout="wide")
category_file = "categories.json"
if "categories" not in st.session_state:
st.session_state.categories = {
"Uncategorized": [],
}
if os.path.exists(category_file):
with open(category_file, "r") as f:
st.session_state.categories = json.load(f)
def save_categories():
with open(category_file, "w") as f:
json.dump(st.session_state.categories, f)
def categorize_transactions(df):
df["Category"] = "Uncategorized"
for category, keywords in st.session_state.categories.items():
if category == "Uncategorized" or not keywords:
continue
lowered_keywords = [keyword.lower().strip() for keyword in keywords]
for idx, row in df.iterrows():
details = row["Details"].lower().strip()
if details in lowered_keywords:
df.at[idx, "Category"] = category
return df
def load_transactions(file):
try:
df = pd.read_csv(file)
df.columns = [col.strip() for col in df.columns]
df["Amount"] = df["Amount"].str.replace(",", "").astype(float)
df["Date"] = pd.to_datetime(df["Date"], format="%d %b %Y")
return categorize_transactions(df)
except Exception as e:
st.error(f"Error processing file: {str(e)}")
return None
def add_keyword_to_category(category, keyword):
keyword = keyword.strip()
if keyword and keyword not in st.session_state.categories[category]:
st.session_state.categories[category].append(keyword)
save_categories()
return True
return False
def main():
st.title("Simple Finance Dashboard")
uploaded_file = st.file_uploader("Upload your transaction CSV file", type=["csv"])
if uploaded_file is not None:
df = load_transactions(uploaded_file)
if df is not None:
debits_df = df[df["Debit/Credit"] == "Debit"].copy()
credits_df = df[df["Debit/Credit"] == "Credit"].copy()
st.session_state.debits_df = debits_df.copy()
tab1, tab2 = st.tabs(["Expenses (Debits)", "Payments (Credits)"])
with tab1:
new_category = st.text_input("New Category Name")
add_button = st.button("Add Category")
if add_button and new_category:
if new_category not in st.session_state.categories:
st.session_state.categories[new_category] = []
save_categories()
st.rerun()
st.subheader("Your Expenses")
edited_df = st.data_editor(
st.session_state.debits_df[["Date", "Details", "Amount", "Category"]],
column_config={
"Date": st.column_config.DateColumn("Date", format="DD/MM/YYYY"),
"Amount": st.column_config.NumberColumn("Amount", format="%.2f AED"),
"Category": st.column_config.SelectboxColumn(
"Category",
options=list(st.session_state.categories.keys())
)
},
hide_index=True,
use_container_width=True,
key="category_editor"
)
save_button = st.button("Apply Changes", type="primary")
if save_button:
for idx, row in edited_df.iterrows():
new_category = row["Category"]
if new_category == st.session_state.debits_df.at[idx, "Category"]:
continue
details = row["Details"]
st.session_state.debits_df.at[idx, "Category"] = new_category
add_keyword_to_category(new_category, details)
st.subheader('Expense Summary')
category_totals = st.session_state.debits_df.groupby("Category")["Amount"].sum().reset_index()
category_totals = category_totals.sort_values("Amount", ascending=False)
st.dataframe(
category_totals,
column_config={
"Amount": st.column_config.NumberColumn("Amount", format="%.2f AED")
},
use_container_width=True,
hide_index=True
)
fig = px.pie(
category_totals,
values="Amount",
names="Category",
title="Expenses by Category"
)
st.plotly_chart(fig, use_container_width=True)
with tab2:
st.subheader("Payments Summary")
total_payments = credits_df["Amount"].sum()
st.metric("Total Payments", f"{total_payments:,.2f} AED")
st.write(credits_df)
main()