Tech-savvy saving: how to build a budget tracker with a few lines of code in Python
Part 2 — Implementation
In this article, we will build a budget tracker program in Python based on the concept of functions and classes (the first part of the article containing an introduction to functions and classes in Python can be found here). Before having a look on the code, let us state the following requirements that the budget tracker has to have:
- The budget of the user is an object that is instantiated from a Budget class with an (initial) balance.
- Using that object, the user can record any income or expense values along with their category and the date of transaction.
- When recorded, the balance is adjusted accordingly. Moreover, the user can have a detailed look on the evolution of the expenses by taking into account the budget history. He/She can also view the allocation of expenses with respect to the category.
One method to implement such a budget tracker is to write the Budget class and its underlying attributes and methods in a Python .py file. The user can then instantiate his/her own budget object in the Python shell or any other integrated development environment (IDE) after importing that particular .py file.
A possible structure for the .py file is shown below:
import matplotlib.pyplot as plt
from datetime import datetime
class Budget:
budget_history = {
'income_value':[], 'income_category':[], 'income_date':[],
'expense_value':[],'expense_category':[],'expense_date':[]
}
def __init__(self, balance):
self.balance = balance
def addIncome(self, income, category, date):
self.balance += income
self.budget_history['income_value'].append(income)
self.budget_history['income_category'].append(category)
self.budget_history['income_date'].append(date)
def addExpense(self, expense, category, date):
self.balance -= expense
self.budget_history['expense_value'].append(expense)
self.budget_history['expense_category'].append(category)
self.budget_history['expense_date'].append(date)
def plotExpenseEvolution(self):
X = [x.day for x in self.budget_history['expense_date']]
Y = self.budget_history['expense_value']
plt.plot(X, Y, '-o')
plt.xlabel('Day of month')
plt.ylabel('Expense amount in USD')
plt.title('Expense overview - February')
def plotExpenseAllocation(self):
plt.pie(self.budget_history['expense_value'],
labels=self.budget_history['expense_category'],
autopct='%1.1f%%')
plt.title('Expense allocation - February')
Here, the class syntax contains the initial balance for instantiating a budget object, along with the addIncome and addExpense methods. When these are called on the budget object, the income or expense value is added (subtracted) to the balance, and the value is further appended to the budget_history dictionary, that stores all the transactions along with the income or expense category and the date. Once the information is entered to the dictionary, the user can plot the evolution of expenses with the plotExpenseEvolution, and their allocation with the plotExpenseAllocation methods, respectively (note that we do not consider the evolution of incomes, as we assume that only one monthly salary is entered as single source of income for the sake of simplicity). Finally, apart from the class syntax, the matplotlib library along with datetime is also imported, in order to create the plots and to assign a data to the budget history. Overall, the program contains 50 lines of code.
Given the above, you now have everything you need to create your own budget tracker. Within the Python shell (or the IDE), make sure to go to the same path where the .py file is stored. Here, I named the file as Expense_Tracker.py; the class definition together with the libraries can be imported by entering the following command in the shell (without the .py file extension!)
from Expense_Tracker import *
Let’s assume that for an arbitrary month, e.g., February, the initial balance in your account was 2000 $ as of Feb 1st. You can instantiate your budget object as:
myBudget = Budget(balance=2000)
In addition, assume that you had the following income and expenses in the first week of February:
- Salary: +3000 $, Date: Feb 1st
- Monthly rent: -1000 $, Date: Feb 1st
- Groceries: -75 $, Date: Feb 3rd
- Electricity: -80 $, Date: Feb 5th
- Phone bill: -100 $, Date: Feb 6th
These along with their respective categories and dates are entered as follows:
myBudget.addIncome(3000, 'Salary', datetime(2024, 2, 1))
myBudget.addExpense(1000, 'Monthly rent', datetime(2024, 2, 1))
myBudget.addExpense(75, 'Groceries', datetime(2024, 2, 3))
myBudget.addExpense(80, 'Electricity', datetime(2024, 2, 5))
myBudget.addExpense(100, 'Phone bill', datetime(2024, 2, 6))
After inserting, you can check the current balance at any time by
myBudget.balance #Returns 3745 $
Now let us consider the evolution of expenses. To view the raw data, simply call the budget_history dictionary
myBudget.budget_history
#Returns
#{'income_value': [3000],
#'income_category': ['Salary'],
#'income_date': [datetime.datetime(2024, 2, 1, 0, 0)],
#'expense_value': [1000, 75, 80, 100],
#'expense_category': ['Monthly rent', 'Groceries', 'Electricity', 'Phone bill'],
#'expense_date': [datetime.datetime(2024, 2, 1, 0, 0), datetime.datetime(2024, 2, 3, 0, 0), datetime.datetime(2024, 2, 5, 0, 0), datetime.datetime(2024, 2, 6, 0, 0)]
#}
In turn, when calling the plotExpenseEvolution method
myBudget.plotExpenseEvolution()
plt.show()
you will get the following line plot based on the entered data
Here, note that we plot the evolution with respect to the days out of the recorded date from the budget history, as implemented in the first line of the method.
Finally, if you want to inspect the relative distribution of expenses with respect to the individual categories, you can do so by
myBudget.plotExpenses()
plt.show()
which results in the following pie chart
In summary, this article provided you with a comprehensive introduction on how to construct your personal budget tracker based on an object-oriented approach. Using the proposed Budget class syntax and the tracking functionalities in Python, you can define your budget and customize it according to your income and expenses. This not only allows you to take control of your own finances, but also to extend your programming skills using this versatile programming language.