-
Notifications
You must be signed in to change notification settings - Fork 0
/
budget.py
86 lines (65 loc) · 2.09 KB
/
budget.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class Category:
def __init__(self, label):
self.label = label
self.ledger = []
def get_balance(self):
c = 0
for item in self.ledger:
c += item['amount']
return c
def check_funds(self, amount):
return amount <= self.get_balance()
def deposit(self, amount, description=""):
self.ledger.append({"amount": amount, "description": description})
def withdraw(self, amount, description=""):
if self.check_funds(amount):
self.ledger.append({"amount": -amount, "description": description})
return True
return False
def transfer(self, amount, obj):
if self.withdraw(amount, "Transfer to " + obj.label):
obj.deposit(amount, "Transfer from " + self.label)
return True
return False
def __str__(self):
output = ""
output += self.label.center(30,"*") + "\n"
total = 0
for item in self.ledger:
total += item['amount']
output += item['description'].ljust(23, " ")[:23]
output += "{0:>7.2f}".format(item['amount'])
output += "\n"
output += "Total: " + "{0:.2f}".format(total)
return output
def create_spend_chart(categories):
output = "Percentage spent by category\n"
# Retrieve total expense of each category
total = 0
expenses = []
labels = []
len_labels = 0
for item in categories:
expense = sum([-x['amount'] for x in item.ledger if x['amount'] < 0])
total += expense
if len(item.label) > len_labels:
len_labels = len(item.label)
expenses.append(expense)
labels.append(item.label)
# Convert to percent + pad labels
expenses = [(x/total)*100 for x in expenses]
labels = [label.ljust(len_labels, " ") for label in labels]
# Format output
for c in range(100,-1,-10):
output += str(c).rjust(3, " ") + '|'
for x in expenses:
output += " o " if x >= c else " "
output += " \n"
# Add each category name
output += " " + "---"*len(labels) + "-\n"
for i in range(len_labels):
output += " "
for label in labels:
output += " " + label[i] + " "
output += " \n"
return output.strip("\n")