PERSONAL EXPENSE TRACKER CODE IN PYTHON

Project Overview: Personal Expense Tracker

Features:

  1. User Authentication: Allow users to create an account and log in.
  2. Add Expenses: Users can add expenses with details such as amount, category (e.g., food, transportation, entertainment), and date.
  3. View Expenses: Display a list of expenses, filtered by date or category.
  4. Budget Management: Set a monthly budget and track spending against that budget.
  5. Data Visualization: Use charts to show spending patterns over time (daily, weekly, monthly).
  6. Export Data: Allow users to export their expense data to a CSV file for further analysis.

Technologies Used:

  • Python: For the backend logic.
  • SQLite: As a lightweight database to store user data and expenses.
  • Matplotlib or Plotly: For data visualization.
  • Flask: As a web framework for handling requests and rendering templates.
  • HTML/CSS: For front-end development to create a user-friendly interface.

Step-by-Step Implementation:

1. Setup Environment

  • Install required packages:bash
Step-by-Step Implementation:
1. Setup Environment
Install required packages:
bash
Bash

2. Create the Database Model

Create a models.py file to define the user and expense tables.

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(100), nullable=False)
    expenses = db.relationship('Expense', backref='owner', lazy=True)

class Expense(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    amount = db.Column(db.Float, nullable=False)
    category = db.Column(db.String(50), nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
Python

3. Initialize Flask App

Create a app.py file to handle routes and application logic.

from flask import Flask, render_template, request, redirect, url_for, flash
from models import db, User, Expense

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///expenses.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db.init_app(app)

with app.app_context():
    db.create_all()

@app.route('/')
def index():
    return render_template('index.html')

# Additional routes will go here

if __name__ == '__main__':
    app.run(debug=True)
Python

4. Implement User Authentication

Add routes for user registration and login.

from flask import session, redirect, url_for

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        new_user = User(username=username, password=password)
        db.session.add(new_user)
        db.session.commit()
        flash('Registration successful! Please log in.')
        return redirect(url_for('login'))
    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username, password=password).first()
        if user:
            session['user_id'] = user.id
            flash('Login successful!')
            return redirect(url_for('dashboard'))
        flash('Invalid username or password')
    return render_template('login.html')
Python

5. Add and View Expenses

Implement routes to add and view expenses

@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
    if request.method == 'POST':
        amount = request.form['amount']
        category = request.form['category']
        new_expense = Expense(amount=amount, category=category, user_id=session['user_id'])
        db.session.add(new_expense)
        db.session.commit()
        flash('Expense added successfully!')
    expenses = Expense.query.filter_by(user_id=session['user_id']).all()
    return render_template('dashboard.html', expenses=expenses)
Python

6. Data Visualization

Use Matplotlib to visualize expenses.

import matplotlib.pyplot as plt

@app.route('/visualize')
def visualize():
    expenses = Expense.query.filter_by(user_id=session['user_id']).all()
    categories = {}
    for expense in expenses:
        categories[expense.category] = categories.get(expense.category, 0) + expense.amount

    plt.bar(categories.keys(), categories.values())
    plt.xlabel('Categories')
    plt.ylabel('Amount Spent')
    plt.title('Expenses by Category')
    plt.savefig('static/expenses.png')
    return render_template('visualize.html', plot='static/expenses.png')
Python

7. Exporting Data

Add functionality to export expense data to CSV.

import csv

@app.route('/export')
def export():
    expenses = Expense.query.filter_by(user_id=session['user_id']).all()
    with open('expenses.csv', 'w', newline='') as csvfile:
        fieldnames = ['id', 'amount', 'category', 'date']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for expense in expenses:
            writer.writerow({'id': expense.id, 'amount': expense.amount, 'category': expense.category, 'date': expense.date})
    flash('Data exported to expenses.csv')
    return redirect(url_for('dashboard'))
Python

Create HTML Templates

Create templates/index.html, templates/login.html, templates/register.html, templates/dashboard.html, and templates/visualize.html for the user interface.

<!-- Example: templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expense Tracker</title>
</head>
<body>
    <h1>Welcome to the Expense Tracker</h1>
    <a href="{{ url_for('register') }}">Register</a>
    <a href="{{ url_for('login') }}">Login</a>
</body>
</html>
Python

Conclusion

This Personal Expense Tracker project provides a comprehensive learning experience with Python and web development concepts. You can further enhance it by adding features like user roles, mobile responsiveness, and using a more sophisticated database like PostgreSQL or MongoDB.

Feel free to modify the project to suit your needs, and happy coding! If you need any more specific details or additional features, let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *


error: Content is protected !!
Scroll to Top
MacroNepal
Verified by MonsterInsights