Spaces:
Runtime error
Runtime error
LearnwithShashank commited on
Commit Β·
d70a27d
1
Parent(s): ca38434
113235456781112910111415161712131415161718192019202122232422232425262728292627282930313031323334353637383940413334353637424339404142444546474445464748495051484950515253545553545556575859606162636465666768697071727374565758596061626364import pandas as pdimport streamlit as stimport osimport requestsfrom datetime import datetimeimport matplotlib.pyplot as plt
# App configst.set_page_config(page_title="Expense Tracker", layout="wide")st.title("πΈ Personal Expense Tracker")
# File to store expensesDATA_FILE = "expenses.csv"# Use secrets for API securityAPI_URL = st.secrets['API_URL']
# Initialize fileif not os.path.exists(DATA_FILE): df_init = pd.DataFrame(columns=["Date", "Category", "Amount", "Remarks"]) df_init.to_csv(DATA_FILE, index=False)# Sidebarwith st.sidebar: st.markdown("### π Menu") st.markdown("β Add Expense") st.markdown("---") st.info("Track your daily expenses with ease.\nAll data is securely stored in Google Sheets.")
# Sidebar Navigationmenu = st.sidebar.radio("Navigate", ["β Add Expense", "π View Analytics"])# Main UIst.markdown("### βοΈ Log Your Expense")
# Add Expense Pageif menu == "β Add Expense": st.header("Log Your Expense")# Form layoutcol1, col2 = st.columns(2)with col1: date = st.date_input("Date", value=datetime.today()) category = st.selectbox("Category", ["Food", "Transport", "Utilities", "Shopping", "Entertainment", "Other"])with col2: amount = st.number_input("Amount Spent (βΉ)", min_value=0.0, step=10.0, format="%.2f")
with st.form("expense_form"): date = st.date_input("Date", value=datetime.today()) category = st.selectbox("Category", ["Food", "Transport", "Utilities", "Shopping", "Entertainment", "Other"]) amount = st.number_input("Amount Spent (βΉ)", min_value=0.0, format="%.2f") notes = st.text_input("Notes (optional)") submitted = st.form_submit_button("Add Expense") # Quick amount presets st.markdown("π‘ Quick Add:") preset_col1, preset_col2, preset_col3, preset_col4 = st.columns(4) if preset_col1.button("βΉ100"): amount = 100.0 if preset_col2.button("βΉ200"): amount = 200.0 if preset_col3.button("βΉ500"): amount = 500.0 if preset_col4.button("βΉ1000"): amount = 1000.0
if submitted: new_data = pd.DataFrame([[date, category, amount, notes]], columns=["Date", "Category", "Amount", "Notes"]) new_data.to_csv(DATA_FILE, mode='a', header=False, index=False) st.success("Expense added successfully!")notes = st.text_input("π Notes (optional)")
# View Analytics Pageelse: st.header("π Expense Analytics") df = pd.read_csv(DATA_FILE, parse_dates=["Date"])# Submissionwith st.form("expense_form"): submitted = st.form_submit_button("π€ Submit Expense")
if df.empty: st.warning("No expenses found. Please add some data first.") else: col1, col2 = st.columns(2) with col1: st.metric("Total Spent", f"βΉ{df['Amount'].sum():,.2f}") with col2: st.metric("Total Entries", len(df)) if submitted: payload = { "date": str(date), "category": category, "amount": str(amount), "notes": notes }
df["Month"] = df["Date"].dt.to_period("M").astype(str)
# Daily expense trend daily = df.groupby("Date")["Amount"].sum() st.subheader("ποΈ Daily Spending Trend") st.line_chart(daily)
# Category-wise pie chart category_totals = df.groupby("Category")["Amount"].sum() st.subheader("π Spending by Category") fig, ax = plt.subplots() ax.pie(category_totals, labels=category_totals.index, autopct='%1.1f%%', startangle=90) ax.axis("equal") st.pyplot(fig)
# Monthly summary st.subheader("π
Monthly Summary") monthly = df.groupby("Month")["Amount"].sum().reset_index() st.bar_chart(monthly.set_index("Month"))
# Download data st.download_button("Download Data as CSV", data=df.to_csv(index=False), file_name="expenses.csv") with st.spinner("Logging your expense..."): try: res = requests.post(API_URL, data=payload) if res.status_code == 200 and "Success" in res.text: st.success("β
Expense added to Google Sheet successfully!") else: st.error("β Failed to send data. Server says: " + res.text) except Exception as e: st.error(f"β οΈ An error occurred: {e}")expense.py+49-59