Spaces:
Runtime error
Runtime error
LearnwithShashank commited on
Commit Β·
d70a27d
1
Parent(s): ca38434
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import pandas as pdimport streamlit as stimport osfrom 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"# 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)# Sidebar Navigationmenu = st.sidebar.radio("Navigate", ["β Add Expense", "π View Analytics"])# Add Expense Pageif menu == "β Add Expense":st.header("Log Your Expense")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")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!")# View Analytics Pageelse:st.header("π Expense Analytics")df = pd.read_csv(DATA_FILE, parse_dates=["Date"])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))df["Month"] = df["Date"].dt.to_period("M").astype(str)# Daily expense trenddaily = df.groupby("Date")["Amount"].sum()st.subheader("ποΈ Daily Spending Trend")st.line_chart(daily)# Category-wise pie chartcategory_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 summaryst.subheader("π Monthly Summary")monthly = df.groupby("Month")["Amount"].sum().reset_index()st.bar_chart(monthly.set_index("Month"))# Download datast.download_button("Download Data as CSV", data=df.to_csv(index=False), file_name="expenses.csv")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import streamlit as stimport requestsfrom datetime import datetime# App configst.set_page_config(page_title="Expense Tracker", layout="wide")st.title("πΈ Personal Expense Tracker")# Use secrets for API securityAPI_URL = st.secrets['API_URL']# 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.")# Main UIst.markdown("### βοΈ 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")# Quick amount presetsst.markdown("π‘ Quick Add:")preset_col1, preset_col2, preset_col3, preset_col4 = st.columns(4)if preset_col1.button("βΉ100"):amount = 100.0if preset_col2.button("βΉ200"):amount = 200.0if preset_col3.button("βΉ500"):amount = 500.0if preset_col4.button("βΉ1000"):amount = 1000.0notes = st.text_input("π Notes (optional)")# Submissionwith st.form("expense_form"):submitted = st.form_submit_button("π€ Submit Expense")if submitted:payload = {"date": str(date),"category": category,"amount": str(amount),"notes": notes}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