0% found this document useful (0 votes)
12 views

code

Uploaded by

rastogiamber580
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

code

Uploaded by

rastogiamber580
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

#Importing the necessary modules

import mysql.connector
import datetime
from datetime import datetime
from datetime import date

# Connecting to the MySQL database


db = mysql.connector.connect(host="localhost", user="root",
passwd="pass", database="expense_tracker")

#Creating a cursor object to execute SQL queries


cursor = db.cursor()

#Creating a table to store the expense records


cursor.execute("CREATE TABLE IF NOT EXISTS expenses (id INT
AUTO_INCREMENT PRIMARY KEY, date DATE, category VARCHAR(255), description
VARCHAR(255), amount DECIMAL(10,2))")

#A function to insert a new expense record into the table


def add_expense(date, category, description, amount):
sql = "INSERT INTO expenses (date, category, description, amount)
VALUES (%s, %s, %s, %s)"
val = (date, category, description, amount)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record(s) inserted.")

#A function to display all the expense records from the table


def show_expenses():
print("")
sql = "SELECT * FROM expenses"
cursor.execute(sql)
result = cursor.fetchall()
print("| ID"," "*3,
"| Date"," "*16,
"| Category"," "*12,
"| Description"," "*39,
"| Amount"," "*14, "|")
for row in result:
print("|",row[0]," "*(5-len(str(row[0]))), "|",
row[1]," "*10, "|",
row[2]," "*(20 - len(row[2])), "|",
row[3]," "*(50 - len(row[3])), "|",
row[4]," "*(20 - len(str(row[4]))), "|")

# A function to display the total expenses by category


def show_total_by_category():
sql = "SELECT category, SUM(amount) FROM expenses GROUP BY category"
cursor.execute(sql)
result = cursor.fetchall()
print("| Category"," "*12,
"| Total"," "*15, "|")
for row in result:
print("|",row[0]," "*(20-len(row[0])), "|",
row[1]," "*(20 - len(str(row[1]))), "|")

# A function to display the total exp by month


def show_total_by_month():
sql = "SELECT MONTH(date), SUM(amount) FROM expenses GROUP BY
MONTH(date)"
cursor.execute(sql)
result = cursor.fetchall()
result=[list(x) for x in result]
for row in result:

row[0]=['January','February','March','April','May','June','July','August'
,'September','October','November','December'][row[0]-1]
print("| Month"," "*15,
"| Total"," "*15, "|")
for row in result:
print("|",row[0]," "*(20 - len(row[0])), "|",
row[1]," "*(20 - len(str(row[1]))), "|")

# A function to delete an expense record by id


def delete_expense(id):
sql = "DELETE FROM expenses WHERE id = %s"
val = (id,)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record deleted.")

#A function to update an expense record by id


def update_expense(id, date, category, description, amount):
sql = "UPDATE expenses SET date = %s, category = %s, description =
%s, amount = %s WHERE id = %s"
val = (date, category, description, amount, id)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record updated.")

# a function to delete all expenses


def delete_all_expenses():
delete_query = "DELETE FROM expenses"
try:
# Execute the delete command
cursor.execute(delete_query)
db.commit()
print("All expenses have been deleted successfully.")
except:
print(f"Error occurred while deleting expenses: {error}")

def view_expense_details(id):
query = "SELECT * FROM expenses WHERE id = %s"
cursor.execute(query, (id,))
result = cursor.fetchone()
# Check if we found the expense
if result:
# Print the expense details
print("Expense Details:")
print("Expense Category- " + str(result[2]))
print("Expense Description- " + str(result[3]))
print("Amount- " + str(result[4]))
print("Expense Date- " + str(result[1]))
else:
print("Expense not found!")
# Function to show weekly total expenses
def show_weekly_expenses():
query = """
SELECT YEAR(date), WEEK(date), SUM(amount)
FROM expenses
GROUP BY YEAR(date), WEEK(date)
ORDER BY YEAR(date), WEEK(date)
"""
cursor.execute(query)
result = cursor.fetchall()
print("| Year"," "*6,
"| Week"," "*6,
"| Total Expenses"," "*6, "|")
# Loop through the result and print each week's expenses
for row in result:
print("|",row[0]," "*(10-len(str(row[0]))), "|",
row[1]," "*(10-len(str(row[1]))), "|",
row[2]," "*(20 - len(str(row[2]))), "|")

# A function to display expenses whose amount is within given range


def show_expenses_by_amount_range(m,M):
query ="SELECT id, date, category, description, amount FROM expenses
WHERE amount > "+str(m)+" AND amount <"+str(M)
cursor.execute(query)
expenses = cursor.fetchall()
if expenses:
print("| ID"," "*3,
"| Date"," "*16,
"| Category"," "*12,
"| Description"," "*39,
"| Amount"," "*14, "|")

# Loop through the expenses and print them


if expense:
for expense in expenses:
print("|",expense[0]," "*(5-len(str(expense[0]))), "|",
expense[1]," "*10, "|",
expense[2]," "*(20 - len(expense[2])), "|",
expense[3]," "*(50 - len(expense[3])), "|",
expense[4]," "*(20 - len(str(expense[4]))), "|")
else:
print("No expenses found within the specified amount range.")

# A function to display the maximum amount in expenses


def show_maximum_amount():
sql = "SELECT MAX(amount) FROM expenses"
cursor.execute(sql)
result = cursor.fetchone()
if result and result[0] is not None:
print("The maximum amount in the expenses is: " + str(result[0]))
else:
# If no expenses are found, print a message
print("No expenses found.")

# A function to display the minimum amount in expenses


def show_minimum_amount():
sql = "SELECT MIN(amount) FROM expenses"
cursor.execute(sql)
result = cursor.fetchone()
if result and result[0] is not None:
print("The minimum amount in the expenses is: " + str(result[0]))
else:
# If no expenses are found, print a message
print("No expenses found.")

# a function to show average amount in expenses


def show_average_amount():
sql = "SELECT AVG(amount) FROM expenses"
cursor.execute(sql)
result = cursor.fetchone()
if result and result[0] is not None:
print("Average expenditure is: " + str(result[0]))
else:
print("No expenses found.")

# Function to display total expenses by year and month


def show_monthly_expenses_trends():
query = """
SELECT YEAR(date), MONTH(date), SUM(amount)
FROM expenses
GROUP BY YEAR(date), MONTH(date)
ORDER BY YEAR(date), MONTH(date)
"""
cursor.execute(query)
result = cursor.fetchall()
print("| Year"," "*6,
"| Month"," "*5,
"| Total Expenses"," "*6, "|")
# Loop through the result and print each month's expenses
for row in result:
print("|",row[0]," "*(10-len(str(row[0]))), "|",
row[1]," "*(10-len(str(row[1]))), "|",
row[2]," "*(20 - len(str(row[2]))), "|")

# Function to display the most expensive expense


def show_most_expensive_expense():
query = "SELECT * FROM expenses ORDER BY amount DESC LIMIT 1"
cursor.execute(query)
expense = cursor.fetchone()
# Check if an expense was found
if expense:
print("Most Expensive Expense: ID: " + str(expense[0]) +
", Date: " + str(expense[1]) +
", Category: " + str(expense[2]) +
", Description: " + str(expense[3]) +
", Amount: " + str(expense[4]))
else:
# If no expenses are found
print("No expenses found.")

# Function to display the least expensive expense


def show_least_expensive_expense():
query = "SELECT * FROM expenses ORDER BY amount ASC LIMIT 1"
cursor.execute(query)
expense = cursor.fetchone()
if expense:
print("Least Expensive Expense: ID: " + str(expense[0]) +
", Date: " + str(expense[1]) +
", Category: " + str(expense[2]) +
", Description: " + str(expense[3]) +
", Amount: " + str(expense[4]))
else:
# If no expenses are found
print("No expenses found.")

# Function to display total expenses by year


def show_yearly_expenses():
query = """
SELECT YEAR(date), SUM(amount)
FROM expenses
GROUP BY YEAR(date)
ORDER BY YEAR(date)
"""
cursor.execute(query)
result = cursor.fetchall()
print("| Year"," "*6,
"| Total Expenses"," "*6, "|")
for row in result:
print("|",row[0]," "*(10-len(str(row[0]))), "|",
round(row[1],2)," "*(20-len(str(row[1]))), "|")

# Function to show daily total expenses


def show_daily_expenses():
query = """
SELECT date, SUM(amount)
FROM expenses
GROUP BY date
ORDER BY date
"""
cursor.execute(query)
result = cursor.fetchall()
print("| Date"," "*6,
"| Total Expenses"," "*6, "|")
for row in result:
print("|",row[0]," "*(10-len(str(row[0]))), "|",
row[1]," "*(20-len(str(round(row[1],2)))), "|")

# Function to display expenses within a date range


def show_expenses_by_date_range(start_date, end_date):
query = """
SELECT id, date, category, description, amount
FROM expenses
WHERE date BETWEEN %s AND %s
"""
cursor.execute(query, (start_date, end_date))
expenses = cursor.fetchall()
# Check if any expenses are found
if expenses:
# Print the header
print("| ID"," "*3,
"| Date"," "*16,
"| Category"," "*12,
"| Description"," "*39,
"| Amount"," "*14, "|")
# Loop through the expenses and print each one
for expense in expenses:
print("|",expense[0]," "*(5-len(str(expense[0]))), "|",
expense[1]," "*10, "|",
expense[2]," "*(20 - len(expense[2])), "|",
expense[3]," "*(50 - len(expense[3])), "|",
expense[4]," "*(20 - len(str(expense[4]))), "|")
else:
# If no expenses found, print a message
print("No expenses found between " + str(start_date) + " and " +
str(end_date) + ".")

# Function to search expenses by keyword in category or description


def search_expenses(keyword):
query = """
SELECT id, date, category, description, amount
FROM expenses
WHERE category LIKE %s OR description LIKE %s
"""
cursor.execute(query, (f"%{keyword}%", f"%{keyword}%"))
expenses = cursor.fetchall()
if expenses:
# Print the header
print("| ID"," "*3,
"| Date"," "*16,
"| Category"," "*12,
"| Description"," "*39,
"| Amount"," "*14, "|")

# Loop through the expenses and print each one


for expense in expenses:
print("|",expense[0]," "*(5-len(str(expense[0]))), "|",
expense[1]," "*10, "|",
expense[2]," "*(20 - len(expense[2])), "|",
expense[3]," "*(50 - len(expense[3])), "|",
expense[4]," "*(20 - len(str(expense[4]))), "|")
else:
# If no expenses are found, print a message
print("No expenses found matching '" + str(keyword) + "'.")

#a function to show expenses of past 30 days


def show_expenses_last_30_days():
query = """
SELECT * FROM expenses
WHERE date >= CURDATE() - INTERVAL 30 DAY
"""
cursor.execute(query)
expenses = cursor.fetchall()
# Check if any expenses were found
if expenses:
# Print the header
print("Expenses from the last 30 days:")
print("| ID"," "*3,
"| Date"," "*16,
"| Category"," "*12,
"| Description"," "*39,
"| Amount"," "*14, "|")
# Loop through the expenses and print each one
for expense in expenses:
print("|",expense[0]," "*(5-len(str(expense[0]))), "|",
expense[1]," "*10, "|",
expense[2]," "*(20 - len(expense[2])), "|",
expense[3]," "*(50 - len(expense[3])), "|",
expense[4]," "*(20 - len(str(expense[4]))), "|")
else:
# If no expenses found, print a message
print("No expenses recorded in the last 30 days.")

# Function to Show Average Spend per Category:


def show_average_spend_per_category():
query = """
SELECT category, AVG(amount) AS average_amount
FROM expenses
GROUP BY category
"""
cursor.execute(query)
result = cursor.fetchall()
if result:
print("Average Spend Per Category:")
print("| Category"," "*12,
"| Average Amount"," "*6, "|")
# Loop through the results and print each category's average
spend
for row in result:
print("|",row[0]," "*(20-len(str(row[0]))), "|",
row[1]," "*(20-len(str(row[1]))), "|")
else:
# If no results, print a message
print("No expenses recorded yet.")
#Function to Search Expenses by Amount Range:
def search_expenses_by_amount_range(min_amount, max_amount):
query = """
SELECT id, date, category, description, amount
FROM expenses
WHERE amount BETWEEN %s AND %s
"""
cursor.execute(query, (min_amount, max_amount))
result = cursor.fetchall()
# Check if any results are found
if result:
# Print the header
print("Expenses between " + str(min_amount) + " and " +
str(max_amount) + ":")
print("| ID"," "*3,
"| Date"," "*16,
"| Category"," "*12,
"| Description"," "*39,
"| Amount"," "*14, "|")
# Loop through the results and print each expense
for row in result:
print("|",row[0]," "*(5-len(str(row[0]))), "|",
row[1]," "*10, "|",
row[2]," "*(20 - len(row[2])), "|",
row[3]," "*(50 - len(row[3])), "|",
row[4]," "*(20 - len(str(row[4]))), "|")
else:
# If no expenses found, print a message
print("No expenses found in the range " + str(min_amount) + " to
" + str(max_amount) + ".")

#a function to calculate savings


def calculate_savings(Budget, Month):
y= datetime.today().strftime("%Y")
query = """
SELECT SUM(amount)
FROM expenses
WHERE YEAR(date) = %s AND MONTH(date) = %s
"""
cursor.execute(query, (y,Month))
result = cursor.fetchone()
if result[0] is not None:
total_expenses = result[0]
else:
total_expenses = 0
savings = Budget - total_expenses
if savings>0:
print("Savings for month " + str(month) + ": " + str(savings))
elif savings<=0:
print("YOU HAVE SPENT Rs.",-1*savings,"MORE THAN YOUR BUDGET THIS
MONTH")
print("SAVE SOME MONEY FOR A RAINY DAY")
#A function to display the menu options
def show_menu():
print("Please choose an option:")
print("1. Add a new expense")
print("2. Show all expenses")
print("3. Show total expenses by category")
print("4. Show total expenses by month")
print("5. Delete an expense")
print("6. Update an expense")
print("7. clear all records")
print("8. view expense details")
print("9. show weekly expense")
print("10. show the maximum amount in expenses")
print("11. show the minimum amount in expenses")
print("12. show the average amount ")
print("13. View expenses where the amount is within given range")
print("14. Show monthly spending trends")
print("15. Show most expensive expense")
print("16. Show least expensive expense")
print("17. Show yearly spending trends")
print("18. Show daily expenses")
print("19. Show expenses by date range")
print("20. Search expenses by description/category")
print("21. Show expenses from the last 30 days")
print("22. Show Average Spend per Category")
print("23. Search Expenses by Amount Range")
print("24. Enter Budget")
print("25. View saving/overspending report")
print("26. Exit")
# A loop to run the menu until the user chooses to exit
print("Welcome to the Expense Tracker!")
while True:
print(" ")
show_menu()
choice = input("Enter your choice: ")
if choice == "1":
try:
d = input("Enter the date (YYYY-MM-DD): ")
d1 = datetime.strptime(d,'%Y-%m-%d').date()
if d1<=date.today():
category = input("Enter the category (Assign a label to
your expense based on the type or purpose of the spending. Eg: food,
rent, utilities, entertainment, etc.): ")
description = input("Enter the description [Add a brief
note of the expense. Eg: 'groceries for the week' or 'electricity bill
for June' etc.]: ")
amount = input("Enter the amount: ")
try:
add_expense(d, category, description, amount)
except:
print('invalid entry')
elif d1>date.today():
print("Future date cannot be entered")
except:
print('invalid date entered')
elif choice == "2":
show_expenses()
elif choice == "3":
show_total_by_category()
elif choice == "4":
show_total_by_month()
elif choice == "5":
id = input("Enter the id of the expense to delete: ")
delete_expense(id)
elif choice == "6":
id = input("Enter the id of the expense to update: ")
date = input("Enter the new date (YYYY-MM-DD): ")
category = input("Enter the new category: ")
description = input("Enter the new description: ")
amount = input("Enter the new amount: ")
update_expense(id, date, category, description, amount)
elif choice == "7":
delete_all_expenses()
print("all the records are cleared!")
elif choice == "8":
id = input("Enter the id of the expense to view ")
view_expense_details(id)
elif choice =="9":
show_weekly_expenses()
elif choice == "10":
show_maximum_amount() # Call the function to show max amount
elif choice == "11":
show_minimum_amount() # Call the function to show min amount
elif choice == "12":
show_average_amount() # Call the function to show avg amount
elif choice == "13": # For viewing expenses in range 1000 to 10000
m=int(input("Enter lower limit of amount range - "))
M=int(input("Enter lower upper of amount range - "))
show_expenses_by_amount_range(m,M)
elif choice == "14":
show_monthly_expenses_trends()
elif choice == "15":
show_most_expensive_expense()
elif choice == "16":
show_least_expensive_expense()
elif choice == "17":
show_yearly_expenses()
elif choice == "18":
show_daily_expenses()
elif choice == "19":
start_date = input("Enter the start date (YYYY-MM-DD): ")
end_date = input("Enter the end date (YYYY-MM-DD): ")
show_expenses_by_date_range(start_date, end_date)
elif choice == "20":
keyword = input("Enter a keyword to search by
description/category: ")
search_expenses(keyword)
elif choice == "21":
show_expenses_last_30_days() # Call the function for last 30
days' expenses
elif choice=="22":
show_average_spend_per_category()
elif choice=="23":
# Prompt the user for the amount range
min_amount = float(input("Enter the minimum amount: "))
max_amount = float(input("Enter the maximum amount: "))
search_expenses_by_amount_range(min_amount, max_amount) # Call
the function
elif choice=="24":
budget=int(input("Enter your budget (in Rs.) - "))
elif choice=="25":
month = int(input("Enter the month (1-12): "))
'''try:'''
calculate_savings(budget, month)
'''except:
print("budget is not defined")'''
elif choice=="26":
break
else:
print("Invalid choice. Please try again.")

You might also like