Upload 7 files
Browse files- .replit +36 -0
- app.py +841 -0
- budgets.csv +2 -0
- expenses.csv +2 -0
- pyproject.toml +10 -0
- replit.md +70 -0
- uv.lock +0 -0
.replit
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
modules = ["python-3.11"]
|
| 2 |
+
|
| 3 |
+
[nix]
|
| 4 |
+
channel = "stable-25_05"
|
| 5 |
+
|
| 6 |
+
[deployment]
|
| 7 |
+
deploymentTarget = "autoscale"
|
| 8 |
+
run = ["streamlit", "run", "app.py", "--server.port", "5000"]
|
| 9 |
+
|
| 10 |
+
[workflows]
|
| 11 |
+
runButton = "Project"
|
| 12 |
+
|
| 13 |
+
[[workflows.workflow]]
|
| 14 |
+
name = "Project"
|
| 15 |
+
mode = "parallel"
|
| 16 |
+
author = "agent"
|
| 17 |
+
|
| 18 |
+
[[workflows.workflow.tasks]]
|
| 19 |
+
task = "workflow.run"
|
| 20 |
+
args = "Server"
|
| 21 |
+
|
| 22 |
+
[[workflows.workflow]]
|
| 23 |
+
name = "Server"
|
| 24 |
+
author = "agent"
|
| 25 |
+
|
| 26 |
+
[[workflows.workflow.tasks]]
|
| 27 |
+
task = "shell.exec"
|
| 28 |
+
args = "streamlit run app.py --server.port 5000"
|
| 29 |
+
waitForPort = 5000
|
| 30 |
+
|
| 31 |
+
[workflows.workflow.metadata]
|
| 32 |
+
outputType = "webview"
|
| 33 |
+
|
| 34 |
+
[[ports]]
|
| 35 |
+
localPort = 5000
|
| 36 |
+
externalPort = 80
|
app.py
ADDED
|
@@ -0,0 +1,841 @@
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ime import datetime, timedelta
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Page configuration
|
| 8 |
+
st.set_page_config(
|
| 9 |
+
page_title="College Expense Tracker",
|
| 10 |
+
page_icon="💰",
|
| 11 |
+
layout="wide"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# Initialize session state
|
| 15 |
+
if 'expenses_df' not in st.session_state:
|
| 16 |
+
st.session_state.expenses_df = pd.DataFrame()
|
| 17 |
+
|
| 18 |
+
if 'monthly_budgets_df' not in st.session_state:
|
| 19 |
+
st.session_state.monthly_budgets_df = pd.DataFrame()
|
| 20 |
+
|
| 21 |
+
# Load data from CSV if exists
|
| 22 |
+
@st.cache_data
|
| 23 |
+
def load_expenses():
|
| 24 |
+
if os.path.exists('expenses.csv'):
|
| 25 |
+
try:
|
| 26 |
+
df = pd.read_csv('expenses.csv')
|
| 27 |
+
return df
|
| 28 |
+
except Exception as e:
|
| 29 |
+
st.error(f"Error loading expenses: {e}")
|
| 30 |
+
return pd.DataFrame()
|
| 31 |
+
else:
|
| 32 |
+
return pd.DataFrame()
|
| 33 |
+
|
| 34 |
+
# Save data to CSV
|
| 35 |
+
def save_expenses(df):
|
| 36 |
+
try:
|
| 37 |
+
df.to_csv('expenses.csv', index=False)
|
| 38 |
+
return True
|
| 39 |
+
except Exception as e:
|
| 40 |
+
st.error(f"Error saving expenses: {e}")
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
# Load monthly budgets from CSV (no cache to ensure fresh data)
|
| 44 |
+
def load_monthly_budgets():
|
| 45 |
+
if os.path.exists('budgets.csv'):
|
| 46 |
+
try:
|
| 47 |
+
df = pd.read_csv('budgets.csv')
|
| 48 |
+
return df
|
| 49 |
+
except Exception as e:
|
| 50 |
+
st.error(f"Error loading budgets: {e}")
|
| 51 |
+
return pd.DataFrame()
|
| 52 |
+
else:
|
| 53 |
+
return pd.DataFrame()
|
| 54 |
+
|
| 55 |
+
# Save monthly budgets to CSV
|
| 56 |
+
def save_monthly_budgets(df):
|
| 57 |
+
try:
|
| 58 |
+
df.to_csv('budgets.csv', index=False)
|
| 59 |
+
return True
|
| 60 |
+
except Exception as e:
|
| 61 |
+
st.error(f"Error saving budgets: {e}")
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
# Load expenses on app start
|
| 65 |
+
if st.session_state.expenses_df.empty:
|
| 66 |
+
st.session_state.expenses_df = load_expenses()
|
| 67 |
+
|
| 68 |
+
# Load monthly budgets on app start
|
| 69 |
+
if st.session_state.monthly_budgets_df.empty:
|
| 70 |
+
st.session_state.monthly_budgets_df = load_monthly_budgets()
|
| 71 |
+
|
| 72 |
+
# Format date based on granularity
|
| 73 |
+
def format_date_by_granularity(date, granularity):
|
| 74 |
+
if granularity == "Daily":
|
| 75 |
+
return date.strftime("%Y-%m-%d")
|
| 76 |
+
elif granularity == "Weekly":
|
| 77 |
+
# Get ISO week number
|
| 78 |
+
year, week, _ = date.isocalendar()
|
| 79 |
+
return f"{year}-W{week:02d}"
|
| 80 |
+
elif granularity == "Monthly":
|
| 81 |
+
return date.strftime("%Y-%m")
|
| 82 |
+
|
| 83 |
+
# Main app title
|
| 84 |
+
st.title("💰 College Expense Tracker")
|
| 85 |
+
|
| 86 |
+
# Create tabs
|
| 87 |
+
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs(["Add Expense", "View Expenses", "Summary", "Graph", "Trends", "Budget", "Monthly Budget", "Monthly Expense Sheet"])
|
| 88 |
+
|
| 89 |
+
# Tab 1: Add Expense
|
| 90 |
+
with tab1:
|
| 91 |
+
st.header("Add New Expense")
|
| 92 |
+
|
| 93 |
+
col1, col2 = st.columns(2)
|
| 94 |
+
|
| 95 |
+
with col1:
|
| 96 |
+
# Category selection
|
| 97 |
+
categories = ["Food", "Transport", "Stationery", "Entertainment", "Others"]
|
| 98 |
+
category = st.selectbox("Category", categories)
|
| 99 |
+
|
| 100 |
+
# Amount input
|
| 101 |
+
amount = st.number_input("Amount (₹)", min_value=0.01, step=0.01, format="%.2f")
|
| 102 |
+
|
| 103 |
+
with col2:
|
| 104 |
+
# Granularity selector
|
| 105 |
+
granularity = st.selectbox("Time Granularity", ["Daily", "Weekly", "Monthly"])
|
| 106 |
+
|
| 107 |
+
# Date input with today as default
|
| 108 |
+
selected_date = st.date_input("Date", value=datetime.now().date())
|
| 109 |
+
|
| 110 |
+
# Add expense button
|
| 111 |
+
if st.button("Add Expense", type="primary"):
|
| 112 |
+
if amount > 0:
|
| 113 |
+
# Format date based on granularity
|
| 114 |
+
formatted_date = format_date_by_granularity(selected_date, granularity)
|
| 115 |
+
|
| 116 |
+
# Create new expense record
|
| 117 |
+
new_expense = {
|
| 118 |
+
'Category': category,
|
| 119 |
+
'Amount': amount,
|
| 120 |
+
'Granularity': granularity,
|
| 121 |
+
'Date': formatted_date,
|
| 122 |
+
'Raw_Date': selected_date.strftime("%Y-%m-%d")
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
# Add to dataframe using loc
|
| 126 |
+
if st.session_state.expenses_df.empty:
|
| 127 |
+
st.session_state.expenses_df = pd.DataFrame([new_expense])
|
| 128 |
+
else:
|
| 129 |
+
st.session_state.expenses_df.loc[len(st.session_state.expenses_df)] = new_expense
|
| 130 |
+
|
| 131 |
+
# Save to CSV
|
| 132 |
+
if save_expenses(st.session_state.expenses_df):
|
| 133 |
+
st.success(f"✅ Added {category}: ₹{amount:.2f} for {formatted_date} ({granularity})")
|
| 134 |
+
st.rerun()
|
| 135 |
+
else:
|
| 136 |
+
st.error("Please enter a valid amount greater than 0")
|
| 137 |
+
|
| 138 |
+
# Tab 2: View Expenses
|
| 139 |
+
with tab2:
|
| 140 |
+
st.header("All Expenses")
|
| 141 |
+
|
| 142 |
+
if not st.session_state.expenses_df.empty:
|
| 143 |
+
# Date range filter
|
| 144 |
+
st.subheader("Filter by Date Range")
|
| 145 |
+
col1, col2, col3 = st.columns([2, 2, 1])
|
| 146 |
+
|
| 147 |
+
with col1:
|
| 148 |
+
# Get min and max dates from data
|
| 149 |
+
min_date = pd.to_datetime(st.session_state.expenses_df['Raw_Date']).min().date()
|
| 150 |
+
max_date = pd.to_datetime(st.session_state.expenses_df['Raw_Date']).max().date()
|
| 151 |
+
start_date = st.date_input("Start Date", value=min_date, min_value=min_date, max_value=max_date)
|
| 152 |
+
|
| 153 |
+
with col2:
|
| 154 |
+
end_date = st.date_input("End Date", value=max_date, min_value=min_date, max_value=max_date)
|
| 155 |
+
|
| 156 |
+
with col3:
|
| 157 |
+
apply_filter = st.button("Apply Filter", type="primary")
|
| 158 |
+
clear_filter = st.button("Clear Filter")
|
| 159 |
+
|
| 160 |
+
# Filter data based on date range
|
| 161 |
+
filtered_df = st.session_state.expenses_df.copy()
|
| 162 |
+
|
| 163 |
+
if apply_filter or 'date_filter_active' in st.session_state:
|
| 164 |
+
if apply_filter:
|
| 165 |
+
st.session_state.date_filter_active = True
|
| 166 |
+
st.session_state.filter_start = start_date
|
| 167 |
+
st.session_state.filter_end = end_date
|
| 168 |
+
|
| 169 |
+
if 'date_filter_active' in st.session_state and st.session_state.date_filter_active:
|
| 170 |
+
start = st.session_state.filter_start
|
| 171 |
+
end = st.session_state.filter_end
|
| 172 |
+
|
| 173 |
+
# Filter using Raw_Date column
|
| 174 |
+
filtered_df = filtered_df[
|
| 175 |
+
(pd.to_datetime(filtered_df['Raw_Date']).dt.date >= start) &
|
| 176 |
+
(pd.to_datetime(filtered_df['Raw_Date']).dt.date <= end)
|
| 177 |
+
]
|
| 178 |
+
st.info(f"Showing expenses from {start} to {end} ({len(filtered_df)} entries)")
|
| 179 |
+
|
| 180 |
+
if clear_filter:
|
| 181 |
+
st.session_state.date_filter_active = False
|
| 182 |
+
st.rerun()
|
| 183 |
+
|
| 184 |
+
# Display expenses table with edit/delete options
|
| 185 |
+
if not filtered_df.empty:
|
| 186 |
+
st.subheader("Expense List")
|
| 187 |
+
|
| 188 |
+
# Display each expense with edit/delete buttons
|
| 189 |
+
for idx in filtered_df.index:
|
| 190 |
+
expense = filtered_df.loc[idx]
|
| 191 |
+
|
| 192 |
+
col1, col2, col3, col4, col5, col6, col7 = st.columns([2, 1.5, 1.5, 1.5, 1.5, 0.8, 0.8])
|
| 193 |
+
|
| 194 |
+
with col1:
|
| 195 |
+
st.text(f"{expense['Category']}")
|
| 196 |
+
with col2:
|
| 197 |
+
st.text(f"₹{expense['Amount']:.2f}")
|
| 198 |
+
with col3:
|
| 199 |
+
st.text(f"{expense['Granularity']}")
|
| 200 |
+
with col4:
|
| 201 |
+
st.text(f"{expense['Date']}")
|
| 202 |
+
with col5:
|
| 203 |
+
st.text(f"{expense['Raw_Date']}")
|
| 204 |
+
with col6:
|
| 205 |
+
if st.button("✏️", key=f"edit_{idx}"):
|
| 206 |
+
st.session_state.editing_index = idx
|
| 207 |
+
st.rerun()
|
| 208 |
+
with col7:
|
| 209 |
+
if st.button("🗑️", key=f"delete_{idx}"):
|
| 210 |
+
st.session_state.deleting_index = idx
|
| 211 |
+
st.rerun()
|
| 212 |
+
|
| 213 |
+
# Edit expense dialog
|
| 214 |
+
if 'editing_index' in st.session_state:
|
| 215 |
+
idx = st.session_state.editing_index
|
| 216 |
+
expense = st.session_state.expenses_df.loc[idx]
|
| 217 |
+
|
| 218 |
+
st.markdown("---")
|
| 219 |
+
st.subheader("Edit Expense")
|
| 220 |
+
|
| 221 |
+
col1, col2 = st.columns(2)
|
| 222 |
+
|
| 223 |
+
with col1:
|
| 224 |
+
edit_category = st.selectbox("Category", ["Food", "Transport", "Stationery", "Entertainment", "Others"],
|
| 225 |
+
index=["Food", "Transport", "Stationery", "Entertainment", "Others"].index(expense['Category']),
|
| 226 |
+
key=f"edit_category_{idx}")
|
| 227 |
+
edit_amount = st.number_input("Amount (₹)", value=float(expense['Amount']), min_value=0.01, step=0.01, format="%.2f", key=f"edit_amount_{idx}")
|
| 228 |
+
|
| 229 |
+
with col2:
|
| 230 |
+
edit_granularity = st.selectbox("Time Granularity", ["Daily", "Weekly", "Monthly"],
|
| 231 |
+
index=["Daily", "Weekly", "Monthly"].index(expense['Granularity']),
|
| 232 |
+
key=f"edit_granularity_{idx}")
|
| 233 |
+
edit_date = st.date_input("Date", value=pd.to_datetime(expense['Raw_Date']).date(), key=f"edit_date_{idx}")
|
| 234 |
+
|
| 235 |
+
col1, col2 = st.columns(2)
|
| 236 |
+
with col1:
|
| 237 |
+
if st.button("Save Changes", type="primary", key=f"save_{idx}"):
|
| 238 |
+
# Update the expense
|
| 239 |
+
formatted_date = format_date_by_granularity(edit_date, edit_granularity)
|
| 240 |
+
st.session_state.expenses_df.loc[idx, 'Category'] = edit_category
|
| 241 |
+
st.session_state.expenses_df.loc[idx, 'Amount'] = edit_amount
|
| 242 |
+
st.session_state.expenses_df.loc[idx, 'Granularity'] = edit_granularity
|
| 243 |
+
st.session_state.expenses_df.loc[idx, 'Date'] = formatted_date
|
| 244 |
+
st.session_state.expenses_df.loc[idx, 'Raw_Date'] = edit_date.strftime("%Y-%m-%d")
|
| 245 |
+
|
| 246 |
+
save_expenses(st.session_state.expenses_df)
|
| 247 |
+
del st.session_state.editing_index
|
| 248 |
+
st.success("✅ Expense updated successfully!")
|
| 249 |
+
st.rerun()
|
| 250 |
+
|
| 251 |
+
with col2:
|
| 252 |
+
if st.button("Cancel", type="secondary", key=f"cancel_edit_{idx}"):
|
| 253 |
+
del st.session_state.editing_index
|
| 254 |
+
st.rerun()
|
| 255 |
+
|
| 256 |
+
# Delete confirmation dialog
|
| 257 |
+
if 'deleting_index' in st.session_state:
|
| 258 |
+
idx = st.session_state.deleting_index
|
| 259 |
+
expense = st.session_state.expenses_df.loc[idx]
|
| 260 |
+
|
| 261 |
+
st.markdown("---")
|
| 262 |
+
st.warning(f"⚠️ Are you sure you want to delete this expense?\n\n**{expense['Category']}**: ₹{expense['Amount']:.2f} on {expense['Date']}")
|
| 263 |
+
|
| 264 |
+
col1, col2 = st.columns(2)
|
| 265 |
+
with col1:
|
| 266 |
+
if st.button("Yes, Delete", type="primary"):
|
| 267 |
+
st.session_state.expenses_df = st.session_state.expenses_df.drop(idx).reset_index(drop=True)
|
| 268 |
+
save_expenses(st.session_state.expenses_df)
|
| 269 |
+
del st.session_state.deleting_index
|
| 270 |
+
st.success("✅ Expense deleted successfully!")
|
| 271 |
+
st.rerun()
|
| 272 |
+
|
| 273 |
+
with col2:
|
| 274 |
+
if st.button("Cancel", type="secondary", key="cancel_delete"):
|
| 275 |
+
del st.session_state.deleting_index
|
| 276 |
+
st.rerun()
|
| 277 |
+
else:
|
| 278 |
+
st.warning("No expenses found in the selected date range.")
|
| 279 |
+
|
| 280 |
+
# Export functionality
|
| 281 |
+
st.markdown("---")
|
| 282 |
+
st.subheader("Export Data")
|
| 283 |
+
|
| 284 |
+
col1, col2 = st.columns(2)
|
| 285 |
+
|
| 286 |
+
with col1:
|
| 287 |
+
# Export filtered data
|
| 288 |
+
if not filtered_df.empty:
|
| 289 |
+
csv_data = filtered_df.to_csv(index=False)
|
| 290 |
+
st.download_button(
|
| 291 |
+
label="📥 Download Filtered Data (CSV)",
|
| 292 |
+
data=csv_data,
|
| 293 |
+
file_name=f"expenses_filtered_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
| 294 |
+
mime="text/csv",
|
| 295 |
+
type="primary"
|
| 296 |
+
)
|
| 297 |
+
else:
|
| 298 |
+
st.button("📥 Download Filtered Data (CSV)", disabled=True, type="primary")
|
| 299 |
+
|
| 300 |
+
with col2:
|
| 301 |
+
# Export all data
|
| 302 |
+
csv_all = st.session_state.expenses_df.to_csv(index=False)
|
| 303 |
+
st.download_button(
|
| 304 |
+
label="📥 Download All Data (CSV)",
|
| 305 |
+
data=csv_all,
|
| 306 |
+
file_name=f"expenses_all_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
| 307 |
+
mime="text/csv",
|
| 308 |
+
type="secondary"
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# Option to clear all expenses
|
| 312 |
+
st.markdown("---")
|
| 313 |
+
if st.button("Clear All Expenses", type="secondary"):
|
| 314 |
+
st.session_state.expenses_df = pd.DataFrame()
|
| 315 |
+
if os.path.exists('expenses.csv'):
|
| 316 |
+
os.remove('expenses.csv')
|
| 317 |
+
st.success("All expenses cleared!")
|
| 318 |
+
st.rerun()
|
| 319 |
+
else:
|
| 320 |
+
st.info("No expenses recorded yet. Add some expenses to see them here!")
|
| 321 |
+
|
| 322 |
+
# Tab 3: Summary
|
| 323 |
+
with tab3:
|
| 324 |
+
st.header("Expense Summary")
|
| 325 |
+
|
| 326 |
+
if not st.session_state.expenses_df.empty:
|
| 327 |
+
# Total spent
|
| 328 |
+
total_spent = st.session_state.expenses_df['Amount'].sum()
|
| 329 |
+
st.metric("Total Spent", f"₹{total_spent:.2f}")
|
| 330 |
+
|
| 331 |
+
st.subheader("Category-wise Breakdown")
|
| 332 |
+
|
| 333 |
+
# Category-wise summary
|
| 334 |
+
category_summary = st.session_state.expenses_df.groupby('Category')['Amount'].agg(['sum', 'count']).reset_index()
|
| 335 |
+
category_summary.columns = ['Category', 'Total Amount', 'Number of Transactions']
|
| 336 |
+
category_summary['Total Amount'] = category_summary['Total Amount'].apply(lambda x: f"₹{x:.2f}")
|
| 337 |
+
|
| 338 |
+
st.dataframe(
|
| 339 |
+
category_summary,
|
| 340 |
+
use_container_width=True,
|
| 341 |
+
hide_index=True
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
# Display totals clearly
|
| 345 |
+
st.subheader("Clear Totals")
|
| 346 |
+
col1, col2, col3 = st.columns(3)
|
| 347 |
+
|
| 348 |
+
with col1:
|
| 349 |
+
st.metric("Food", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Food']['Amount'].sum():.2f}")
|
| 350 |
+
|
| 351 |
+
with col2:
|
| 352 |
+
st.metric("Transport", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Transport']['Amount'].sum():.2f}")
|
| 353 |
+
|
| 354 |
+
with col3:
|
| 355 |
+
st.metric("Entertainment", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Entertainment']['Amount'].sum():.2f}")
|
| 356 |
+
|
| 357 |
+
col4, col5 = st.columns(2)
|
| 358 |
+
|
| 359 |
+
with col4:
|
| 360 |
+
st.metric("Stationery", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Stationery']['Amount'].sum():.2f}")
|
| 361 |
+
|
| 362 |
+
with col5:
|
| 363 |
+
st.metric("Others", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Others']['Amount'].sum():.2f}")
|
| 364 |
+
|
| 365 |
+
else:
|
| 366 |
+
st.info("No expenses recorded yet. Add some expenses to see the summary!")
|
| 367 |
+
|
| 368 |
+
# Tab 4: Graph
|
| 369 |
+
with tab4:
|
| 370 |
+
st.header("Expense Visualization")
|
| 371 |
+
|
| 372 |
+
if not st.session_state.expenses_df.empty:
|
| 373 |
+
# Category totals for bar chart
|
| 374 |
+
category_totals = st.session_state.expenses_df.groupby('Category')['Amount'].sum().reset_index()
|
| 375 |
+
category_totals = category_totals.sort_values('Amount', ascending=False)
|
| 376 |
+
|
| 377 |
+
# Create bar chart
|
| 378 |
+
fig = px.bar(
|
| 379 |
+
category_totals,
|
| 380 |
+
x='Category',
|
| 381 |
+
y='Amount',
|
| 382 |
+
title='Category-wise Expense Distribution',
|
| 383 |
+
labels={'Amount': 'Amount (₹)', 'Category': 'Expense Category'},
|
| 384 |
+
color='Amount',
|
| 385 |
+
color_continuous_scale='viridis'
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
# Update layout
|
| 389 |
+
fig.update_layout(
|
| 390 |
+
showlegend=False,
|
| 391 |
+
height=500,
|
| 392 |
+
title_x=0.5
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
# Display chart
|
| 396 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 397 |
+
|
| 398 |
+
# Additional insights
|
| 399 |
+
st.subheader("Quick Insights")
|
| 400 |
+
|
| 401 |
+
if len(category_totals) > 0:
|
| 402 |
+
highest_category = category_totals.iloc[0]
|
| 403 |
+
lowest_category = category_totals.iloc[-1]
|
| 404 |
+
|
| 405 |
+
col1, col2 = st.columns(2)
|
| 406 |
+
|
| 407 |
+
with col1:
|
| 408 |
+
st.info(f"💸 Highest spending: **{highest_category['Category']}** (₹{highest_category['Amount']:.2f})")
|
| 409 |
+
|
| 410 |
+
with col2:
|
| 411 |
+
st.info(f"💡 Lowest spending: **{lowest_category['Category']}** (₹{lowest_category['Amount']:.2f})")
|
| 412 |
+
|
| 413 |
+
else:
|
| 414 |
+
st.info("No expenses recorded yet. Add some expenses to see the visualization!")
|
| 415 |
+
|
| 416 |
+
# Tab 5: Trends
|
| 417 |
+
with tab5:
|
| 418 |
+
st.header("Spending Trends Over Time")
|
| 419 |
+
|
| 420 |
+
if not st.session_state.expenses_df.empty:
|
| 421 |
+
# Create a copy with datetime column
|
| 422 |
+
trend_df = st.session_state.expenses_df.copy()
|
| 423 |
+
trend_df['Date_dt'] = pd.to_datetime(trend_df['Raw_Date'])
|
| 424 |
+
trend_df = trend_df.sort_values('Date_dt')
|
| 425 |
+
|
| 426 |
+
# View options
|
| 427 |
+
view_option = st.radio("View by:", ["Total Spending", "Category-wise"], horizontal=True)
|
| 428 |
+
|
| 429 |
+
if view_option == "Total Spending":
|
| 430 |
+
# Aggregate by date
|
| 431 |
+
daily_spending = trend_df.groupby('Raw_Date')['Amount'].sum().reset_index()
|
| 432 |
+
daily_spending['Date_dt'] = pd.to_datetime(daily_spending['Raw_Date'])
|
| 433 |
+
daily_spending = daily_spending.sort_values('Date_dt')
|
| 434 |
+
|
| 435 |
+
# Create line chart
|
| 436 |
+
fig = px.line(
|
| 437 |
+
daily_spending,
|
| 438 |
+
x='Date_dt',
|
| 439 |
+
y='Amount',
|
| 440 |
+
title='Total Daily Spending Trend',
|
| 441 |
+
labels={'Date_dt': 'Date', 'Amount': 'Amount (₹)'},
|
| 442 |
+
markers=True
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
fig.update_layout(
|
| 446 |
+
height=500,
|
| 447 |
+
title_x=0.5,
|
| 448 |
+
xaxis_title="Date",
|
| 449 |
+
yaxis_title="Amount (₹)"
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 453 |
+
|
| 454 |
+
# Show statistics
|
| 455 |
+
col1, col2, col3 = st.columns(3)
|
| 456 |
+
with col1:
|
| 457 |
+
st.metric("Average Daily Spending", f"₹{daily_spending['Amount'].mean():.2f}")
|
| 458 |
+
with col2:
|
| 459 |
+
st.metric("Highest Day", f"₹{daily_spending['Amount'].max():.2f}")
|
| 460 |
+
with col3:
|
| 461 |
+
st.metric("Lowest Day", f"₹{daily_spending['Amount'].min():.2f}")
|
| 462 |
+
|
| 463 |
+
else: # Category-wise
|
| 464 |
+
# Category selector
|
| 465 |
+
selected_categories = st.multiselect(
|
| 466 |
+
"Select Categories to Display",
|
| 467 |
+
["Food", "Transport", "Stationery", "Entertainment", "Others"],
|
| 468 |
+
default=["Food", "Transport", "Entertainment"]
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
if selected_categories:
|
| 472 |
+
# Filter by selected categories
|
| 473 |
+
category_trend = trend_df[trend_df['Category'].isin(selected_categories)]
|
| 474 |
+
|
| 475 |
+
# Aggregate by date and category
|
| 476 |
+
category_daily = category_trend.groupby(['Raw_Date', 'Category'])['Amount'].sum().reset_index()
|
| 477 |
+
category_daily['Date_dt'] = pd.to_datetime(category_daily['Raw_Date'])
|
| 478 |
+
category_daily = category_daily.sort_values('Date_dt')
|
| 479 |
+
|
| 480 |
+
# Create multi-line chart
|
| 481 |
+
fig = px.line(
|
| 482 |
+
category_daily,
|
| 483 |
+
x='Date_dt',
|
| 484 |
+
y='Amount',
|
| 485 |
+
color='Category',
|
| 486 |
+
title='Category-wise Spending Trends',
|
| 487 |
+
labels={'Date_dt': 'Date', 'Amount': 'Amount (₹)'},
|
| 488 |
+
markers=True
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
fig.update_layout(
|
| 492 |
+
height=500,
|
| 493 |
+
title_x=0.5,
|
| 494 |
+
xaxis_title="Date",
|
| 495 |
+
yaxis_title="Amount (₹)"
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 499 |
+
|
| 500 |
+
# Show category statistics
|
| 501 |
+
st.subheader("Category Statistics")
|
| 502 |
+
for cat in selected_categories:
|
| 503 |
+
cat_data = trend_df[trend_df['Category'] == cat]
|
| 504 |
+
if not cat_data.empty:
|
| 505 |
+
col1, col2, col3 = st.columns(3)
|
| 506 |
+
with col1:
|
| 507 |
+
st.metric(f"{cat} - Total", f"₹{cat_data['Amount'].sum():.2f}")
|
| 508 |
+
with col2:
|
| 509 |
+
st.metric(f"{cat} - Average", f"₹{cat_data['Amount'].mean():.2f}")
|
| 510 |
+
with col3:
|
| 511 |
+
st.metric(f"{cat} - Count", f"{len(cat_data)} expenses")
|
| 512 |
+
else:
|
| 513 |
+
st.warning("Please select at least one category to view trends.")
|
| 514 |
+
|
| 515 |
+
# Weekly/Monthly aggregation option
|
| 516 |
+
st.markdown("---")
|
| 517 |
+
st.subheader("Aggregated View")
|
| 518 |
+
agg_period = st.selectbox("Aggregate by:", ["Week", "Month"])
|
| 519 |
+
|
| 520 |
+
if agg_period == "Week":
|
| 521 |
+
trend_df['Period'] = trend_df['Date_dt'].dt.to_period('W').astype(str)
|
| 522 |
+
else:
|
| 523 |
+
trend_df['Period'] = trend_df['Date_dt'].dt.to_period('M').astype(str)
|
| 524 |
+
|
| 525 |
+
period_spending = trend_df.groupby('Period')['Amount'].sum().reset_index()
|
| 526 |
+
|
| 527 |
+
fig = px.bar(
|
| 528 |
+
period_spending,
|
| 529 |
+
x='Period',
|
| 530 |
+
y='Amount',
|
| 531 |
+
title=f'{agg_period}ly Spending Overview',
|
| 532 |
+
labels={'Period': agg_period, 'Amount': 'Amount (₹)'},
|
| 533 |
+
color='Amount',
|
| 534 |
+
color_continuous_scale='blues'
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
fig.update_layout(
|
| 538 |
+
height=400,
|
| 539 |
+
title_x=0.5,
|
| 540 |
+
showlegend=False
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 544 |
+
|
| 545 |
+
else:
|
| 546 |
+
st.info("No expenses recorded yet. Add some expenses to see spending trends!")
|
| 547 |
+
|
| 548 |
+
# Tab 6: Budget
|
| 549 |
+
with tab6:
|
| 550 |
+
st.header("Budget Management")
|
| 551 |
+
|
| 552 |
+
# Initialize budget in session state
|
| 553 |
+
if 'budgets' not in st.session_state:
|
| 554 |
+
st.session_state.budgets = {
|
| 555 |
+
'Food': 0,
|
| 556 |
+
'Transport': 0,
|
| 557 |
+
'Stationery': 0,
|
| 558 |
+
'Entertainment': 0,
|
| 559 |
+
'Others': 0
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
# Budget setting section
|
| 563 |
+
st.subheader("Set Category Budgets")
|
| 564 |
+
st.write("Set monthly budget limits for each category. Leave at 0 to disable alerts.")
|
| 565 |
+
|
| 566 |
+
col1, col2 = st.columns(2)
|
| 567 |
+
|
| 568 |
+
with col1:
|
| 569 |
+
food_budget = st.number_input("Food Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Food']), step=100.0, key="food_budget")
|
| 570 |
+
transport_budget = st.number_input("Transport Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Transport']), step=100.0, key="transport_budget")
|
| 571 |
+
stationery_budget = st.number_input("Stationery Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Stationery']), step=100.0, key="stationery_budget")
|
| 572 |
+
|
| 573 |
+
with col2:
|
| 574 |
+
entertainment_budget = st.number_input("Entertainment Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Entertainment']), step=100.0, key="entertainment_budget")
|
| 575 |
+
others_budget = st.number_input("Others Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Others']), step=100.0, key="others_budget")
|
| 576 |
+
|
| 577 |
+
if st.button("Save Budgets", type="primary"):
|
| 578 |
+
st.session_state.budgets = {
|
| 579 |
+
'Food': food_budget,
|
| 580 |
+
'Transport': transport_budget,
|
| 581 |
+
'Stationery': stationery_budget,
|
| 582 |
+
'Entertainment': entertainment_budget,
|
| 583 |
+
'Others': others_budget
|
| 584 |
+
}
|
| 585 |
+
st.success("✅ Budgets saved successfully!")
|
| 586 |
+
st.rerun()
|
| 587 |
+
|
| 588 |
+
# Budget status and alerts
|
| 589 |
+
if not st.session_state.expenses_df.empty:
|
| 590 |
+
st.markdown("---")
|
| 591 |
+
st.subheader("Budget Status")
|
| 592 |
+
|
| 593 |
+
# Calculate current month spending
|
| 594 |
+
current_month = datetime.now().strftime("%Y-%m")
|
| 595 |
+
current_month_df = st.session_state.expenses_df[
|
| 596 |
+
st.session_state.expenses_df['Raw_Date'].str.startswith(current_month)
|
| 597 |
+
]
|
| 598 |
+
|
| 599 |
+
if not current_month_df.empty:
|
| 600 |
+
st.write(f"**Current Month:** {datetime.now().strftime('%B %Y')}")
|
| 601 |
+
|
| 602 |
+
# Check each category
|
| 603 |
+
alerts = []
|
| 604 |
+
for category in ['Food', 'Transport', 'Stationery', 'Entertainment', 'Others']:
|
| 605 |
+
budget = st.session_state.budgets[category]
|
| 606 |
+
|
| 607 |
+
if budget > 0:
|
| 608 |
+
spent = current_month_df[current_month_df['Category'] == category]['Amount'].sum()
|
| 609 |
+
remaining = budget - spent
|
| 610 |
+
percentage = (spent / budget) * 100 if budget > 0 else 0
|
| 611 |
+
|
| 612 |
+
# Create progress display
|
| 613 |
+
col1, col2 = st.columns([3, 1])
|
| 614 |
+
|
| 615 |
+
with col1:
|
| 616 |
+
st.write(f"**{category}**")
|
| 617 |
+
st.progress(min(percentage / 100, 1.0))
|
| 618 |
+
|
| 619 |
+
# Color-coded status
|
| 620 |
+
if percentage >= 100:
|
| 621 |
+
st.error(f"⚠️ Over budget by ₹{abs(remaining):.2f} ({percentage:.1f}% of budget)")
|
| 622 |
+
alerts.append(f"**{category}**: Over budget by ₹{abs(remaining):.2f}")
|
| 623 |
+
elif percentage >= 80:
|
| 624 |
+
st.warning(f"⚠️ ₹{remaining:.2f} remaining ({percentage:.1f}% used)")
|
| 625 |
+
else:
|
| 626 |
+
st.success(f"✓ ₹{remaining:.2f} remaining ({percentage:.1f}% used)")
|
| 627 |
+
|
| 628 |
+
with col2:
|
| 629 |
+
st.metric("Spent", f"₹{spent:.2f}")
|
| 630 |
+
st.metric("Budget", f"₹{budget:.2f}")
|
| 631 |
+
|
| 632 |
+
# Display alerts summary
|
| 633 |
+
if alerts:
|
| 634 |
+
st.markdown("---")
|
| 635 |
+
st.error("### 🚨 Budget Alerts")
|
| 636 |
+
for alert in alerts:
|
| 637 |
+
st.write(f"- {alert}")
|
| 638 |
+
else:
|
| 639 |
+
st.info(f"No expenses recorded for {datetime.now().strftime('%B %Y')} yet.")
|
| 640 |
+
else:
|
| 641 |
+
st.info("No expenses recorded yet. Add some expenses to see budget status!")
|
| 642 |
+
|
| 643 |
+
# Tab 7: Monthly Budget Input
|
| 644 |
+
with tab7:
|
| 645 |
+
st.header("Monthly Budget Input")
|
| 646 |
+
st.write("Set a total budget for a specific month. This budget will be compared against your total spending for that month.")
|
| 647 |
+
|
| 648 |
+
col1, col2 = st.columns(2)
|
| 649 |
+
|
| 650 |
+
with col1:
|
| 651 |
+
# Month selection
|
| 652 |
+
budget_year = st.number_input("Year", min_value=2020, max_value=2030, value=datetime.now().year, step=1, key="budget_year")
|
| 653 |
+
budget_month = st.selectbox("Month", list(range(1, 13)),
|
| 654 |
+
format_func=lambda x: datetime(2000, x, 1).strftime('%B'),
|
| 655 |
+
index=datetime.now().month - 1,
|
| 656 |
+
key="budget_month")
|
| 657 |
+
|
| 658 |
+
with col2:
|
| 659 |
+
budget_amount = st.number_input("Budget Amount (₹)", min_value=0.0, step=100.0, format="%.2f", key="budget_amount")
|
| 660 |
+
|
| 661 |
+
# Format month as YYYY-MM
|
| 662 |
+
month_key = f"{budget_year}-{budget_month:02d}"
|
| 663 |
+
|
| 664 |
+
if st.button("Save Monthly Budget", type="primary"):
|
| 665 |
+
if budget_amount > 0:
|
| 666 |
+
# Check if budget already exists for this month
|
| 667 |
+
if not st.session_state.monthly_budgets_df.empty and month_key in st.session_state.monthly_budgets_df['Month'].values:
|
| 668 |
+
# Update existing budget
|
| 669 |
+
st.session_state.monthly_budgets_df.loc[
|
| 670 |
+
st.session_state.monthly_budgets_df['Month'] == month_key, 'Budget'
|
| 671 |
+
] = budget_amount
|
| 672 |
+
st.success(f"✅ Updated budget for {month_key}: ₹{budget_amount:.2f}")
|
| 673 |
+
else:
|
| 674 |
+
# Add new budget
|
| 675 |
+
new_budget = {'Month': month_key, 'Budget': budget_amount}
|
| 676 |
+
if st.session_state.monthly_budgets_df.empty:
|
| 677 |
+
st.session_state.monthly_budgets_df = pd.DataFrame([new_budget])
|
| 678 |
+
else:
|
| 679 |
+
st.session_state.monthly_budgets_df.loc[len(st.session_state.monthly_budgets_df)] = new_budget
|
| 680 |
+
st.success(f"✅ Added budget for {month_key}: ₹{budget_amount:.2f}")
|
| 681 |
+
|
| 682 |
+
# Save to CSV
|
| 683 |
+
if save_monthly_budgets(st.session_state.monthly_budgets_df):
|
| 684 |
+
st.rerun()
|
| 685 |
+
else:
|
| 686 |
+
st.error("Failed to save budget. Please try again.")
|
| 687 |
+
else:
|
| 688 |
+
st.error("Please enter a budget amount greater than 0")
|
| 689 |
+
|
| 690 |
+
# Display saved budgets
|
| 691 |
+
if not st.session_state.monthly_budgets_df.empty:
|
| 692 |
+
st.markdown("---")
|
| 693 |
+
st.subheader("Saved Monthly Budgets")
|
| 694 |
+
|
| 695 |
+
# Sort by month
|
| 696 |
+
display_budgets = st.session_state.monthly_budgets_df.copy()
|
| 697 |
+
display_budgets = display_budgets.sort_values('Month', ascending=False)
|
| 698 |
+
display_budgets['Budget'] = display_budgets['Budget'].apply(lambda x: f"₹{x:.2f}")
|
| 699 |
+
|
| 700 |
+
st.dataframe(
|
| 701 |
+
display_budgets,
|
| 702 |
+
use_container_width=True,
|
| 703 |
+
hide_index=True
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
# Option to delete a budget
|
| 707 |
+
st.markdown("---")
|
| 708 |
+
delete_month = st.selectbox("Select month to delete",
|
| 709 |
+
st.session_state.monthly_budgets_df['Month'].values,
|
| 710 |
+
key="delete_budget_month")
|
| 711 |
+
|
| 712 |
+
if st.button("Delete Selected Budget", type="secondary"):
|
| 713 |
+
st.session_state.monthly_budgets_df = st.session_state.monthly_budgets_df[
|
| 714 |
+
st.session_state.monthly_budgets_df['Month'] != delete_month
|
| 715 |
+
].reset_index(drop=True)
|
| 716 |
+
if save_monthly_budgets(st.session_state.monthly_budgets_df):
|
| 717 |
+
st.success(f"✅ Deleted budget for {delete_month}")
|
| 718 |
+
st.rerun()
|
| 719 |
+
else:
|
| 720 |
+
st.error("Failed to delete budget. Please try again.")
|
| 721 |
+
else:
|
| 722 |
+
st.info("No monthly budgets saved yet. Add a budget above to get started!")
|
| 723 |
+
|
| 724 |
+
# Tab 8: Monthly Expense Sheet
|
| 725 |
+
with tab8:
|
| 726 |
+
st.header("Monthly Expense Sheet")
|
| 727 |
+
st.write("Compare your actual spending against your monthly budget.")
|
| 728 |
+
|
| 729 |
+
# Month selection
|
| 730 |
+
col1, col2 = st.columns(2)
|
| 731 |
+
|
| 732 |
+
with col1:
|
| 733 |
+
sheet_year = st.number_input("Year", min_value=2020, max_value=2030, value=datetime.now().year, step=1, key="sheet_year")
|
| 734 |
+
|
| 735 |
+
with col2:
|
| 736 |
+
sheet_month = st.selectbox("Month", list(range(1, 13)),
|
| 737 |
+
format_func=lambda x: datetime(2000, x, 1).strftime('%B'),
|
| 738 |
+
index=datetime.now().month - 1,
|
| 739 |
+
key="sheet_month")
|
| 740 |
+
|
| 741 |
+
# Format month as YYYY-MM
|
| 742 |
+
selected_month = f"{sheet_year}-{sheet_month:02d}"
|
| 743 |
+
month_name = datetime(sheet_year, sheet_month, 1).strftime('%B %Y')
|
| 744 |
+
|
| 745 |
+
st.markdown("---")
|
| 746 |
+
st.subheader(f"Expense Summary for {month_name}")
|
| 747 |
+
|
| 748 |
+
# Calculate total spending for selected month
|
| 749 |
+
if not st.session_state.expenses_df.empty:
|
| 750 |
+
month_expenses = st.session_state.expenses_df[
|
| 751 |
+
st.session_state.expenses_df['Raw_Date'].str.startswith(selected_month)
|
| 752 |
+
]
|
| 753 |
+
|
| 754 |
+
total_spent = month_expenses['Amount'].sum() if not month_expenses.empty else 0
|
| 755 |
+
|
| 756 |
+
# Check if budget exists for this month
|
| 757 |
+
budget_amount = 0
|
| 758 |
+
if not st.session_state.monthly_budgets_df.empty and selected_month in st.session_state.monthly_budgets_df['Month'].tolist():
|
| 759 |
+
budget_amount = st.session_state.monthly_budgets_df[
|
| 760 |
+
st.session_state.monthly_budgets_df['Month'] == selected_month
|
| 761 |
+
]['Budget'].values[0]
|
| 762 |
+
|
| 763 |
+
# Display metrics
|
| 764 |
+
col1, col2, col3 = st.columns(3)
|
| 765 |
+
|
| 766 |
+
with col1:
|
| 767 |
+
st.metric("Budget Set", f"₹{budget_amount:.2f}")
|
| 768 |
+
|
| 769 |
+
with col2:
|
| 770 |
+
st.metric("Total Spent", f"₹{total_spent:.2f}")
|
| 771 |
+
|
| 772 |
+
with col3:
|
| 773 |
+
remaining = budget_amount - total_spent
|
| 774 |
+
st.metric("Remaining", f"₹{remaining:.2f}", delta=f"{remaining:.2f}")
|
| 775 |
+
|
| 776 |
+
# Budget status
|
| 777 |
+
st.markdown("---")
|
| 778 |
+
|
| 779 |
+
if budget_amount > 0:
|
| 780 |
+
percentage = (total_spent / budget_amount) * 100
|
| 781 |
+
|
| 782 |
+
# Progress bar
|
| 783 |
+
st.progress(min(percentage / 100, 1.0))
|
| 784 |
+
|
| 785 |
+
# Status message
|
| 786 |
+
if total_spent > budget_amount:
|
| 787 |
+
over_amount = total_spent - budget_amount
|
| 788 |
+
st.error(f"🔴 **Budget Exceeded!** You have overspent by ₹{over_amount:.2f} ({percentage:.1f}% of budget used)")
|
| 789 |
+
else:
|
| 790 |
+
st.success(f"✅ **Under Budget!** You have ₹{remaining:.2f} remaining ({percentage:.1f}% of budget used)")
|
| 791 |
+
|
| 792 |
+
# Category breakdown
|
| 793 |
+
if not month_expenses.empty:
|
| 794 |
+
st.markdown("---")
|
| 795 |
+
st.subheader("Category Breakdown")
|
| 796 |
+
|
| 797 |
+
category_breakdown = month_expenses.groupby('Category')['Amount'].sum().reset_index()
|
| 798 |
+
category_breakdown = category_breakdown.sort_values('Amount', ascending=False)
|
| 799 |
+
|
| 800 |
+
# Create bar chart
|
| 801 |
+
fig = px.bar(
|
| 802 |
+
category_breakdown,
|
| 803 |
+
x='Category',
|
| 804 |
+
y='Amount',
|
| 805 |
+
title=f'Spending by Category - {month_name}',
|
| 806 |
+
labels={'Amount': 'Amount (₹)', 'Category': 'Category'},
|
| 807 |
+
color='Amount',
|
| 808 |
+
color_continuous_scale='reds'
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
fig.update_layout(
|
| 812 |
+
showlegend=False,
|
| 813 |
+
height=400,
|
| 814 |
+
title_x=0.5
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 818 |
+
|
| 819 |
+
# Table view
|
| 820 |
+
category_breakdown['Amount'] = category_breakdown['Amount'].apply(lambda x: f"₹{x:.2f}")
|
| 821 |
+
st.dataframe(category_breakdown, use_container_width=True, hide_index=True)
|
| 822 |
+
else:
|
| 823 |
+
st.warning(f"⚠️ No budget set for {month_name}. Go to 'Monthly Budget' tab to set a budget.")
|
| 824 |
+
|
| 825 |
+
# Display expenses for the month
|
| 826 |
+
if not month_expenses.empty:
|
| 827 |
+
st.markdown("---")
|
| 828 |
+
st.subheader(f"All Expenses for {month_name}")
|
| 829 |
+
|
| 830 |
+
display_expenses = month_expenses[['Category', 'Amount', 'Date', 'Raw_Date']].copy()
|
| 831 |
+
display_expenses.loc[:, 'Amount'] = display_expenses['Amount'].apply(lambda x: f"₹{x:.2f}")
|
| 832 |
+
|
| 833 |
+
st.dataframe(display_expenses, use_container_width=True, hide_index=True)
|
| 834 |
+
else:
|
| 835 |
+
st.info(f"No expenses recorded for {month_name}")
|
| 836 |
+
else:
|
| 837 |
+
st.info("No expenses recorded yet. Add some expenses to see the monthly expense sheet!")
|
| 838 |
+
|
| 839 |
+
# Footer
|
| 840 |
+
st.markdown("---")
|
| 841 |
+
st.markdown("*College Expense Tracker - Keep track of your spending habits!*")
|
budgets.csv
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Month,Budget
|
| 2 |
+
2025-10,4000.0
|
expenses.csv
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Category,Amount,Granularity,Date,Raw_Date
|
| 2 |
+
Transport,70.0,Daily,2025-10-05,2025-10-05
|
pyproject.toml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "repl-nix-workspace"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Add your description here"
|
| 5 |
+
requires-python = ">=3.11"
|
| 6 |
+
dependencies = [
|
| 7 |
+
"pandas>=2.3.3",
|
| 8 |
+
"plotly>=6.3.1",
|
| 9 |
+
"streamlit>=1.50.0",
|
| 10 |
+
]
|
replit.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# College Expense Tracker
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
A Streamlit-based web application designed to help college students track and visualize their expenses. The application provides an intuitive interface for recording expenses, categorizing them, and analyzing spending patterns through interactive visualizations. Data is persisted locally using CSV file storage, making it lightweight and portable without requiring a database server.
|
| 6 |
+
|
| 7 |
+
## User Preferences
|
| 8 |
+
|
| 9 |
+
Preferred communication style: Simple, everyday language.
|
| 10 |
+
|
| 11 |
+
## System Architecture
|
| 12 |
+
|
| 13 |
+
### Frontend Architecture
|
| 14 |
+
- **Framework**: Streamlit - A Python-based web framework chosen for rapid development and built-in UI components
|
| 15 |
+
- **Visualization**: Plotly Express for interactive charts and graphs
|
| 16 |
+
- **State Management**: Streamlit's session_state for maintaining application state across user interactions
|
| 17 |
+
- **Layout**: Wide layout configuration to maximize screen real estate for data visualization
|
| 18 |
+
|
| 19 |
+
**Design Rationale**: Streamlit was selected for its simplicity and Python-native development experience, eliminating the need for separate frontend/backend codebases. This is ideal for a student-focused tool where quick iterations and minimal deployment complexity are priorities.
|
| 20 |
+
|
| 21 |
+
### Data Storage
|
| 22 |
+
- **Storage Method**: CSV file-based persistence
|
| 23 |
+
- **File Location**: Local filesystem (`expenses.csv`)
|
| 24 |
+
- **Data Structure**: Pandas DataFrame for in-memory data manipulation
|
| 25 |
+
- **Caching Strategy**: `@st.cache_data` decorator used for loading expenses to optimize performance
|
| 26 |
+
|
| 27 |
+
**Design Rationale**: CSV storage provides a simple, human-readable format that doesn't require database setup or maintenance. This approach offers portability (easy to backup/share) and zero infrastructure overhead, suitable for a personal expense tracking application. The tradeoff is limited concurrent user support, which is acceptable for a single-user college expense tracker.
|
| 28 |
+
|
| 29 |
+
### Data Processing & Analysis
|
| 30 |
+
- **Date Handling**: Datetime operations for temporal analysis with configurable granularity (Daily, Weekly)
|
| 31 |
+
- **Aggregation**: Pandas-based data aggregation for expense categorization and time-based grouping
|
| 32 |
+
- **Error Handling**: Try-catch blocks around file I/O operations to gracefully handle data loading/saving failures
|
| 33 |
+
|
| 34 |
+
**Design Rationale**: Pandas provides powerful data manipulation capabilities well-suited for financial data analysis. The granularity feature allows users to view expenses at different time scales, supporting both detailed daily tracking and broader trend analysis.
|
| 35 |
+
|
| 36 |
+
### Application State Management
|
| 37 |
+
- **Session State**: Centralized expense data stored in `st.session_state.expenses_df`
|
| 38 |
+
- **Initialization**: Lazy loading pattern - data is loaded from CSV only on first access
|
| 39 |
+
- **Persistence Flow**: In-memory DataFrame → CSV file on updates
|
| 40 |
+
|
| 41 |
+
**Design Rationale**: Streamlit's session state maintains data consistency during user interactions without page reloads. The separation between in-memory state and file persistence provides a clear data flow while enabling undo/redo functionality if needed.
|
| 42 |
+
|
| 43 |
+
## External Dependencies
|
| 44 |
+
|
| 45 |
+
### Python Libraries
|
| 46 |
+
- **streamlit**: Core web application framework and UI components
|
| 47 |
+
- **pandas**: Data manipulation, CSV reading/writing, and DataFrame operations
|
| 48 |
+
- **plotly.express**: Interactive data visualization and charting
|
| 49 |
+
- **datetime**: Date/time manipulation for expense tracking and temporal analysis
|
| 50 |
+
- **os**: File system operations for CSV file existence checks
|
| 51 |
+
|
| 52 |
+
### Data Storage
|
| 53 |
+
- **CSV Files**: Local file system storage (no external database required)
|
| 54 |
+
- **Files**:
|
| 55 |
+
- `expenses.csv` - stores all expense records
|
| 56 |
+
- `budgets.csv` - stores monthly budget settings (YYYY-MM format)
|
| 57 |
+
|
| 58 |
+
### Recent Changes (October 2025)
|
| 59 |
+
- **Date Range Filtering**: Added ability to filter expenses by custom date ranges in View Expenses tab
|
| 60 |
+
- **Expense Management**: Implemented edit and delete functionality for individual expenses
|
| 61 |
+
- **Trend Analysis**: Added Trends tab with line charts showing spending patterns over time (daily, weekly, monthly aggregation)
|
| 62 |
+
- **Category Budgets**: Enhanced Budget tab with category-wise budget limits and progress tracking
|
| 63 |
+
- **Monthly Budgets**: Added Monthly Budget Input tab for setting total monthly budgets
|
| 64 |
+
- **Monthly Expense Sheet**: Added dedicated tab comparing monthly spending against budgets with visual alerts
|
| 65 |
+
- **Data Export**: Implemented CSV export functionality for filtered and complete expense data
|
| 66 |
+
|
| 67 |
+
### Deployment Considerations
|
| 68 |
+
- **Runtime**: Python 3.x environment required
|
| 69 |
+
- **File Permissions**: Write access needed for creating/updating `expenses.csv` and `budgets.csv`
|
| 70 |
+
- **No External Services**: Currently operates as a standalone application with no third-party API integrations
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|