File size: 35,173 Bytes
13fdb7b | 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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 | import streamlit as st
import pandas as pd
import plotly.express as px
from datetime import datetime, timedelta
import os
# Page configuration
st.set_page_config(
page_title="College Expense Tracker",
page_icon="💰",
layout="wide"
)
# Initialize session state
if 'expenses_df' not in st.session_state:
st.session_state.expenses_df = pd.DataFrame()
if 'monthly_budgets_df' not in st.session_state:
st.session_state.monthly_budgets_df = pd.DataFrame()
# Load data from CSV if exists
@st.cache_data
def load_expenses():
if os.path.exists('expenses.csv'):
try:
df = pd.read_csv('expenses.csv')
return df
except Exception as e:
st.error(f"Error loading expenses: {e}")
return pd.DataFrame()
else:
return pd.DataFrame()
# Save data to CSV
def save_expenses(df):
try:
df.to_csv('expenses.csv', index=False)
return True
except Exception as e:
st.error(f"Error saving expenses: {e}")
return False
# Load monthly budgets from CSV (no cache to ensure fresh data)
def load_monthly_budgets():
if os.path.exists('budgets.csv'):
try:
df = pd.read_csv('budgets.csv')
return df
except Exception as e:
st.error(f"Error loading budgets: {e}")
return pd.DataFrame()
else:
return pd.DataFrame()
# Save monthly budgets to CSV
def save_monthly_budgets(df):
try:
df.to_csv('budgets.csv', index=False)
return True
except Exception as e:
st.error(f"Error saving budgets: {e}")
return False
# Load expenses on app start
if st.session_state.expenses_df.empty:
st.session_state.expenses_df = load_expenses()
# Load monthly budgets on app start
if st.session_state.monthly_budgets_df.empty:
st.session_state.monthly_budgets_df = load_monthly_budgets()
# Format date based on granularity
def format_date_by_granularity(date, granularity):
if granularity == "Daily":
return date.strftime("%Y-%m-%d")
elif granularity == "Weekly":
# Get ISO week number
year, week, _ = date.isocalendar()
return f"{year}-W{week:02d}"
elif granularity == "Monthly":
return date.strftime("%Y-%m")
# Main app title
st.title("💰 College Expense Tracker")
# Create tabs
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs(["Add Expense", "View Expenses", "Summary", "Graph", "Trends", "Budget", "Monthly Budget", "Monthly Expense Sheet"])
# Tab 1: Add Expense
with tab1:
st.header("Add New Expense")
col1, col2 = st.columns(2)
with col1:
# Category selection
categories = ["Food", "Transport", "Stationery", "Entertainment", "Others"]
category = st.selectbox("Category", categories)
# Amount input
amount = st.number_input("Amount (₹)", min_value=0.01, step=0.01, format="%.2f")
with col2:
# Granularity selector
granularity = st.selectbox("Time Granularity", ["Daily", "Weekly", "Monthly"])
# Date input with today as default
selected_date = st.date_input("Date", value=datetime.now().date())
# Add expense button
if st.button("Add Expense", type="primary"):
if amount > 0:
# Format date based on granularity
formatted_date = format_date_by_granularity(selected_date, granularity)
# Create new expense record
new_expense = {
'Category': category,
'Amount': amount,
'Granularity': granularity,
'Date': formatted_date,
'Raw_Date': selected_date.strftime("%Y-%m-%d")
}
# Add to dataframe using loc
if st.session_state.expenses_df.empty:
st.session_state.expenses_df = pd.DataFrame([new_expense])
else:
st.session_state.expenses_df.loc[len(st.session_state.expenses_df)] = new_expense
# Save to CSV
if save_expenses(st.session_state.expenses_df):
st.success(f"✅ Added {category}: ₹{amount:.2f} for {formatted_date} ({granularity})")
st.rerun()
else:
st.error("Please enter a valid amount greater than 0")
# Tab 2: View Expenses
with tab2:
st.header("All Expenses")
if not st.session_state.expenses_df.empty:
# Date range filter
st.subheader("Filter by Date Range")
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
# Get min and max dates from data
min_date = pd.to_datetime(st.session_state.expenses_df['Raw_Date']).min().date()
max_date = pd.to_datetime(st.session_state.expenses_df['Raw_Date']).max().date()
start_date = st.date_input("Start Date", value=min_date, min_value=min_date, max_value=max_date)
with col2:
end_date = st.date_input("End Date", value=max_date, min_value=min_date, max_value=max_date)
with col3:
apply_filter = st.button("Apply Filter", type="primary")
clear_filter = st.button("Clear Filter")
# Filter data based on date range
filtered_df = st.session_state.expenses_df.copy()
if apply_filter or 'date_filter_active' in st.session_state:
if apply_filter:
st.session_state.date_filter_active = True
st.session_state.filter_start = start_date
st.session_state.filter_end = end_date
if 'date_filter_active' in st.session_state and st.session_state.date_filter_active:
start = st.session_state.filter_start
end = st.session_state.filter_end
# Filter using Raw_Date column
filtered_df = filtered_df[
(pd.to_datetime(filtered_df['Raw_Date']).dt.date >= start) &
(pd.to_datetime(filtered_df['Raw_Date']).dt.date <= end)
]
st.info(f"Showing expenses from {start} to {end} ({len(filtered_df)} entries)")
if clear_filter:
st.session_state.date_filter_active = False
st.rerun()
# Display expenses table with edit/delete options
if not filtered_df.empty:
st.subheader("Expense List")
# Display each expense with edit/delete buttons
for idx in filtered_df.index:
expense = filtered_df.loc[idx]
col1, col2, col3, col4, col5, col6, col7 = st.columns([2, 1.5, 1.5, 1.5, 1.5, 0.8, 0.8])
with col1:
st.text(f"{expense['Category']}")
with col2:
st.text(f"₹{expense['Amount']:.2f}")
with col3:
st.text(f"{expense['Granularity']}")
with col4:
st.text(f"{expense['Date']}")
with col5:
st.text(f"{expense['Raw_Date']}")
with col6:
if st.button("✏️", key=f"edit_{idx}"):
st.session_state.editing_index = idx
st.rerun()
with col7:
if st.button("🗑️", key=f"delete_{idx}"):
st.session_state.deleting_index = idx
st.rerun()
# Edit expense dialog
if 'editing_index' in st.session_state:
idx = st.session_state.editing_index
expense = st.session_state.expenses_df.loc[idx]
st.markdown("---")
st.subheader("Edit Expense")
col1, col2 = st.columns(2)
with col1:
edit_category = st.selectbox("Category", ["Food", "Transport", "Stationery", "Entertainment", "Others"],
index=["Food", "Transport", "Stationery", "Entertainment", "Others"].index(expense['Category']),
key=f"edit_category_{idx}")
edit_amount = st.number_input("Amount (₹)", value=float(expense['Amount']), min_value=0.01, step=0.01, format="%.2f", key=f"edit_amount_{idx}")
with col2:
edit_granularity = st.selectbox("Time Granularity", ["Daily", "Weekly", "Monthly"],
index=["Daily", "Weekly", "Monthly"].index(expense['Granularity']),
key=f"edit_granularity_{idx}")
edit_date = st.date_input("Date", value=pd.to_datetime(expense['Raw_Date']).date(), key=f"edit_date_{idx}")
col1, col2 = st.columns(2)
with col1:
if st.button("Save Changes", type="primary", key=f"save_{idx}"):
# Update the expense
formatted_date = format_date_by_granularity(edit_date, edit_granularity)
st.session_state.expenses_df.loc[idx, 'Category'] = edit_category
st.session_state.expenses_df.loc[idx, 'Amount'] = edit_amount
st.session_state.expenses_df.loc[idx, 'Granularity'] = edit_granularity
st.session_state.expenses_df.loc[idx, 'Date'] = formatted_date
st.session_state.expenses_df.loc[idx, 'Raw_Date'] = edit_date.strftime("%Y-%m-%d")
save_expenses(st.session_state.expenses_df)
del st.session_state.editing_index
st.success("✅ Expense updated successfully!")
st.rerun()
with col2:
if st.button("Cancel", type="secondary", key=f"cancel_edit_{idx}"):
del st.session_state.editing_index
st.rerun()
# Delete confirmation dialog
if 'deleting_index' in st.session_state:
idx = st.session_state.deleting_index
expense = st.session_state.expenses_df.loc[idx]
st.markdown("---")
st.warning(f"⚠️ Are you sure you want to delete this expense?\n\n**{expense['Category']}**: ₹{expense['Amount']:.2f} on {expense['Date']}")
col1, col2 = st.columns(2)
with col1:
if st.button("Yes, Delete", type="primary"):
st.session_state.expenses_df = st.session_state.expenses_df.drop(idx).reset_index(drop=True)
save_expenses(st.session_state.expenses_df)
del st.session_state.deleting_index
st.success("✅ Expense deleted successfully!")
st.rerun()
with col2:
if st.button("Cancel", type="secondary", key="cancel_delete"):
del st.session_state.deleting_index
st.rerun()
else:
st.warning("No expenses found in the selected date range.")
# Export functionality
st.markdown("---")
st.subheader("Export Data")
col1, col2 = st.columns(2)
with col1:
# Export filtered data
if not filtered_df.empty:
csv_data = filtered_df.to_csv(index=False)
st.download_button(
label="📥 Download Filtered Data (CSV)",
data=csv_data,
file_name=f"expenses_filtered_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv",
type="primary"
)
else:
st.button("📥 Download Filtered Data (CSV)", disabled=True, type="primary")
with col2:
# Export all data
csv_all = st.session_state.expenses_df.to_csv(index=False)
st.download_button(
label="📥 Download All Data (CSV)",
data=csv_all,
file_name=f"expenses_all_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv",
type="secondary"
)
# Option to clear all expenses
st.markdown("---")
if st.button("Clear All Expenses", type="secondary"):
st.session_state.expenses_df = pd.DataFrame()
if os.path.exists('expenses.csv'):
os.remove('expenses.csv')
st.success("All expenses cleared!")
st.rerun()
else:
st.info("No expenses recorded yet. Add some expenses to see them here!")
# Tab 3: Summary
with tab3:
st.header("Expense Summary")
if not st.session_state.expenses_df.empty:
# Total spent
total_spent = st.session_state.expenses_df['Amount'].sum()
st.metric("Total Spent", f"₹{total_spent:.2f}")
st.subheader("Category-wise Breakdown")
# Category-wise summary
category_summary = st.session_state.expenses_df.groupby('Category')['Amount'].agg(['sum', 'count']).reset_index()
category_summary.columns = ['Category', 'Total Amount', 'Number of Transactions']
category_summary['Total Amount'] = category_summary['Total Amount'].apply(lambda x: f"₹{x:.2f}")
st.dataframe(
category_summary,
use_container_width=True,
hide_index=True
)
# Display totals clearly
st.subheader("Clear Totals")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Food", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Food']['Amount'].sum():.2f}")
with col2:
st.metric("Transport", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Transport']['Amount'].sum():.2f}")
with col3:
st.metric("Entertainment", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Entertainment']['Amount'].sum():.2f}")
col4, col5 = st.columns(2)
with col4:
st.metric("Stationery", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Stationery']['Amount'].sum():.2f}")
with col5:
st.metric("Others", f"₹{st.session_state.expenses_df[st.session_state.expenses_df['Category'] == 'Others']['Amount'].sum():.2f}")
else:
st.info("No expenses recorded yet. Add some expenses to see the summary!")
# Tab 4: Graph
with tab4:
st.header("Expense Visualization")
if not st.session_state.expenses_df.empty:
# Category totals for bar chart
category_totals = st.session_state.expenses_df.groupby('Category')['Amount'].sum().reset_index()
category_totals = category_totals.sort_values('Amount', ascending=False)
# Create bar chart
fig = px.bar(
category_totals,
x='Category',
y='Amount',
title='Category-wise Expense Distribution',
labels={'Amount': 'Amount (₹)', 'Category': 'Expense Category'},
color='Amount',
color_continuous_scale='viridis'
)
# Update layout
fig.update_layout(
showlegend=False,
height=500,
title_x=0.5
)
# Display chart
st.plotly_chart(fig, use_container_width=True)
# Additional insights
st.subheader("Quick Insights")
if len(category_totals) > 0:
highest_category = category_totals.iloc[0]
lowest_category = category_totals.iloc[-1]
col1, col2 = st.columns(2)
with col1:
st.info(f"💸 Highest spending: **{highest_category['Category']}** (₹{highest_category['Amount']:.2f})")
with col2:
st.info(f"💡 Lowest spending: **{lowest_category['Category']}** (₹{lowest_category['Amount']:.2f})")
else:
st.info("No expenses recorded yet. Add some expenses to see the visualization!")
# Tab 5: Trends
with tab5:
st.header("Spending Trends Over Time")
if not st.session_state.expenses_df.empty:
# Create a copy with datetime column
trend_df = st.session_state.expenses_df.copy()
trend_df['Date_dt'] = pd.to_datetime(trend_df['Raw_Date'])
trend_df = trend_df.sort_values('Date_dt')
# View options
view_option = st.radio("View by:", ["Total Spending", "Category-wise"], horizontal=True)
if view_option == "Total Spending":
# Aggregate by date
daily_spending = trend_df.groupby('Raw_Date')['Amount'].sum().reset_index()
daily_spending['Date_dt'] = pd.to_datetime(daily_spending['Raw_Date'])
daily_spending = daily_spending.sort_values('Date_dt')
# Create line chart
fig = px.line(
daily_spending,
x='Date_dt',
y='Amount',
title='Total Daily Spending Trend',
labels={'Date_dt': 'Date', 'Amount': 'Amount (₹)'},
markers=True
)
fig.update_layout(
height=500,
title_x=0.5,
xaxis_title="Date",
yaxis_title="Amount (₹)"
)
st.plotly_chart(fig, use_container_width=True)
# Show statistics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Average Daily Spending", f"₹{daily_spending['Amount'].mean():.2f}")
with col2:
st.metric("Highest Day", f"₹{daily_spending['Amount'].max():.2f}")
with col3:
st.metric("Lowest Day", f"₹{daily_spending['Amount'].min():.2f}")
else: # Category-wise
# Category selector
selected_categories = st.multiselect(
"Select Categories to Display",
["Food", "Transport", "Stationery", "Entertainment", "Others"],
default=["Food", "Transport", "Entertainment"]
)
if selected_categories:
# Filter by selected categories
category_trend = trend_df[trend_df['Category'].isin(selected_categories)]
# Aggregate by date and category
category_daily = category_trend.groupby(['Raw_Date', 'Category'])['Amount'].sum().reset_index()
category_daily['Date_dt'] = pd.to_datetime(category_daily['Raw_Date'])
category_daily = category_daily.sort_values('Date_dt')
# Create multi-line chart
fig = px.line(
category_daily,
x='Date_dt',
y='Amount',
color='Category',
title='Category-wise Spending Trends',
labels={'Date_dt': 'Date', 'Amount': 'Amount (₹)'},
markers=True
)
fig.update_layout(
height=500,
title_x=0.5,
xaxis_title="Date",
yaxis_title="Amount (₹)"
)
st.plotly_chart(fig, use_container_width=True)
# Show category statistics
st.subheader("Category Statistics")
for cat in selected_categories:
cat_data = trend_df[trend_df['Category'] == cat]
if not cat_data.empty:
col1, col2, col3 = st.columns(3)
with col1:
st.metric(f"{cat} - Total", f"₹{cat_data['Amount'].sum():.2f}")
with col2:
st.metric(f"{cat} - Average", f"₹{cat_data['Amount'].mean():.2f}")
with col3:
st.metric(f"{cat} - Count", f"{len(cat_data)} expenses")
else:
st.warning("Please select at least one category to view trends.")
# Weekly/Monthly aggregation option
st.markdown("---")
st.subheader("Aggregated View")
agg_period = st.selectbox("Aggregate by:", ["Week", "Month"])
if agg_period == "Week":
trend_df['Period'] = trend_df['Date_dt'].dt.to_period('W').astype(str)
else:
trend_df['Period'] = trend_df['Date_dt'].dt.to_period('M').astype(str)
period_spending = trend_df.groupby('Period')['Amount'].sum().reset_index()
fig = px.bar(
period_spending,
x='Period',
y='Amount',
title=f'{agg_period}ly Spending Overview',
labels={'Period': agg_period, 'Amount': 'Amount (₹)'},
color='Amount',
color_continuous_scale='blues'
)
fig.update_layout(
height=400,
title_x=0.5,
showlegend=False
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No expenses recorded yet. Add some expenses to see spending trends!")
# Tab 6: Budget
with tab6:
st.header("Budget Management")
# Initialize budget in session state
if 'budgets' not in st.session_state:
st.session_state.budgets = {
'Food': 0,
'Transport': 0,
'Stationery': 0,
'Entertainment': 0,
'Others': 0
}
# Budget setting section
st.subheader("Set Category Budgets")
st.write("Set monthly budget limits for each category. Leave at 0 to disable alerts.")
col1, col2 = st.columns(2)
with col1:
food_budget = st.number_input("Food Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Food']), step=100.0, key="food_budget")
transport_budget = st.number_input("Transport Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Transport']), step=100.0, key="transport_budget")
stationery_budget = st.number_input("Stationery Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Stationery']), step=100.0, key="stationery_budget")
with col2:
entertainment_budget = st.number_input("Entertainment Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Entertainment']), step=100.0, key="entertainment_budget")
others_budget = st.number_input("Others Budget (₹)", min_value=0.0, value=float(st.session_state.budgets['Others']), step=100.0, key="others_budget")
if st.button("Save Budgets", type="primary"):
st.session_state.budgets = {
'Food': food_budget,
'Transport': transport_budget,
'Stationery': stationery_budget,
'Entertainment': entertainment_budget,
'Others': others_budget
}
st.success("✅ Budgets saved successfully!")
st.rerun()
# Budget status and alerts
if not st.session_state.expenses_df.empty:
st.markdown("---")
st.subheader("Budget Status")
# Calculate current month spending
current_month = datetime.now().strftime("%Y-%m")
current_month_df = st.session_state.expenses_df[
st.session_state.expenses_df['Raw_Date'].str.startswith(current_month)
]
if not current_month_df.empty:
st.write(f"**Current Month:** {datetime.now().strftime('%B %Y')}")
# Check each category
alerts = []
for category in ['Food', 'Transport', 'Stationery', 'Entertainment', 'Others']:
budget = st.session_state.budgets[category]
if budget > 0:
spent = current_month_df[current_month_df['Category'] == category]['Amount'].sum()
remaining = budget - spent
percentage = (spent / budget) * 100 if budget > 0 else 0
# Create progress display
col1, col2 = st.columns([3, 1])
with col1:
st.write(f"**{category}**")
st.progress(min(percentage / 100, 1.0))
# Color-coded status
if percentage >= 100:
st.error(f"⚠️ Over budget by ₹{abs(remaining):.2f} ({percentage:.1f}% of budget)")
alerts.append(f"**{category}**: Over budget by ₹{abs(remaining):.2f}")
elif percentage >= 80:
st.warning(f"⚠️ ₹{remaining:.2f} remaining ({percentage:.1f}% used)")
else:
st.success(f"✓ ₹{remaining:.2f} remaining ({percentage:.1f}% used)")
with col2:
st.metric("Spent", f"₹{spent:.2f}")
st.metric("Budget", f"₹{budget:.2f}")
# Display alerts summary
if alerts:
st.markdown("---")
st.error("### 🚨 Budget Alerts")
for alert in alerts:
st.write(f"- {alert}")
else:
st.info(f"No expenses recorded for {datetime.now().strftime('%B %Y')} yet.")
else:
st.info("No expenses recorded yet. Add some expenses to see budget status!")
# Tab 7: Monthly Budget Input
with tab7:
st.header("Monthly Budget Input")
st.write("Set a total budget for a specific month. This budget will be compared against your total spending for that month.")
col1, col2 = st.columns(2)
with col1:
# Month selection
budget_year = st.number_input("Year", min_value=2020, max_value=2030, value=datetime.now().year, step=1, key="budget_year")
budget_month = st.selectbox("Month", list(range(1, 13)),
format_func=lambda x: datetime(2000, x, 1).strftime('%B'),
index=datetime.now().month - 1,
key="budget_month")
with col2:
budget_amount = st.number_input("Budget Amount (₹)", min_value=0.0, step=100.0, format="%.2f", key="budget_amount")
# Format month as YYYY-MM
month_key = f"{budget_year}-{budget_month:02d}"
if st.button("Save Monthly Budget", type="primary"):
if budget_amount > 0:
# Check if budget already exists for this month
if not st.session_state.monthly_budgets_df.empty and month_key in st.session_state.monthly_budgets_df['Month'].values:
# Update existing budget
st.session_state.monthly_budgets_df.loc[
st.session_state.monthly_budgets_df['Month'] == month_key, 'Budget'
] = budget_amount
st.success(f"✅ Updated budget for {month_key}: ₹{budget_amount:.2f}")
else:
# Add new budget
new_budget = {'Month': month_key, 'Budget': budget_amount}
if st.session_state.monthly_budgets_df.empty:
st.session_state.monthly_budgets_df = pd.DataFrame([new_budget])
else:
st.session_state.monthly_budgets_df.loc[len(st.session_state.monthly_budgets_df)] = new_budget
st.success(f"✅ Added budget for {month_key}: ₹{budget_amount:.2f}")
# Save to CSV
if save_monthly_budgets(st.session_state.monthly_budgets_df):
st.rerun()
else:
st.error("Failed to save budget. Please try again.")
else:
st.error("Please enter a budget amount greater than 0")
# Display saved budgets
if not st.session_state.monthly_budgets_df.empty:
st.markdown("---")
st.subheader("Saved Monthly Budgets")
# Sort by month
display_budgets = st.session_state.monthly_budgets_df.copy()
display_budgets = display_budgets.sort_values('Month', ascending=False)
display_budgets['Budget'] = display_budgets['Budget'].apply(lambda x: f"₹{x:.2f}")
st.dataframe(
display_budgets,
use_container_width=True,
hide_index=True
)
# Option to delete a budget
st.markdown("---")
delete_month = st.selectbox("Select month to delete",
st.session_state.monthly_budgets_df['Month'].values,
key="delete_budget_month")
if st.button("Delete Selected Budget", type="secondary"):
st.session_state.monthly_budgets_df = st.session_state.monthly_budgets_df[
st.session_state.monthly_budgets_df['Month'] != delete_month
].reset_index(drop=True)
if save_monthly_budgets(st.session_state.monthly_budgets_df):
st.success(f"✅ Deleted budget for {delete_month}")
st.rerun()
else:
st.error("Failed to delete budget. Please try again.")
else:
st.info("No monthly budgets saved yet. Add a budget above to get started!")
# Tab 8: Monthly Expense Sheet
with tab8:
st.header("Monthly Expense Sheet")
st.write("Compare your actual spending against your monthly budget.")
# Month selection
col1, col2 = st.columns(2)
with col1:
sheet_year = st.number_input("Year", min_value=2020, max_value=2030, value=datetime.now().year, step=1, key="sheet_year")
with col2:
sheet_month = st.selectbox("Month", list(range(1, 13)),
format_func=lambda x: datetime(2000, x, 1).strftime('%B'),
index=datetime.now().month - 1,
key="sheet_month")
# Format month as YYYY-MM
selected_month = f"{sheet_year}-{sheet_month:02d}"
month_name = datetime(sheet_year, sheet_month, 1).strftime('%B %Y')
st.markdown("---")
st.subheader(f"Expense Summary for {month_name}")
# Calculate total spending for selected month
if not st.session_state.expenses_df.empty:
month_expenses = st.session_state.expenses_df[
st.session_state.expenses_df['Raw_Date'].str.startswith(selected_month)
]
total_spent = month_expenses['Amount'].sum() if not month_expenses.empty else 0
# Check if budget exists for this month
budget_amount = 0
if not st.session_state.monthly_budgets_df.empty and selected_month in st.session_state.monthly_budgets_df['Month'].tolist():
budget_amount = st.session_state.monthly_budgets_df[
st.session_state.monthly_budgets_df['Month'] == selected_month
]['Budget'].values[0]
# Display metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Budget Set", f"₹{budget_amount:.2f}")
with col2:
st.metric("Total Spent", f"₹{total_spent:.2f}")
with col3:
remaining = budget_amount - total_spent
st.metric("Remaining", f"₹{remaining:.2f}", delta=f"{remaining:.2f}")
# Budget status
st.markdown("---")
if budget_amount > 0:
percentage = (total_spent / budget_amount) * 100
# Progress bar
st.progress(min(percentage / 100, 1.0))
# Status message
if total_spent > budget_amount:
over_amount = total_spent - budget_amount
st.error(f"🔴 **Budget Exceeded!** You have overspent by ₹{over_amount:.2f} ({percentage:.1f}% of budget used)")
else:
st.success(f"✅ **Under Budget!** You have ₹{remaining:.2f} remaining ({percentage:.1f}% of budget used)")
# Category breakdown
if not month_expenses.empty:
st.markdown("---")
st.subheader("Category Breakdown")
category_breakdown = month_expenses.groupby('Category')['Amount'].sum().reset_index()
category_breakdown = category_breakdown.sort_values('Amount', ascending=False)
# Create bar chart
fig = px.bar(
category_breakdown,
x='Category',
y='Amount',
title=f'Spending by Category - {month_name}',
labels={'Amount': 'Amount (₹)', 'Category': 'Category'},
color='Amount',
color_continuous_scale='reds'
)
fig.update_layout(
showlegend=False,
height=400,
title_x=0.5
)
st.plotly_chart(fig, use_container_width=True)
# Table view
category_breakdown['Amount'] = category_breakdown['Amount'].apply(lambda x: f"₹{x:.2f}")
st.dataframe(category_breakdown, use_container_width=True, hide_index=True)
else:
st.warning(f"⚠️ No budget set for {month_name}. Go to 'Monthly Budget' tab to set a budget.")
# Display expenses for the month
if not month_expenses.empty:
st.markdown("---")
st.subheader(f"All Expenses for {month_name}")
display_expenses = month_expenses[['Category', 'Amount', 'Date', 'Raw_Date']].copy()
display_expenses.loc[:, 'Amount'] = display_expenses['Amount'].apply(lambda x: f"₹{x:.2f}")
st.dataframe(display_expenses, use_container_width=True, hide_index=True)
else:
st.info(f"No expenses recorded for {month_name}")
else:
st.info("No expenses recorded yet. Add some expenses to see the monthly expense sheet!")
# Footer
st.markdown("---")
st.markdown("*College Expense Tracker - Keep track of your spending habits!*") |