import streamlit as st import pandas as pd import plotly.express as px import os from groq import Groq os.environ["GROQ_API_KEY"] = "Put your key here" st.set_page_config(page_title="Personal Expense Analyzer", layout="wide") st.title("💰 Personal Expense Analyzer") if "expenses" not in st.session_state: st.session_state["expenses"] = pd.DataFrame(columns=["Name", "Description", "Date", "Amount"]) st.sidebar.header("➕ Add New Expense") with st.sidebar.form("expense_form", clear_on_submit=True): name = st.text_input("Expense Name") desc = st.text_area("Description") date = st.date_input("Date of Expense") amount = st.number_input("Amount (SAR)", min_value=0.0, step=1.0) submitted = st.form_submit_button("Add Expense") if submitted: if name and amount > 0: new_exp = pd.DataFrame( {"Name": [name], "Description": [desc], "Date": [pd.to_datetime(date)], "Amount": [amount]} ) st.session_state["expenses"] = pd.concat([st.session_state["expenses"], new_exp], ignore_index=True) st.success("Expense added successfully!") else: st.error("Please enter both name and amount.") df = st.session_state["expenses"] if not df.empty: st.subheader("📊 Expense Summary") st.dataframe(df.sort_values("Date", ascending=False), use_container_width=True) col1, col2 = st.columns(2) with col1: st.markdown("### 💸 Expense Distribution (Pie Chart)") fig1 = px.pie(df, names="Name", values="Amount", title="Expenses by Category", hole=0.4) st.plotly_chart(fig1, use_container_width=True) with col2: st.markdown("### 📈 Expense Trend (Bar Chart)") df_sorted = df.groupby("Date")["Amount"].sum().reset_index() fig2 = px.bar(df_sorted, x="Date", y="Amount", title="Daily Spending Trend") st.plotly_chart(fig2, use_container_width=True) st.markdown("## 🧠 Expense Insights (Powered by Groq Llama Model)") if st.button("🔍 Analyze My Spending"): with st.spinner("Analyzing your expenses using Groq..."): try: client = Groq(api_key=os.environ.get("GROQ_API_KEY")) summary_text = df.to_string(index=False) prompt = f""" Analyze the following expense records and provide: 1. Spending patterns (e.g., high spend periods or frequent categories) 2. Financial control recommendations 3. Suggestions for saving or budgeting Expense data: {summary_text} """ response = client.chat.completions.create( messages=[ {"role": "system", "content": "You are a financial advisor analyzing personal expenses."}, {"role": "user", "content": prompt} ], model="llama-3.3-70b-versatile" ) result = response.choices[0].message.content st.success("✅ Analysis Complete!") st.markdown(f"### 🪄 AI Recommendations:\n{result}") except Exception as e: st.error(f"Error while analyzing: {e}") else: st.info("No expenses added yet. Use the sidebar to start adding your expenses!") st.markdown("---") st.caption("Built with ❤️ using Streamlit + Groq LLM")