A full-stack, intelligent expense management system that combines a modern PHP web application with machine learningβdriven category prediction, smart spending insights, and Apache Sparkβpowered big data analytics.
π Live Demo Β Β·Β π Quick Start Β Β·Β π€ ML Pipeline Β Β·Β β‘ Spark Analytics
- Overview
- Key Features
- Tech Stack
- System Architecture
- Quick Start
- ML Pipeline
- Apache Spark Analytics
- Authentication System
- API Reference
- Database Schema
- Project Structure
- Security
- Screenshots
- License
The AI-Powered Personal Expense Tracker is a comprehensive financial management application built as a major academic project. It goes far beyond basic CRUD operations, integrating a complete machine learning pipeline for automatic expense categorization and a distributed Apache Spark engine for large-scale spending analytics.
| Traditional Trackers | This Project |
|---|---|
| Manual category selection | AI auto-predicts category from description |
| Static reports | Spark-powered real-time analytics & trend detection |
| Basic password login | OTP-based authentication with rate limiting |
| No spending intelligence | Smart Insights Engine with anomaly detection |
| Single-table summaries | Multi-dimensional weekly/monthly/yearly trend analysis |
- Automatic Category Prediction β TF-IDF + Logistic Regression model predicts expense categories from text descriptions with high accuracy
- Smart Spending Insights β Statistical anomaly detection using IQR method, trend analysis, and savings recommendations
- Confidence Scoring β Each prediction returns probability scores across all 8 categories
- Batch Prediction API β Process multiple expenses in a single API call
- Monthly Summary Aggregation β Per-user monthly totals, averages, min/max breakdowns
- Category-wise Analysis β Spending distribution with percentage calculations using Spark window functions
- Trend Detection β Weekly (ISO 8601), monthly, and yearly trend computation with daily burn rates
- Spike Detection β Month-over-month spending surge alerts (>25% threshold)
- End-of-Month Projections β Predictive spending forecasts based on current daily rate vs. last month
- Weekend vs. Weekday Patterns β Spending habit analysis with actionable savings recommendations
- Real-time Metrics β Total spending, average monthly, transaction count, top category
- Interactive Charts β 7-day expense trends and category distribution (Chart.js)
- Recent Transactions β Live feed with category badges and timestamps
- Monthly Budget Tracking β Set per-category budgets with visual progress bars and overspend alerts
- Dual Login Modes β Traditional password + Email OTP (one-time password)
- Guest Mode β Try the app without registration (localStorage-based)
- Rate Limiting β Account lockout after 5 failed attempts (15-minute cooldown)
- OTP Rate Limiting β Max 3 OTP requests per 10-minute window
- Remember Me β Secure 30-day persistent sessions with hashed tokens
- CSRF Protection β Token-based protection on all forms
- Full CRUD operations β Add, edit, delete, search expenses
- Advanced Filtering β By category, date range (today, week, month, year, custom), and search text
- Sortable Columns β Click headers to sort by date or amount
- Custom Categories β Create, edit, and color-code your own categories with icons
- Notes Field β Add optional notes to any transaction
| Technology | Purpose |
|---|---|
| PHP 8.x | Server-side logic, RESTful API |
| MySQL 8.0 | Relational database (XAMPP) |
| Python 3.11 | ML pipeline & Spark analytics |
| Flask 3.0 | ML prediction REST API server |
| Apache Spark 3.5 | Distributed data processing |
| PySpark | Spark's Python API |
| Technology | Purpose |
|---|---|
| HTML5 / CSS3 | Semantic markup, modern styling |
| Vanilla JavaScript | Dashboard interactivity, AJAX calls |
| Chart.js | Financial data visualization |
| Lucide Icons | Consistent iconography |
| Library | Purpose |
|---|---|
| scikit-learn | Logistic Regression, TF-IDF, model evaluation |
| pandas / NumPy | Data manipulation & analysis |
| matplotlib / seaborn | EDA visualizations |
| WordCloud | Text feature visualization |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT (Browser) β
β Dashboard β Expenses β Categories β Reports β Spark UI β
ββββββββ¬ββββββββ΄ββββββ¬βββββββ΄βββββββ¬ββββββββ΄ββββββ¬ββββββ΄βββββββ¬ββββββ
β β β β β
βΌ βΌ βΌ βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PHP REST API Layer β
β auth.php β expenses.php β categories.php β budget.php β spark_.phpβ
ββββββββ¬βββββ΄βββββββ¬ββββββββ΄ββββββββ¬βββββββββ΄ββββββ¬βββββββ΄ββββββ¬βββββ
β β β β β
βΌ βΌ βΌ βΌ βΌ
ββββββββββββββββ ββββββββββββββββββββββ ββββββββββββββββββββββββββββ
β MySQL DB β β Flask ML API β β Apache Spark Engine β
β β β (:5000) β β (PySpark + JDBC) β
β β’ users β β β’ /predict β β β’ Monthly Summary β
β β’ expenses β β β’ /predict/batch β β β’ Category Summary β
β β’ categoriesβ β β’ /insights β β β’ Trend Analysis β
β β’ budgets β β β’ /health β β β’ Smart Insights β
β β’ spark_* β β β β β’ Recommendations β
ββββββββββββββββ ββββββββββββββββββββββ ββββββββββββββββββββββββββββ
β β
βΌ β
βββββββββββββββββββ β
β Trained Models β β
β (.pkl files) βββββββββββββββββββ
β β’ category_modelβ (reads MySQL via JDBC,
β β’ tfidf_vectorizerβ writes summaries back)
β β’ scaler β
β β’ label_encoder β
βββββββββββββββββββ
- XAMPP (Apache + MySQL + PHP)
- Python 3.11+
- Apache Spark 3.5 (optional, for analytics)
- Java 11+ (required for Spark)
git clone https://github.com/Unknown-user-555/expense-tracker.git
# Place in your XAMPP htdocs directory as 'personal_expense'Open phpMyAdmin (http://localhost/phpmyadmin) and run:
-- Create database and tables
SOURCE C:/xampp/htdocs/personal_expense/database/schema.sql;
-- Run auth migration (adds OTP + rate limiting columns)
SOURCE C:/xampp/htdocs/personal_expense/database/migrate_auth.sql;
-- Add Spark analytics tables
SOURCE C:/xampp/htdocs/personal_expense/database/spark_tables.sql;Or import each SQL file via phpMyAdmin's Import tab.
Edit config/database.php if your MySQL credentials differ:
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', ''); // Your MySQL password
define('DB_NAME', 'personal_expense_tracker');cd ml
pip install -r requirements.txtpython expense_ai.pyThis will:
- Load and merge the 602-record training dataset
- Perform exploratory data analysis with 8 visualizations
- Train a Logistic Regression model with TF-IDF features
- Run 5-fold cross-validation and regularization analysis
- Save 4
.pklmodel files toml/models/
python predict_api.py
# Server starts at http://localhost:5000- Start Apache and MySQL from XAMPP Control Panel
- Navigate to:
http://localhost/personal_expense
Input: (description: str, amount: float)
β
βββ Text Branch βββΊ TF-IDF Vectorizer (500 features, 1-2 ngrams)
β βββ Sublinear TF scaling, English stop words removed
β
βββ Numeric Branch βΊ StandardScaler (z-score normalization)
β
βΌ
scipy.sparse.hstack β Combined Feature Matrix (501 features)
β
βΌ
Logistic Regression (multinomial, L-BFGS solver, C=1.0)
β
βΌ
Output: Predicted Category + Confidence Scores (8 classes)
| Parameter | Value |
|---|---|
| Dataset | 602 expense records across 8 categories |
| Features | TF-IDF text (500) + normalized amount (1) |
| Model | Logistic Regression (multinomial) |
| Train/Test Split | 80% / 20% (stratified) |
| Solver | L-BFGS with max 1000 iterations |
| Cross-Validation | 5-fold Stratified K-Fold |
| Regularization | C=1.0 (analyzed across [0.01, 0.1, 0.5, 1.0, 5.0, 10.0]) |
| # | Category | Description |
|---|---|---|
| 1 | π½οΈ Food & Dining | Restaurants, groceries, food delivery |
| 2 | π Transportation | Uber, fuel, public transit |
| 3 | ποΈ Shopping | Clothing, electronics, online orders |
| 4 | π¬ Entertainment | Movies, subscriptions, events |
| 5 | π Bills & Utilities | Electricity, internet, phone bills |
| 6 | π₯ Healthcare | Pharmacy, doctor visits, insurance |
| 7 | π Education | Tuition, books, courses |
| 8 | π·οΈ Other | Miscellaneous expenses |
The pipeline generates 8 publication-quality visualizations during training:
| Visualization | Description |
|---|---|
class_distribution.png |
Bar chart of expense category distribution |
word_cloud.png |
Word cloud from expense descriptions |
amount_distribution.png |
Box plot of amounts per category |
monthly_spending.png |
Monthly spending trend with area fill |
spending_trends.png |
Stacked bar β monthly spending by category |
category_pie.png |
Donut chart of total spending distribution |
confusion_matrix.png |
Heatmap of model prediction performance |
cross_validation.png |
CV scores + regularization analysis |
After training, 4 serialized model files are saved to ml/models/:
| File | Purpose |
|---|---|
category_model.pkl |
Trained Logistic Regression classifier |
tfidf_vectorizer.pkl |
Fitted TF-IDF vectorizer (vocabulary) |
scaler.pkl |
Fitted StandardScaler (mean, std) |
label_encoder.pkl |
Category label β integer mapping |
The SmartInsightsEngine class (ml/smart_insights.py) performs 7 types of statistical analysis:
- High Spending Alerts β Flags categories >1.5Ο above mean
- Unusual Transaction Detection β IQR-based outlier detection per category
- Monthly Trend Analysis β Detects rising/falling spending patterns
- Category Dominance β Alerts when a single category exceeds 30% of total
- Weekend vs. Weekday Patterns β Compares average daily spending
- Savings Recommendations β Suggests 10β20% reductions on discretionary categories
- Spending Velocity β Monitors transaction frequency for impulse detection
The Spark module (spark/spark_analytics.py) connects to the MySQL database via JDBC, ingests raw expense data into distributed DataFrames, and computes 5 types of analytics which are written back to dedicated summary tables.
-
Install PySpark:
cd spark pip install -r requirements.txt -
Download MySQL JDBC driver:
- Get
mysql-connector-j-8.x.x.jarfrom MySQL Downloads - Place in Spark's
jars/directory or specify via--jarsflag
- Get
-
Run the pipeline:
spark-submit --jars <path-to-mysql-connector-j.jar> spark_analytics.py
Or use the convenience script:
run_spark.bat
- Per-user monthly aggregation: total, average, min, max, transaction count
- Uses Spark UDFs for month name mapping
- Category-wise spending per user per month
- Window functions calculate percentage share within each user-month
- Weekly: ISO 8601 week-based trends (last 12 weeks) with date range labels
- Monthly: Calendar month trends (last 12 months)
- Yearly: Full calendar year comparisons
- Includes average daily burn rate at each granularity
- Spending Spike Detection β Compares current month vs. previous month per category; alerts on >25% increases with severity levels (
warningat 25%+,criticalat 75%+) - End-of-Month Projection β Projects total spending from daily burn rate and compares against last month's actual total
- Category Optimization β Identifies highest growth category and suggests capped budgets (110% of last month)
- Weekend vs. Weekday Pattern β Analyzes spending ratio and estimates monthly savings potential
MySQL (XAMPP) Apache Spark (local[*])
ββββββββββββββ JDBC βββββββββββββββββββββββββββββ
β expenses ββββββββββββββΊβ DataFrame: expenses_df β
β categoriesββββββββββββββΊβ DataFrame: categories_df β
ββββββββββββββ βββββββββββββ¬ββββββββββββββββ
β
βββββββββββββΌββββββββββββββββ
β Spark Transformations β
β β’ groupBy / agg β
β β’ Window functions β
β β’ UDFs β
β β’ Joins β
βββββββββββββ¬ββββββββββββββββ
β
βββββββββββββΌββββββββββββββββ
MySQL (XAMPP) JDBC β Computed DataFrames β
ββββββββββββββββββββββββββββ β’ monthly_summary β
β monthly_summaryβ β β’ category_summary β
β category_summaryβ β β’ trend_summary β
β trend_summary β β β’ spark_insights β
β spark_insights β β β’ spark_recommendations β
β spark_recommen.β βββββββββββββββββββββββββββββ
ββββββββββββββββββ
The application supports three authentication modes:
Traditional email + password authentication with:
- bcrypt password hashing (
PASSWORD_DEFAULT) - Brute-force protection β 5 failed attempts β 15-minute lockout
- Remember Me β 30-day persistent session using SHA-256 hashed tokens
Passwordless authentication flow:
- User enters email β system generates 6-digit OTP
- OTP is hashed with bcrypt and stored in the database
- OTP expires after a configurable window (default: 10 minutes)
- Rate limited to 3 sends per 10-minute window
- No registration required
- Data stored in localStorage (browser-only)
- Full dashboard access with limited features
- Seamless upgrade path to registered account
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/auth.php?action=signup |
Register new user |
POST |
/api/auth.php?action=login |
Password login |
POST |
/api/auth.php?action=send_otp |
Send OTP to email |
POST |
/api/auth.php?action=verify_otp |
Verify OTP & login |
POST |
/api/auth.php?action=resend_otp |
Resend OTP |
GET |
/api/auth.php?action=logout |
Logout & clear session |
GET |
/api/auth.php?action=guest |
Activate guest mode |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/expenses.php |
Get all expenses (with filters) |
POST |
/api/expenses.php |
Create new expense |
PUT |
/api/expenses.php?id={id} |
Update expense |
DELETE |
/api/expenses.php?id={id} |
Delete expense |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/categories.php |
List all categories |
POST |
/api/categories.php |
Create category |
PUT |
/api/categories.php?id={id} |
Update category |
DELETE |
/api/categories.php?id={id} |
Delete category |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/budget.php |
Get budget data |
POST |
/api/budget.php |
Set / update budget |
| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
Health check & model info |
POST |
/predict |
Predict category (single) |
POST |
/predict/batch |
Batch category prediction |
GET |
/insights |
Demo insights (training data) |
POST |
/insights |
Custom data insights |
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"description": "swiggy lunch", "amount": 350}'{
"predicted_category": "Food",
"confidence": 0.9234,
"all_probabilities": {
"Food": 0.9234,
"Shopping": 0.0312,
"Entertainment": 0.0198,
"...": "..."
}
}| Method | Endpoint | Description |
|---|---|---|
GET |
/api/spark_summary.php?type=monthly |
Monthly aggregated data |
GET |
/api/spark_summary.php?type=category |
Category breakdown |
GET |
/api/spark_summary.php?type=trends |
Spending trends |
GET |
/api/spark_summary.php?type=insights |
Spark-generated insights |
GET |
/api/spark_summary.php?type=recommendations |
Smart recommendations |
users β User accounts with OTP & rate-limit fields
βββ id, username, email, password
βββ otp_code, otp_expires_at, otp_attempts, otp_last_sent_at
βββ login_attempts, login_locked_until
βββ remember_token, remember_expires_at
categories β User-defined expense categories
βββ id, user_id (FK), name, color, icon
βββ budget (per-category monthly budget)
expenses β Individual expense transactions
βββ id, user_id (FK), category_id (FK)
βββ amount, description, notes
βββ expense_date, created_at, updated_atmonthly_summary β Monthly totals per user
category_summary β Category-wise spending per user/month
trend_summary β Weekly/monthly/yearly trends
spark_insights β AI-generated spending insights
spark_recommendations β Personalized savings recommendationsexpense-tracker/
β
βββ api/ # RESTful API endpoints (PHP)
β βββ auth.php # Authentication (signup, login, OTP, guest)
β βββ expenses.php # Expense CRUD operations
β βββ categories.php # Category management
β βββ budget.php # Budget management
β βββ budget_alerts.php # Budget overspend alerts
β βββ ml_suggestions.php # ML-powered suggestions (PHP β Flask bridge)
β βββ predict_category.php # Category prediction proxy
β βββ spark_summary.php # Spark analytics data API
β
βββ assets/
β βββ css/ # Stylesheets
β β βββ style.css # Global styles (Shadcn-inspired design system)
β β βββ auth.css # Authentication pages
β β βββ dashboard.css # Dashboard layout
β β βββ expenses.css # Expense management
β β βββ categories.css # Category management
β β βββ reports.css # Reports page
β β βββ spark_analytics.css # Spark analytics UI
β βββ js/ # Client-side JavaScript
β βββ dashboard.js # Dashboard logic & charts
β βββ expenses.js # Expense CRUD & filtering
β βββ categories.js # Category management
β βββ reports.js # Reports & visualizations
β βββ guest.js # Guest mode (localStorage)
β βββ spark_analytics.js # Spark analytics UI
β βββ main.js # Shared utilities
β βββ theme.js # Dark/light theme toggle
β
βββ config/ # Server configuration
β βββ database.php # MySQL connection (PDO)
β βββ session.php # Session management & auth helpers
β βββ mail.php # Email (OTP delivery) configuration
β βββ sidebar.php # Shared navigation sidebar component
β
βββ database/ # SQL schema & migrations
β βββ schema.sql # Base schema (users, categories, expenses)
β βββ migrate_auth.sql # OTP & rate-limiting columns
β βββ spark_tables.sql # Spark analytics summary tables
β βββ add_budget_column.sql # Budget field migration
β βββ add_budget_alerts.sql # Alert tables
β βββ add_notes_column.sql # Notes field migration
β βββ complete_update.sql # Consolidated migration
β βββ import_csv_data.sql # Sample data import
β
βββ ml/ # Machine Learning module
β βββ expense_ai.py # Full ML pipeline (EDA β Train β Evaluate β Save)
β βββ predict_api.py # Flask REST API for predictions
β βββ smart_insights.py # Statistical insights engine (7 analysis types)
β βββ requirements.txt # Python dependencies
β βββ dataset/ # Training data
β β βββ expense_dataset1.csv # 302 records
β β βββ expense_dataset2.csv # 300 records
β βββ models/ # Serialized trained models
β β βββ category_model.pkl
β β βββ tfidf_vectorizer.pkl
β β βββ scaler.pkl
β β βββ label_encoder.pkl
β βββ visualizations/ # Generated EDA charts (8 plots)
β
βββ spark/ # Apache Spark analytics module
β βββ spark_analytics.py # Main Spark pipeline (5 analytics)
β βββ generate_sample_data.py # Test data generator
β βββ run_spark.bat # Windows launch script
β βββ requirements.txt # PySpark dependencies
β
βββ index.php # Login page (split-screen UI)
βββ signup.php # Registration page
βββ dashboard.php # Main dashboard
βββ expenses.php # Expense management page
βββ categories.php # Category management page
βββ reports.php # Reports & analytics page
βββ spark_analytics.php # Spark analytics dashboard
βββ migrate_account.php # Account migration utility
β
βββ Dockerfile # Docker deployment config
βββ .htaccess # Apache URL rewriting
βββ LICENSE # MIT License
βββ README.md # This file
| Feature | Implementation |
|---|---|
| Password Hashing | bcrypt via password_hash() (cost factor 10) |
| SQL Injection Prevention | Prepared statements on all queries |
| XSS Protection | Output escaping with htmlspecialchars() |
| CSRF Protection | Token-based validation on forms |
| Session Security | Secure session configuration, regeneration on login |
| Rate Limiting | Login (5 attempts / 15-min lock), OTP (3 sends / 10-min window) |
| OTP Security | Hashed storage (bcrypt), configurable expiry, auto-invalidation |
| Remember Me | SHA-256 hashed tokens with 30-day expiry |
| Input Validation | Server-side + client-side validation on all inputs |
The application features a modern, dark-themed UI inspired by Shadcn design principles with glassmorphism effects, smooth animations, and responsive layouts.
| Page | Description |
|---|---|
| Login | Split-screen layout with password + OTP tabs |
| Dashboard | Financial overview with charts, metrics, and AI insights |
| Expenses | Searchable, filterable transaction table with inline editing |
| Categories | Color-coded category cards with budget progress bars |
| Reports | Date-range reports with exportable charts |
| Spark Analytics | Big data insights dashboard with trend visualizations |
- Core expense CRUD with categories
- Interactive dashboard with Chart.js
- ML-based category prediction
- Smart spending insights engine
- Apache Spark analytics pipeline
- OTP-based authentication
- Guest mode with localStorage
- Monthly budget management
- Dark/light theme toggle
- Recurring expenses
- Export to CSV / PDF
- Multi-currency support
- Mobile-responsive PWA
- Receipt OCR scanning
This project is licensed under the MIT License β see the LICENSE file for details.
Built with β€οΈ as a major academic project β combining full-stack web development, machine learning, and big data analytics.
If you found this useful, consider giving it a β