-
Notifications
You must be signed in to change notification settings - Fork 2
/
cfclassifier.py
844 lines (707 loc) · 27.8 KB
/
cfclassifier.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
##classifier stuff
'''
To add a new category, go to the transactionClasses class and add a new field
To add a new definition, go to the __init__ function in the Classifier() and
add a new definition based on previous definitions (exact or partial match)
'''
import datetime
from enum import Enum
import json
class category():
root = ''
isRoot = False
cat = ''
isIncome = False
isExpense = False
isNeutral = False
class RuleTypes(Enum):
Specific = 1
Exact = 2
Partial = 3
Default = 4
class RuleSet():
rules = list()
defaultRuleSet = False
def ensureOneDefault(self):
if self.defaultRuleSet == True:
return
newRules = list()
for rule in self.rules:
if rule.ruleType != RuleTypes.Default:
newRules.append(rule)
continue
#remove all other default rules
if self.defaultRuleSet == False:
self.defaultRuleSet = True
newRules.append(rule)
else:
print(f"[CoinFlow] Warning: Multiple default rules found. Only the first default rule will be used.")
def checkValidCategories(self, categories):
dictOfCategories = dict()
for category in categories:
if category.isRoot == True:
dictOfCategories[category.root] = list()
for category in categories:
if category.isRoot == False:
dictOfCategories[category.root].append(category.cat)
newRules = list()
for rule in self.rules:
ruleToCat = rule.ruleMatchValue.split('-')[1].strip()
ruleToRoot = rule.ruleMatchValue.split(' - ')[0].strip()
isInDict = False
if ruleToRoot in dictOfCategories:
ldict = dictOfCategories[ruleToRoot]
if ruleToCat in ldict:
isInDict = True
if isInDict:
newRules.append(rule)
else:
print(f"[CoinFlow] Warning: Rule {rule.rulestr} does not have a valid category. Rule will not be used.")
self.rules = newRules
#for length, use len(self.rules)
def __getitem__(self, index):
return self.rules[index]
def __len__(self):
return len(self.rules)
class Rule():
symbol = ''
incsymbol = ''
rulestr = ''
ruleType = ''
ruleMatchType = ''
ruleMatchValue = ''
rulematchwithtype = ''
def __init__(self, symbol, inc, rulestr, ruleMatchValue):
self.symbol = symbol
self.incsymbol = inc
self.rulestr = rulestr
self.ruleMatchValue = ruleMatchValue
self.parseRule()
def parseRule(self):
if self.symbol == 's':
self.ruleType = RuleTypes.Specific
self.ruleMatchType = 'ID'
elif self.symbol == 's':
self.ruleType = RuleTypes.Specific
self.ruleMatchType = 'Date'
self.rulestr = datetime.datetime.strptime(self.rulestr, '%m/%d/%Y')
elif self.symbol == 'e':
self.ruleType = RuleTypes.Exact
self.ruleMatchType = 'Description'
elif self.symbol == 'p':
self.ruleType = RuleTypes.Partial
self.ruleMatchType = 'Description'
elif self.symbol == 'd':
self.ruleType = RuleTypes.Default
self.ruleMatchType = 'Description'
if self.incsymbol == 'i':
self.rulematchwithtype = 'income'
elif self.incsymbol == 'e':
self.rulematchwithtype = 'expense'
elif self.incsymbol == 'n':
self.rulematchwithtype = 'neutral'
elif self.incsymbol == 'a':
self.rulematchwithtype = 'all'
class Classifier2():
ruleSet = RuleSet()
categories = list()
def __init__(self, categories, ruleSet):
print(type(ruleSet))
self.categories = categories
self.ruleSet = ruleSet
def classify(self, desc, amt):
category = ''
root = ''
#check for specifc rules
#not implemented
#check for exact rules
root, category = self.classifyByExact(desc, amt)
if root != '' and category != '':
return root, category, self.mapRootToIncome(root)
root, category = self.classifyByPartial(desc, amt)
if root != '' and category != '':
return root, category, self.mapRootToIncome(root)
root, category = self.classifyByDefault(desc)
#check for partial rules
#check for default rules
return root, category, self.mapRootToIncome(root)
def classifyByExact(self, desc, amt):
exactRules = list()
for rule in self.ruleSet.rules:
if rule.ruleType == RuleTypes.Exact:
exactRules.append(rule)
for rule in exactRules:
if amt > 0 and (rule.rulematchwithtype != 'income' and rule.rulematchwithtype != 'all'):
continue
if amt < 0 and (rule.rulematchwithtype != 'expense' and rule.rulematchwithtype != 'all'):
continue
if amt == 0 and (rule.rulematchwithtype != 'neutral' and rule.rulematchwithtype != 'all'):
continue
ruleRoot = rule.ruleMatchValue.split(' - ')[0].strip()
ruleCat = rule.ruleMatchValue.split(' - ')[1].strip()
ruleMatch = rule.rulestr.lower().strip()
#print(f"Attempting match for {ruleMatch} to {desc.lower().strip()}")
isMatch = False
if rule.ruleMatchType == 'Description':
if rule.rulestr == desc.lower().strip():
isMatch = True
if isMatch:
#print(f"Exact Matched {rule.rulestr} to {desc}")
return ruleRoot, ruleCat
#print(f"[CoinFlow] Exact Rule: {rule.rulestr}, {rule.ruleMatchValue}")
return '', ''
def classifyByPartial(self, desc, amt):
partialRules = list()
for rule in self.ruleSet.rules:
if rule.ruleType == RuleTypes.Partial:
partialRules.append(rule)
for rule in partialRules:
if amt > 0 and (rule.rulematchwithtype != 'income' and rule.rulematchwithtype != 'all'):
continue
if amt < 0 and (rule.rulematchwithtype != 'expense' and rule.rulematchwithtype != 'all'):
continue
if amt == 0 and (rule.rulematchwithtype != 'neutral' and rule.rulematchwithtype != 'all'):
continue
ruleRoot = rule.ruleMatchValue.split(' - ')[0].strip()
ruleCat = rule.ruleMatchValue.split(' - ')[1].strip()
ruleMatch = rule.rulestr.lower().strip()
ruleDesc = desc.lower().strip()
isMatch = False
if rule.ruleMatchType == 'Description':
if ruleMatch in ruleDesc:
isMatch = True
if isMatch:
#print(f"Partial Matched {rule.rulestr} to {desc}")
return ruleRoot, ruleCat
return '', ''
def classifyByDefault(self, desc):
for rule in self.ruleSet.rules:
if rule.ruleType == RuleTypes.Default:
defaultRule = rule
ruleRoot = defaultRule.ruleMatchValue.split(' - ')[0].strip()
ruleCat = defaultRule.ruleMatchValue.split(' - ')[1].strip()
print(f"Default Matched: {ruleRoot} - {ruleCat} to {desc}")
return ruleRoot, ruleCat
return 'Misc', 'Error'
def mapRootToIncome(self, root):
#maps root to 'income', 'expense' or 'neutral'
isIncome = False
isExpense = False
isNeutral = False
for cat in self.categories:
#print(cat.cat)
if root in cat.cat:
if cat.isIncome:
return 'income'
elif cat.isExpense:
return 'expense'
elif cat.isNeutral:
return 'neutral'
else:
return 'unknown'
class tranactionClasses():
#costs money
#shopping - offline
Shopping = ("Shopping")
ShoppingTools = ("Shopping - Tools")
ShoppingGarden = ("Shopping - Garden")
ShoppingFurniture = ("Shopping - Furniture")
ShoppingHome = ("Shopping - Home")
ShoppingElectronics = ("Shopping - Electronics")
ShoppingOffice = ("Shopping - Office Supplies")
ShoppingBooks = ("Shopping - Books")
ShoppingMovies = ("Shopping - Movies")
ShoppingMusic = ("Shopping - Music")
ShoppingGames = ("Shopping - Games")
ShoppingToys = ("Shopping - Toys")
ShoppingBaby = ("Shopping - Baby")
#personal - self improvement, entertainment, etc
Personal = ("Personal")
PersonalGeneral = ("Personal - General")
PersonalGym = ("Personal - Gym")
PersonalHair = ("Personal - Hair")
PersonalCosmetics = ("Personal - Cosmetics")
PersonalBaby = ("Personal - Baby")
PersonalEntertainment = ("Personal - Entertainment")
#Food
Food = ("Food")
FoodFast = ("Food - Fast Food")
FoodDining = ("Food - Dining")
FoodDelivery = ("Food - Delivery")
FoodPet = ("Food - Pet")
ShoppingGrocery = ("Shopping - Grocery")
#Online - Subscriptions, Services, Shopping
Online = ("Online")
OnlineSubscriptions = ("Online - Subscriptions")
OnlineServices = ("Online - Services")
OnlineShopping = ("Online - Shopping")
#bills
BillsAndUtilities = ("Bills and Utilities")
BillsAndUtilitiesElectric = ("Bills and Utilities - Electric")
BillsAndUtilitiesWater = ("Bills and Utilities - Water")
BillsAndUtilitiesInternet = ("Bills and Utilities - Internet")
BillsAndUtilitiesPhone = ("Bills and Utilities - Phone")
BillsAndUtilitiesCable = ("Bills and Utilities - Cable")
BillsAndUtilitiesOther = ("Bills and Utilities - Other")
#clothes sub categories
Clothing = ("Clothing")
ClothingShoes = ("Clothing - Shoes")
ClothingAccessories = ("Clothing - Accessories")
#Medical
Medical = ("Medical")
MedicalPrimary = ("Medical - Primary Care")
MedicalDental = ("Medical - Dental")
MedicalSpecialty = ("Medical - Specialty Care")
MedicalUrgentCare = ("Medical - Urgent Care")
MedicalMedications = ("Medical - Medications")
MedicalMedicalDevices = ("Medical - Medical Devices")
#Insurance
Insurance = ("Insurance")
InsuranceHome = ("Insurance - Home")
InsuranceAuto = ("Insurance - Auto")
InsuranceLife = ("Insurance - Life")
InsuranceRenter = ("Insurance - Renter")
InsuranceDisability = ("Insurance - Disability")
InsuranceOther = ("Insurance - Other")
#Home
Home = ("Home")
HomeRent = ("Home - Rent")
HomeRepairs = ("Home - Repairs")
HomeHOAFees = ("Home - HOA Fees")
OtherTaxes = ("Other - Taxes")
#Savings
SavingsGeneral = ("Savings - General")
SavingsEmergency = ("Savings - Emergency")
SavingsRetirement = ("Savings - Retirement")
SavingsInvestments = ("Savings - Investments")
#Transportation
Transportation = ("Transportation")
TransportationCar = ("Transportation - Car")
TransportationGas = ("Transportation - Gas")
TransportationRepairs = ("Transportation - Repairs")
TransportationParking = ("Transportation - Parking")
#Debt
DebtGeneral = ("Debt - General")
DebtPersonal = ("Debt - Personal Loan")
DebtStudent = ("Debt - Student Loan")
DebtCreditCard = ("Debt - Credit Card")
DebtAuto = ("Debt - Auto")
DebtMortgage = ("Debt - Mortgage")
OneTime = ("One Time")
OtherExpenses = ("Expenses - Other")
Gifts = ("Gifts")
Donations = ("Donations")
Entertainment = ("Entertainment")
EntertainmentAlcohol = ("Entertainment - Alcohol")
EntertainmentDrugs = ("Entertainment - Drugs")
EntertainmentDating = ("Entertainment - Dating")
EntertainmentGambling = ("Entertainment - Gambling")
TravelConcerts = ("Travel - Concerts")
TravelGeneral = ("Travel - General")
TravelVacation = ("Travel - Vacation")
TravelBusiness = ("Travel - Business")
BankVerification = ("Other - Bank Verification")
ExpenseTransfer = ("Expense - Transfer")
Expense = ("Expense")
Cash = ("Cash")
Other = ("Other")
OtherFees = ("Other - Fees")
#gives money
IncomeGifts = ("Income - Gifts")
IncomeDividends = ("Income - Dividends")
IncomePaycheck = ("Income - Paycheck")
IncomeBonus = ("Income - Bonus")
IncomeInterest = ("Income - Interest")
IncomeRefunds = ("Income - Refunds")
IncomeReimbursements = ("Income - Reimbursements")
IncomeRental = ("Income - Rental")
IncomeTransfer = ("Income - Transfer")
IncomeOther = ("Income - Other")
Income = ("Income")
def returnListOfClasses(self):
classes = list()
for field in dir(tranactionClasses):
if not field.startswith("__") and not field.startswith("returnListOfClasses"):
#get the value of the string
vstr = getattr(tranactionClasses, field)
#classes.append(getattr(tranactionClasses, field))
#create tuple of root class and category, root class has no dash
if '-' in vstr:
root = vstr.split('-')[0].strip()
cat = vstr.split('-')[1].strip()
classes.append((root, cat))
else:
classes.append((vstr, vstr))
return classes
class baseDefinitions():
RootClass = tranactionClasses.Other
Category = tranactionClasses.Other
exactMatch = dict()
partialMatch = dict()
def addExactMatch(self, key, value):
self.exactMatch[key] = value
def addPartialMatch(self, key, value):
self.partialMatch[key] = value
def attemptExactMatch(self, matchString):
for key in self.exactMatch:
if key == matchString:
return self.Category, self.RootClass
return None, None
def attemptPartialMatch(self, matchString):
for key in self.partialMatch:
if key in matchString:
return self.Category, self.RootClass
return None, None
def getRootClass(self):
return self.RootClass
def attemptMatch(self, matchString):
matchString = matchString.lower().strip()
match, root = self.attemptExactMatch(matchString)
if match is not None and root is not None:
return str(match), root
match, root = self.attemptPartialMatch(matchString)
if match is not None and root is not None:
return str(match), root
return '', ''
def __init__(self, rootClass = tranactionClasses.Other, category = tranactionClasses.Other):
self.RootClass = rootClass.strip()
self.Category = category.split('-')[1].strip()
self.partialMatch = dict()
self.exactMatch = dict()
class Classifier():
AllCategories = list()
def ClassifyDescription(self, description):
assumed = ''
for category in self.AllCategories:
assumed = category.attemptMatch(description)
if assumed != ('', ''):
return assumed
return assumed
def __init__(self):
cat_IncomePayroll = baseDefinitions(tranactionClasses.Income, tranactionClasses.IncomePaycheck)
cat_IncomePayroll.addPartialMatch("coreweave", tranactionClasses.IncomePaycheck)
cat_IncomePayroll.addPartialMatch("remote online deposit", tranactionClasses.IncomePaycheck)
self.AllCategories.append(cat_IncomePayroll)
cat_IncomeTransfer = baseDefinitions(tranactionClasses.Income, tranactionClasses.IncomeTransfer)
cat_IncomeTransfer.addPartialMatch("transfer from", tranactionClasses.IncomeTransfer)
cat_IncomeTransfer.addPartialMatch("payment from", tranactionClasses.IncomeTransfer)
self.AllCategories.append(cat_IncomeTransfer)
cat_BankVerification = baseDefinitions(tranactionClasses.Other, tranactionClasses.BankVerification)
cat_BankVerification.addPartialMatch("acctverify", tranactionClasses.BankVerification)
self.AllCategories.append(cat_BankVerification)
cat_ExpenseTransfer = baseDefinitions(tranactionClasses.Expense, tranactionClasses.ExpenseTransfer)
cat_ExpenseTransfer.addPartialMatch("transfer to", tranactionClasses.ExpenseTransfer)
cat_ExpenseTransfer.addPartialMatch("payment to", tranactionClasses.ExpenseTransfer)
self.AllCategories.append(cat_ExpenseTransfer)
print("Classifier initialized")
#class Budget():
# values = dict()
#
# def __init__(self):
# tclasses = tranactionClasses()
# tlist = tclasses.returnListOfClasses()
#
#
# ##initialize all values to 0
# for tclass in tlist:
# cat = tclass[1]
# root = tclass[0]
# self.values[f"{root}-{cat}"] = 0
#
# def getBudgetForCategory(self, cat, root):
# return self.values[f"{root}-{cat}"]
#
# def setBudgetForCategory(self, cat, root, value):
# self.values[f"{root}-{cat}"] = value
# return
#
# def getAllOfKey(self, keyInput="Income"):
# if self.values is None:
# return None
# total = 0
# for key in self.values:
# if keyInput in key:
# total += self.values[key]
# return total
#
# def getAllSummedNonIncome(self):
# if self.values is None:
# return None
#
# total = 0
# for key in self.values:
# if "Income" not in key:
# total += self.values[key]
# return total
#
# def getAllSummed(self):
# if self.values is None:
# return None
#
# total = 0
# for key in self.values:
# total += self.values[key]
# return total
#
# def getTableData(self):
# dataplot1x = []
# dataplot1y = [] #expense root pie
# data1 = dict()
# dataplot2x = []
# dataplot2y = [] #expense category pie
# data2 = dict()
# dataplot3x = []
# dataplot3y = [] #income category pie
# #dataplot4x = []
# #dataplot4y = [] #actual ex
# data3 = dict()
# #data4 = dict()
# #x is root category, y is value of root category
# for i in self.values:
# root = i.split("-")[0].strip()
# cat = root
# if len(i.split("-")) > 1:
# cat = i.split("-")[1].strip()
# val = float(self.values[i])
# if val == 0:
# continue
# if root not in data1 and i.isExpense == True:
# data1[root] = val
# elif i.isIncome == True:
# data1[root] += val
# #convert data1 to list
# data1 = list(data1.items())
#
# #remove all but top 10
# data1.sort(key=lambda x: x[1], reverse=True)
# for i in range(0, 9):
# if i >= len(data1):
# break
# dataplot1x.append(data1[i][0])
# dataplot1y.append(data1[i][1])
#
# #category plot
# for i in self.values:
# root = i.split("-")[0].strip()
# cat = root
# if len(i.split("-")) > 1:
# cat = i.split("-")[1].strip()
# val = float(self.values[i])
# if val == 0:
# continue
# if cat not in data2 and i.isExpense == True:
# data2[cat] = val
# elif cat in data2 and i.isExpense == True:
# data2[cat] += val
# elif cat not in data3 and i.isIncome == True:
# data3[cat] = val
# elif cat in data3 and i.isIncome == True:
# data3[cat] += val
#
#
#
# #convert data2 to list
# data2 = list(data2.items())
#
# #remove all but top 10
# data2.sort(key=lambda x: x[1], reverse=True)
# for i in range(0, 9):
# if i >= len(data2):
# break
# dataplot2x.append(data2[i][0])
# dataplot2y.append(data2[i][1])
# print(data3)
# #convert data3 to list
# data3 = list(data3.items())
# data3.sort(key=lambda x: x[1], reverse=True)
# for i in range(0, 9):
# if i >= len(data3):
# break
# dataplot3x.append(data3[i][0])
# dataplot3y.append(data3[i][1])
#
#
# return dataplot1x, dataplot1y, dataplot2x, dataplot2y, dataplot3x, dataplot3y
class BudgetSet():
values = dict()
categories = dict()
def __init__(self, categories=list()):
self.categories = categories
self.createEmptyBudget()
def createEmptyBudget(self):
for cat in self.categories:
catstr = cat.cat
rootstr = cat.root
#print(f"Enter budget for {catstr} in {rootstr}: ")
key = f"{rootstr}-{catstr}"
self.values[key] = 0
def getBudgetForCategory(self, cat, root):
return self.values[f"{root}-{cat}"]
def setBudgetForCategory(self, cat, root, value):
self.values[f"{root}-{cat}"] = value
return
def getAllOfKey(self, keyInput="Income"):
if self.values is None:
return None
total = 0
for key in self.values:
if keyInput in key:
total += self.values[key]
return total
def getAllSummedNonIncome(self):
if self.values is None:
return None
#get (root=cat) pairs for all expenses
rcp = dict()
for key in self.categories:
if key.isExpense == True:
rcp[key.root] = key.cat
print(rcp)
#sum all expenses
total = 0
for key in self.values:
cat = key.split("-")[1].strip()
root = key.split("-")[0].strip()
amt = self.values[key]
if root in rcp and amt != 0:
print(f"adding {key} to total for expense (+{self.values[key]})")
total += self.values[key]
print(f"total: {total}")
return round(total, 2)
def getAllSummedIncome(self):
if self.values is None:
return None
#get (root=cat) pairs for all expenses
rcp = dict()
for key in self.categories:
if key.isIncome == True:
rcp[key.root] = key.cat
#print(rcp)
#sum all income
total = 0
for key in self.values:
cat = key.split("-")[1].strip()
root = key.split("-")[0].strip()
if root in rcp:
#print(f"adding {key} to total for income (+{self.values[key]})")
total += self.values[key]
return round(total, 2)
def getAllSummed(self):
if self.values is None:
return None
total = 0
for key in self.values:
total += self.values[key]
return total
def getTableData(self):
dataplot1x = []
dataplot1y = [] #expense root pie
data1 = dict()
dataplot2x = []
dataplot2y = [] #expense category pie
data2 = dict()
dataplot3x = []
dataplot3y = [] #income category pie
#dataplot4x = []
#dataplot4y = [] #actual ex
data3 = dict()
#data4 = dict()
#x is root category, y is value of root category
for i in self.values:
root = i.split("-")[0].strip()
cat = root
if len(i.split("-")) > 1:
cat = i.split("-")[1].strip()
val = float(self.values[i])
if val == 0:
continue
if root not in data1 and root != "Income":
data1[root] = val
elif root != "Income":
data1[root] += val
#convert data1 to list
data1 = list(data1.items())
#remove all but top 10
data1.sort(key=lambda x: x[1], reverse=True)
for i in range(0, 9):
if i >= len(data1):
break
dataplot1x.append(data1[i][0])
dataplot1y.append(data1[i][1])
#category plot
for i in self.values:
root = i.split("-")[0].strip()
cat = root
if len(i.split("-")) > 1:
cat = i.split("-")[1].strip()
val = float(self.values[i])
if val == 0:
continue
if cat not in data2 and root != "Income":
data2[cat] = val
elif cat in data2 and root != "Income":
data2[cat] += val
elif cat not in data3 and root == "Income":
data3[cat] = val
elif cat in data3 and root == "Income":
data3[cat] += val
#convert data2 to list
data2 = list(data2.items())
#remove all but top 10
data2.sort(key=lambda x: x[1], reverse=True)
for i in range(0, 9):
if i >= len(data2):
break
dataplot2x.append(data2[i][0])
dataplot2y.append(data2[i][1])
print(data3)
#convert data3 to list
data3 = list(data3.items())
data3.sort(key=lambda x: x[1], reverse=True)
for i in range(0, 9):
if i >= len(data3):
break
dataplot3x.append(data3[i][0])
dataplot3y.append(data3[i][1])
return dataplot1x, dataplot1y, dataplot2x, dataplot2y, dataplot3x, dataplot3y
def getListOfCategoriesKeys(self):
cats = list()
for cat in self.categories:
catstr = cat.cat
rootstr = cat.root
if cat.isRoot == False:
cats.append(f"{rootstr}-{catstr}")
return cats
def getListOfCategoriesKeysWithType(self):
cats = list()
for cat in self.categories:
catstr = cat.cat
rootstr = cat.root
typeofcat = ""
if cat.isRoot == False:
if cat.isExpense == True:
typeofcat = "expense"
elif cat.isIncome == True:
typeofcat = "income"
else:
typeofcat = "neutral"
cats.append((typeofcat,f"{rootstr}-{catstr}"))
continue
return cats
def reconcileChangedBudgetFile(self, budgetPath):
#get all categories, removing categories that are in the budget file but not in the categories file
#and adding categories that are in the categories file but not in the budget file
allcatkeys = self.getListOfCategoriesKeys()
allbudgetkeys = list(self.values.keys())
#if in categories but not in budget, add to budget
for cat in allcatkeys:
if cat not in allbudgetkeys:
self.values[cat] = 0
#write updated budget file
with open(budgetPath, 'w') as json_file:
json.dump(self.values, json_file)
json_file.close()
if __name__ == "__main__":
matchstring = "transfer from"
classifier = Classifier()
print(classifier.ClassifyDescription(matchstring))