0% found this document useful (0 votes)
13 views3 pages

Tracker

This document is a Python script for an expense tracker application that connects to a MySQL database. It allows users to add, view, delete expenses, and generate monthly expense reports with visualizations using Matplotlib. The script includes a menu-driven interface for user interaction and handles various functionalities related to expense management.

Uploaded by

baracktrump185
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

Tracker

This document is a Python script for an expense tracker application that connects to a MySQL database. It allows users to add, view, delete expenses, and generate monthly expense reports with visualizations using Matplotlib. The script includes a menu-driven interface for user interaction and handles various functionalities related to expense management.

Uploaded by

baracktrump185
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import mysql.

connector

import pandas as pd
import matplotlib.pyplot as plt

pwd = input("Enter database password: ")

# Connect to MySQL Database


mydb = mysql.connector.connect(
host="127.0.0.1",
user="root", # Enter your MySQL username
password=pwd, # Enter your MySQL password
database="expense_tracker" # The database we created earlier
)

# Create a cursor object to execute SQL queries


cursor = mydb.cursor()

# Function to add a new expense


def add_expense(date, category, amount, description):
query = "INSERT INTO expenses (date, category, amount, description) VALUES (%s,
%s, %s, %s)"
values = (date, category, amount, description)
cursor.execute(query, values)
mydb.commit()
print("Expense added successfully.")

# Function to view all expenses


def view_expenses():
query = "SELECT * FROM expenses"
cursor.execute(query)
result = cursor.fetchall()
tot=0
if result:
print("\nAll Expenses:")
for expense in result:
print(f"ID: {expense[0]}, Date: {expense[1]}, Category: {expense[2]},
Amount: {expense[3]}, Description: {expense[4]}")
tot+=expense[3]
print("TOTAL EXPENSE: {}".format(tot))
else:
print("\nNo expenses recorded yet.")

# Function to view expenses by category


def view_expenses_by_category(category):
query = "SELECT * FROM expenses WHERE category = %s"
cursor.execute(query, (category,))
tot=0
result = cursor.fetchall()
if result:
print(f"\nExpenses in category '{category}':")
for expense in result:
print(f"ID: {expense[0]}, Date: {expense[1]}, Category: {expense[2]},
Amount: {expense[3]}, Description: {expense[4]}")
tot+=expense[3]
print("TOTAL CATEGORY EXPENSE: {}".format(tot))
else:
print(f"\nNo expenses found in category '{category}'.")
# Function to delete an expense by ID
def delete_expense(expense_id):
query = "DELETE FROM expenses WHERE id = %s"
cursor.execute(query, (expense_id,))
mydb.commit()
print("Expense deleted successfully.")

def monthly_expenses_table():
# Query to get total expenses grouped by month
query = """
SELECT
DATE_FORMAT(date, '%Y-%m') AS month,
SUM(amount) AS total_expense
FROM expenses
GROUP BY month
ORDER BY month;
"""
cursor.execute(query)
res = cursor.fetchall()

if res:
df = pd.DataFrame(res, columns=['Month', 'Total Expense'])

df['Total Expense'] = pd.to_numeric(df['Total Expense'], errors='coerce')

print("\nMonthly Expenses Table:")


print(df)

df.plot(kind='line', x='Month', y='Total Expense', color='skyblue',


marker='o')
plt.xlabel("Month")
plt.ylabel("Total Expense")
plt.title("Monthly Expenses")
plt.xticks(rotation=45)
plt.grid(True)
plt.tight_layout()
plt.show()

else:
print("\nNo expenses recorded yet.")

# Main function to display the menu and take user input


def menu():
while True:
print("\nExpense Tracker Menu:")
print("1. Add a new expense")
print("2. View all expenses")
print("3. View expenses by category")
print("4. Delete an expense")
print("5. Show Expense Chart")
print("6. Exit")

choice = input("Enter your choice (1-6): ")

if choice == "1":
date = input("Enter date (YYYY-MM-DD): ")
category = input("Enter category (e.g., Food, Transport,
Entertainment): ")
amount = float(input("Enter amount: "))
description = input("Enter description: ")
add_expense(date, category, amount, description)

elif choice == "2":


view_expenses()

elif choice == "3":


category = input("Enter category to filter: ")
view_expenses_by_category(category)

elif choice == "4":


expense_id = int(input("Enter the expense ID to delete: "))
delete_expense(expense_id)

elif choice == "5":


print("Showing Graph")
monthly_expenses_table()
print("Exiting Expense Tracker. Goodbye!")
break

elif choice == "6":


print("Exiting Expense Tracker. Goodbye!")
break

else:
print("Invalid choice. Please try again.")

# Run the menu


menu()

# Close the database connection when done


cursor.close()
mydb.close()

You might also like