Expense_Manager / app.py
Ashlin-Joseph's picture
Upload 7 files
13fdb7b verified
Raw History Blame Contribute Delete
35.2 kB
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!*")