-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidebar.py
More file actions
2317 lines (1911 loc) · 87.1 KB
/
sidebar.py
File metadata and controls
2317 lines (1911 loc) · 87.1 KB
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import sys
from pathlib import Path
import threading
import asyncio
from collections import Counter
from datetime import timedelta
from decimal import Decimal
from itertools import combinations
from typing import Iterable, Literal
import pickle
# Import with error handling for potentially missing dependencies
try:
import pandas as pd
# Try to set copy_on_write, but don't fail if not supported
try:
pd.options.mode.copy_on_write = True
except (AttributeError, TypeError):
pass # Older pandas versions don't have this option
except Exception:
pd = None
try:
import numpy as np
except Exception:
np = None
try:
from dotmap import DotMap
except Exception:
DotMap = None
try:
from matplotlib import pyplot as plt
except Exception:
plt = None
try:
from pydantic import BaseModel
except Exception:
BaseModel = None
try:
import tqdm.asyncio as _tqdm_asyncio
from tqdm import tqdm
except Exception:
_tqdm_asyncio = None
tqdm = None
# OpenAI imports
try:
from openai import AsyncOpenAI, OpenAI
ACLIENT = AsyncOpenAI()
CLIENT = OpenAI()
except Exception:
ACLIENT = None
CLIENT = None
from pyxll import xl_macro, create_ctp, xl_app
from PySide6 import QtWidgets, QtCore, QtGui
# ============================================================================
# CONFIGURATION
# ============================================================================
# Absolute paths - root directory where data dir resides
PROJECT_ROOT = Path(r"C:\Users\usa\Documents\steward-view-main")
INPUT_DATA_DIR = PROJECT_ROOT / 'data' / 'input'
OUTPUT_DATA_DIR = PROJECT_ROOT / 'data' / 'output'
# Chart configuration
CATEGORY_MIN = 500
VENDOR_MIN = 500
# Column name mappings
COLUMNS = {
'Date': 'date',
'Transaction Date': 'date',
'Order Date': 'date',
0: 'date',
'Description': 'description',
'Product Name': 'description',
3: 'description',
'Amount': 'amount',
'Total Owed': 'amount',
1: 'amount'
}
# Row exclusion indicators
ROW_EXCLUSION_INDICATORS = 'Mobile Payment|Beginning balance|EPAY ID'
# Vendor dictionary for known vendors
VENDOR_DICT = {
'ALLY AUTO': {'vendor': 'Ally Auto', 'category': 'Automotive'},
'CITY OF DALLAS UTILITIES': {'vendor': 'City of Dallas', 'category': 'Utilities'},
'GOOGLE STORAGE': {'vendor': 'Google', 'category': 'Subscriptions'},
'GREYSTAR': {'vendor': 'Greystar', 'category': 'Rent'},
'NETFLIX': {'vendor': 'Netflix', 'category': 'Subscriptions'},
'PLANET FITNESS': {'vendor': 'Planet Fitness', 'category': 'Gym & Fitness'},
'PLNT FITNESS': {'vendor': 'Planet Fitness', 'category': 'Gym & Fitness'},
'SPOTIFY': {'vendor': 'Spotify', 'category': 'Subscriptions'},
'TXU ENERGY': {'vendor': 'TXU Energy', 'category': 'Utilities'},
'WSJ DIGITAL': {'vendor': 'Wall Street Journal', 'category': 'Subscriptions'}
}
# Expense categories
ExpenseCategory = Literal[
'Automotive',
'Baby & Child',
'Books',
'Clothing & Accessories',
'Electronics & Accessories',
'General',
'Groceries',
'Gym & Fitness',
'Health & Personal Care',
'Home',
'Office Supplies',
'Other Food & Beverage',
'Pet Supplies',
'Sports & Recreation',
'Other'
]
# OpenAI configuration
MODEL = 'gpt-5-mini'
SERVICE_TIER = 'priority'
PRODUCT_LABELING_INSTRUCTIONS = '''The user will provide an Amazon
product name. Return the most fitting category from the supplied
JSON schema.'''
PAYMENT_LABELING_INSTRUCTIONS = '''The user will provide a transaction
description from a bank statement. Return the common short brand
name of the counterparty and the most fitting category from the
supplied JSON schema.'''
CHAT_INSTRUCTIONS = '''Provide a direct, terse answer to the user's
questions about the expense data in the supplied file using the
Python tool (a.k.a. the Code Interpreter tool) as necessary. Do not
offer to share created files. Do not mention the supplied file or
its structure (e.g. its columns); from the user's perspective,
these are implementation details.'''
# ============================================================================
# UTILITY CLASSES AND HELPERS
# ============================================================================
# Utility classes - only define if dependencies are available
if _tqdm_asyncio is not None:
class ProgressBar:
"""A minimal ProgressBar wrapper for asynchronous operations."""
@staticmethod
async def gather(*args, **kwargs):
return await _tqdm_asyncio.tqdm_asyncio.gather(*args, **kwargs)
@staticmethod
def as_completed(*args, **kwargs):
return _tqdm_asyncio.tqdm_asyncio.as_completed(*args, **kwargs)
else:
class ProgressBar:
@staticmethod
async def gather(*args, **kwargs):
import asyncio
return await asyncio.gather(*args, **kwargs)
@staticmethod
def as_completed(*args, **kwargs):
import asyncio
return asyncio.as_completed(*args, **kwargs)
if BaseModel is not None:
class CategoryResponse(BaseModel):
category: ExpenseCategory
class DualResponse(BaseModel):
vendor: str
category: ExpenseCategory
else:
# Fallback classes if pydantic is not available
class CategoryResponse:
def __init__(self, category):
self.category = category
class DualResponse:
def __init__(self, vendor, category):
self.vendor = vendor
self.category = category
def convert_to_decimal(value):
"""Convert value to Decimal with 2 decimal places."""
cent = Decimal('0.01')
return Decimal(value).quantize(cent)
# ============================================================================
# DATA LOADING
# ============================================================================
def load_data():
"""
Load Jack and Jill's checking, credit card, and Amazon data from Excel
sheets in the active workbook and return a dictionary of DataFrames.
Uses PyXLL's COM access to read data directly from Excel without requiring openpyxl.
Expected sheet names in the active workbook:
- 'amazon' (header row 0)
- 'jack_checking' (no header)
- 'jack_credit_card' (header row 0)
- 'jill_checking' (header row 0)
- 'jill_credit_card' (header row 4)
"""
if pd is None:
raise ImportError("pandas is required for load_data()")
# Get the active workbook
app = xl_app()
wb = app.ActiveWorkbook
if wb is None:
raise RuntimeError("No active workbook found. Please open the Excel file first.")
print("\n=== LOADING DATA FROM EXCEL ===")
# Helper function to read Excel range into DataFrame using COM
def read_sheet_to_dataframe(sheet_name, header_row=None):
"""Read an Excel sheet into a pandas DataFrame using PyXLL COM access."""
try:
ws = wb.Worksheets(sheet_name)
except Exception:
raise RuntimeError(f"Sheet '{sheet_name}' not found in the active workbook.")
# Get the used range to find the extent of data
used_range = ws.UsedRange
if used_range is None:
return pd.DataFrame()
# Find the last row and column with data
last_row = used_range.Row + used_range.Rows.Count - 1
last_col = used_range.Column + used_range.Columns.Count - 1
# Debug: print range being read
print(f" Reading {sheet_name}: Excel rows {used_range.Row} to {last_row}, columns {used_range.Column} to {last_col}")
# Always read from row 1 to ensure we capture header rows correctly
# This matches CSV behavior where we read from the beginning
# Read from row 1, column 1 to last_row, last_col
data_range = ws.Range(ws.Cells(1, 1), ws.Cells(last_row, last_col))
values = data_range.Value
# Convert COM return value to list of lists
if values is None:
return pd.DataFrame()
# Normalize COM return value to list of lists
# COM can return: scalar, 1D list (row/column), or 2D list
if not isinstance(values, (list, tuple)):
# Single cell - wrap in list
data = [[values]]
elif len(values) == 0:
# Empty range
return pd.DataFrame()
else:
# Check if first element is a list/tuple (indicating 2D structure)
first_elem = values[0] if len(values) > 0 else None
if isinstance(first_elem, (list, tuple)):
# 2D array - convert tuples to lists if needed
data = [list(row) if isinstance(row, tuple) else row for row in values]
else:
# Single row - wrap in list
# Convert tuple to list if needed
data = [list(values) if isinstance(values, tuple) else values]
# Convert to DataFrame
if header_row is None:
# No header - use default column names
df = pd.DataFrame(data)
else:
# Has header - use specified row as column names
# header_row is 0-indexed, so row 0 = Excel row 1, row 4 = Excel row 5
if len(data) <= header_row:
raise RuntimeError(f"Sheet '{sheet_name}' has fewer rows than header row {header_row}.")
# Convert header row to list if it's a tuple
header = list(data[header_row]) if isinstance(data[header_row], tuple) else data[header_row]
# Start data from row after header (header_row + 1)
df = pd.DataFrame(data[header_row + 1:], columns=header)
return df
# Read data from Excel sheets (sheet names match CSV file names without .csv extension)
# Map: sheet_name -> (data_key, header_row)
sheet_configs = {
'amazon': ('amzn', 0),
'jack_checking': ('jack_ch', None),
'jack_credit_card': ('jack_cc', 0),
'jill_checking': ('jill_ch', 0),
'jill_credit_card': ('jill_cc', 4)
}
data = {}
for sheet_name, (data_key, header_row) in sheet_configs.items():
try:
df = read_sheet_to_dataframe(sheet_name, header_row)
data[data_key] = df
print(f" Loaded {sheet_name} ({data_key}): {len(df)} rows, {len(df.columns)} columns")
except Exception as e:
raise RuntimeError(f"Error reading sheet '{sheet_name}': {str(e)}")
print("=" * 50)
return data
# ============================================================================
# DATA TAGGING
# ============================================================================
def tag(data):
"""
Add 'account' and 'spender' columns with the appropriate values.
"""
for account in data:
data[account]['account'] = account
data[account]['spender'] = 'Jack' if 'jack' in account else 'Jill'
return data
# ============================================================================
# DATA CLEANING
# ============================================================================
def rename_columns(data):
"""Rename the necessary columns in each data table."""
for account in data:
data[account] = data[account].rename(columns=COLUMNS)
return data
def filter_amazon(table):
"""
Isolate Amazon products purchased exclusively with Jill's Visa
credit card ending in 1234.
"""
filter = table['Payment Instrument Type'] == 'Visa - 1234'
table = table[filter]
return table
def filter_cc(table):
"""Remove unnecessary rows from both credit card accounts."""
filter = ~table['description'].str.contains(ROW_EXCLUSION_INDICATORS)
table = table[filter]
return table
def filter_rows(data):
"""
Remove unnecessary rows from both credit card accounts and isolate
Amazon products purchased exclusively with Jill's Visa credit card
ending in 1234.
"""
for account, table in data.items():
if account == 'amzn':
data[account] = filter_amazon(table)
elif 'cc' in account:
data[account] = filter_cc(table)
return data
def drop_columns(data):
"""
Drop all columns except date, amount, description, account, and spender.
"""
for account, table in data.items():
data[account] = table[['date', 'amount', 'description', 'account', 'spender']]
return data
def cast_date_dtype(data, account):
"""
Cast the dtype of the 'amzn' date column to datetime and all other
date columns to date.
Handles timezone-aware datetimes from Excel COM by normalizing to UTC
then removing timezone info to match CSV behavior.
"""
if account == 'amzn':
# For Amazon, convert to datetime (timezone-naive)
# Handle timezone-aware datetimes from Excel COM
data[account]['date'] = pd.to_datetime(data[account]['date'], utc=True).dt.tz_localize(None)
else:
# For other accounts, convert to date (timezone-naive)
# Handle timezone-aware datetimes from Excel COM
data[account]['date'] = pd.to_datetime(data[account]['date'], utc=True).dt.tz_localize(None).dt.date
return data
def cast_amount_dtype(data, account):
"""Cast the amount column of data[account] to Decimal."""
data[account]['amount'] = data[account]['amount'].apply(convert_to_decimal)
return data
def cast_dtypes(data):
"""
Cast the dtype of the 'amzn' date column to datetime, all other
date columns to date, and all amount columns to Decimal.
"""
for account in data:
data = cast_date_dtype(data, account)
data = cast_amount_dtype(data, account)
return data
def clean(data):
"""
Remove unnecessary rows and columns and set the names and dtypes
of the remaining columns.
"""
# Debug: print row counts before cleaning
print("\n=== CLEANING DATA ===")
for account in data:
print(f" {account}: {len(data[account])} rows before clean")
data = rename_columns(data)
data = filter_rows(data)
# Debug: print row counts after filtering
print("\nAfter filtering:")
for account in data:
print(f" {account}: {len(data[account])} rows")
data = drop_columns(data)
data = cast_dtypes(data)
# Debug: print row counts after cleaning
print("\nAfter cleaning:")
for account in data:
print(f" {account}: {len(data[account])} rows")
print("=" * 50)
return data
# ============================================================================
# DATA COMBINING - MATCHER CLASS
# ============================================================================
class Order:
"""
Create a new Order instance for matching Amazon products to payments.
"""
def __init__(self, matcher, order_id):
self.date = order_id.date()
self.pmts = DotMap({
'candidates': self.identify_candidates(matcher),
'matched': pd.Index([], dtype='int64')
})
self.prods = DotMap({
'unmatched': Order.extract_products(matcher, order_id),
'matched': pd.Index([], dtype='int64')
})
self.counter = Counter({
'match_all_products': 0,
'match_single_products': 0,
'match_product_combos': 0
})
def match(self):
"""
Identify the matching payments and products associated with a
single Amazon order.
"""
# Step 1
if len(self.pmts.candidates) == 0:
return None
else:
self.match_all_products()
# Step 2
if len(self.prods.unmatched) < 2:
return None
else:
self.match_single_products()
# Step 3
if len(self.prods.unmatched) < 4:
return None
else:
self.match_product_combos()
def match_all_products(self):
prods_amt = self.prods.unmatched['amount'].sum()
for pmt_idx, pmt_amt in self.pmts.candidates['amount'].items():
if pmt_amt == prods_amt:
self.record_match(
pd.Index([pmt_idx]),
self.prods.unmatched.index,
'match_all_products'
)
break
def match_single_products(self):
for pmt_idx, pmt_amt in self.pmts.candidates['amount'].items():
for prod_idx, prod_amt in self.prods.unmatched['amount'].items():
if prod_amt == pmt_amt:
self.record_match(
pd.Index([pmt_idx]),
pd.Index([prod_idx]),
'match_single_products'
)
if len(self.prods.unmatched) > 1:
self.match_all_products()
break
if len(self.prods.unmatched) == 0:
break
def match_product_combos(self):
initial_prod_count = len(self.prods.unmatched)
for combo_length in self.generate_combo_lengths(initial_prod_count):
self.match_combos_of_length(combo_length)
if len(self.prods.unmatched) <= combo_length:
break
@staticmethod
def generate_combo_lengths(initial_prod_count):
return range(2, initial_prod_count // 2 + 1)
def match_combos_of_length(self, combo_length):
for pmt_idx, pmt_amt in self.pmts.candidates['amount'].items():
for combo in self.generate_combinations(combo_length):
combo_amt = self.calculate_combo_amount(combo)
if combo_amt == pmt_amt:
self.record_match(
pd.Index([pmt_idx]),
pd.Index(combo),
'match_product_combos'
)
if len(self.prods.unmatched) >= combo_length:
self.match_all_products()
break
if len(self.prods.unmatched) <= combo_length:
break
def generate_combinations(self, combo_length) -> Iterable[tuple[int]]:
return combinations(self.prods.unmatched.index, combo_length)
def calculate_combo_amount(self, combo):
return self.prods.unmatched.loc[list(combo), 'amount'].sum()
def record_match(self, payment_index: pd.Index, product_index: pd.Index, function):
self.pmts.matched = self.pmts.matched.append(payment_index)
self.pmts.candidates = self.pmts.candidates.drop(index=payment_index)
self.prods.matched = self.prods.matched.append(product_index)
self.prods.unmatched = self.prods.unmatched.drop(index=product_index)
self.counter[function] += 1
def identify_candidates(self, matcher, max_delay=3) -> pd.DataFrame:
payments = matcher.pmts.filtered
filter = payments['date'].between(self.date, self.date + timedelta(days=max_delay))
return payments[filter]
@staticmethod
def extract_products(matcher, order_id) -> pd.DataFrame:
products = matcher.prods.original
products = products[products['date'] == order_id]
return products
class Matcher:
"""
Create a new Matcher instance for matching Amazon payments with products.
"""
def __init__(self, payments, products, path):
self.pmts = DotMap({
'original': payments,
'filtered': payments[payments['description'].str.contains('AMAZON')],
'matched': pd.Index([], dtype='int64'),
'unmatched': pd.Index([], dtype='int64')
})
self.prods = DotMap({
'original': products,
'order_ids': products['date'].unique(),
'matched': pd.Index([], dtype='int64'),
'unmatched': pd.Index([], dtype='int64')
})
self.counter = Counter({
'match_all_products': 0,
'match_single_products': 0,
'match_product_combos': 0
})
self.integrated_data = pd.DataFrame({})
self.path = path / 'matcher.pkl'
def match(self):
"""
Replace bank records of Amazon payments with the more detailed
product data to enable more meaningful expense classification.
"""
self.process_orders()
self.compile_results()
self.save()
def process_orders(self):
if tqdm is None:
# Fallback if tqdm is not available
for id in self.prods.order_ids:
order = Order(self, id)
order.match()
self.update(order)
else:
for id in tqdm(self.prods.order_ids, desc='Matching Amazon Orders', unit='order', bar_format='{l_bar}{bar} {n_fmt}/{total_fmt} [{elapsed}]'):
order = Order(self, id)
order.match()
self.update(order)
def update(self, order):
self.pmts.matched = self.pmts.matched.append(order.pmts.matched)
self.prods.matched = self.prods.matched.append(order.prods.matched)
self.prods.unmatched = self.prods.unmatched.append(order.prods.unmatched.index)
self.counter += order.counter
def compile_results(self):
self.integrated_data = self.integrate_data()
self.pmts.unmatched = self.isolate_unmatched_payments()
def integrate_data(self):
pmts_minus_matches = self.pmts.original.drop(index=self.pmts.matched)
matched_prods_to_add = self.prods.original.loc[self.prods.matched]
integrated_data = pd.concat([pmts_minus_matches, matched_prods_to_add], ignore_index=True)
# Convert all dates to date objects (timezone-naive)
# Data should already be timezone-naive from cast_date_dtype(), but handle
# any potential timezone-aware datetimes that might have slipped through
# Use utc=True to normalize any timezone-aware datetimes, then remove timezone
# This ensures all dates are unified to date objects, matching original behavior
try:
# Try with utc=True first (handles timezone-aware datetimes)
integrated_data['date'] = pd.to_datetime(integrated_data['date'], utc=True).dt.tz_localize(None).dt.date
except (TypeError, ValueError):
# Fallback: if utc=True fails (e.g., with date objects), convert normally
# This matches the original behavior exactly
integrated_data['date'] = pd.to_datetime(integrated_data['date']).dt.date
return integrated_data
def isolate_unmatched_payments(self):
return self.pmts.filtered.drop(index=self.pmts.matched).index
def save(self):
with open(self.path, 'wb') as f:
pickle.dump(self, f)
def integrate_product_data(payments, products):
"""
Replace matchable Amazon payments with corresponding products.
Returns tuple: (integrated_data, unmatched_products)
"""
matcher = Matcher(payments, products, OUTPUT_DATA_DIR)
matcher.match()
# Get unmatched products: all original products minus matched products
# This is more reliable than using prods.unmatched which accumulates per order
all_product_indices = matcher.prods.original.index
matched_indices = matcher.prods.matched
unmatched_indices = all_product_indices.difference(matched_indices)
unmatched_products = matcher.prods.original.loc[unmatched_indices].copy()
# Convert unmatched products dates to date objects to match integrated_data format
# This ensures all dates are the same type (date objects) for consistent comparison
if len(unmatched_products) > 0 and 'date' in unmatched_products.columns:
try:
# Handle timezone-aware datetimes if present
unmatched_products['date'] = pd.to_datetime(unmatched_products['date'], utc=True).dt.tz_localize(None).dt.date
except (TypeError, ValueError):
# Fallback: if utc=True fails, convert normally
unmatched_products['date'] = pd.to_datetime(unmatched_products['date']).dt.date
return matcher.integrated_data, unmatched_products
def combine_ch_and_cc_data(data):
"""Combine all checking and credit card data, plus unmatched Amazon products."""
data_to_combine = [
data['jack_ch'],
data['jack_cc'],
data['jill_ch'],
data['jill_cc']
]
# Add unmatched Amazon products if they exist
if 'amzn_unmatched' in data and len(data['amzn_unmatched']) > 0:
data_to_combine.append(data['amzn_unmatched'])
return pd.concat(data_to_combine, ignore_index=True)
def combine(data):
"""
Swap Amazon payments in Jill's credit card data with more detailed
product purchase data and then combine all checking and credit card
data, plus unmatched Amazon products.
"""
# Debug: print row counts before combining
print("\n=== COMBINING DATA ===")
print(f" jill_cc before integration: {len(data['jill_cc'])} rows")
print(f" amzn products: {len(data['amzn'])} rows")
# Integrate products - returns (integrated_data, unmatched_products)
data['jill_cc'], data['amzn_unmatched'] = integrate_product_data(data['jill_cc'], data['amzn'])
print(f" jill_cc after integration: {len(data['jill_cc'])} rows")
print(f" amzn unmatched products: {len(data['amzn_unmatched'])} rows")
data['combined'] = combine_ch_and_cc_data(data)
print(f" combined total: {len(data['combined'])} rows")
print("=" * 50)
return data
# ============================================================================
# DATA LABELING
# ============================================================================
def vendor_is_known(row, table):
"""
Return `True` if the row description contains a familiar vendor
code and `False` if not.
"""
description = table.loc[row, 'description']
vendor_codes = VENDOR_DICT.keys()
for code in vendor_codes:
if code in description:
return True
return False
def get_known_labels(row, table):
"""Get pre-defined labels for a payment to a familiar vendor."""
description = table.loc[row, 'description']
vendor_codes = VENDOR_DICT.keys()
for code in vendor_codes:
if code in description:
labels = VENDOR_DICT[code]
return labels
async def make_product_labels(row, table):
"""Label one row of Amazon product data using the OpenAI API."""
if ACLIENT is None:
raise ImportError("OpenAI client is required for make_product_labels()")
product_name = table.loc[row, 'description']
instructions = PRODUCT_LABELING_INSTRUCTIONS
response = await ACLIENT.responses.parse(
model=MODEL,
input=product_name,
instructions=instructions,
text_format=CategoryResponse,
service_tier=SERVICE_TIER
)
labels = {
'vendor': 'Amazon',
'category': response.output_parsed.category,
'llm_category': 1
}
return labels
async def make_labels_with_OpenAI(row, table):
"""Label one row of payment data using the OpenAI API."""
if ACLIENT is None:
raise ImportError("OpenAI client is required for make_labels_with_OpenAI()")
description = table.loc[row, 'description']
instructions = PAYMENT_LABELING_INSTRUCTIONS
response = await ACLIENT.responses.parse(
model=MODEL,
input=description,
instructions=instructions,
text_format=DualResponse,
service_tier=SERVICE_TIER
)
labels = {
'vendor': response.output_parsed.vendor,
'category': response.output_parsed.category,
'llm_vendor': 1,
'llm_category': 1
}
return labels
async def make_payment_labels(row, table):
"""
Label one row of payment data.
This function returns pre-defined labels for familiar transactions
and makes new labels for other transactions with the OpenAI API.
"""
if vendor_is_known(row, table):
labels = get_known_labels(row, table)
else:
labels = await make_labels_with_OpenAI(row, table)
return labels
def make_row_instructions(table):
"""Make a list with one labeling coroutine for each row in table."""
row_instructions = []
for row in table.index:
if table.loc[row, 'account'] == 'amzn':
row_instructions.append(make_product_labels(row, table))
else:
row_instructions.append(make_payment_labels(row, table))
return row_instructions
async def process_asynchronously(row_instructions):
"""Process all coroutines in row_instructions asynchronously."""
labels = await ProgressBar.gather(
*row_instructions,
desc='Labeling Rows with OpenAI',
unit='row',
bar_format='{l_bar}{bar} {n_fmt}/{total_fmt} [{elapsed}]'
)
return labels
def make_table_instructions(row_instructions):
"""
Convert row_instructions into a function that contains all
asynchronous labeling operations for the source table.
"""
def table_instructions():
labels = asyncio.run(process_asynchronously(row_instructions))
return labels
return table_instructions
def make_labeling_instructions(table):
"""
Make a function that contains all asynchronous labeling operations
for table.
"""
row_instructions = make_row_instructions(table)
table_instructions = make_table_instructions(row_instructions)
return table_instructions
def make_labels(instructions):
"""
Make labels from instructions with the OpenAI API.
This function executes all asynchronous labeling operations in a
new thread to avoid conflict with Jupyter Notebook event loops.
"""
from concurrent.futures import ThreadPoolExecutor as JobManager
with JobManager() as m:
job = m.submit(instructions)
labels = job.result()
return labels
def apply_labels(all_labels, table):
"""Apply labels to table."""
for row, row_labels in zip(table.index, all_labels):
for column in row_labels:
table.loc[row, column] = row_labels[column]
return table
def save(table):
"""
Save table as labeled_data.csv in the output data folder defined in
the config module.
"""
table.to_csv(OUTPUT_DATA_DIR / 'labeled_data.csv', index=False)
def label(data):
"""
Label each row of data['combined'] and bind the result to
data['labeled'].
This function adds the following columns:
vendor: The transaction counterparty
category: The transaction category
llm_vendor: A binary flag that indicates that an LLM generated
the corresponding value in the vendor column
llm_category: A binary flag that indicates that an LLM
generated the corresponding value in the category column
"""
if ACLIENT is None:
raise ImportError("OpenAI client is required for label() function")
instructions = make_labeling_instructions(data['combined'])
labels = make_labels(instructions)
data['labeled'] = apply_labels(labels, data['combined'])
save(data['labeled'])
return data
# ============================================================================
# DATA ANALYSIS - STATISTICS
# ============================================================================
def show_time_period(table):
"""Display the dates of the earliest and latest transactions in table."""
# Ensure all dates are the same type (date objects) for comparison
# Convert any datetime objects to date objects to avoid comparison errors
date_col = table['date'].copy()
if date_col.dtype.name.startswith('datetime'):
# Has datetime objects - convert to date
date_col = pd.to_datetime(date_col).dt.date
else:
# Check if we have mixed types (datetime and date)
# Convert all to date objects to ensure consistency
try:
date_col = pd.to_datetime(date_col).dt.date
except (TypeError, ValueError):
# Already date objects or can't convert - use as is
pass
start_date = str(date_col.min())
end_date = str(date_col.max())
print('')
print(f'Time Period: {start_date} to {end_date}')
def show_total_spend(table):
"""Print the sum of all expenses in the given table."""
total_spend = table['amount'].sum()
print('')
print(f'Total Spending: ${total_spend:,.2f}')
def format_values(account_totals):
"""Format the values of account_totals as money."""
return account_totals.map(lambda x: f'${x:,.2f}')
def remove_unnecessary_data(account_totals):
"""
Remove the Series name, index name, and dtype from the
account_totals display.
"""
return account_totals.to_string(header=False)
def format_account_totals(account_totals):
"""Format values and remove unnecessary data."""
account_totals = format_values(account_totals)
account_totals = remove_unnecessary_data(account_totals)
return account_totals
def show_spend_by_account(table):
"""Print the sum of expenses by account."""
grouped_table = table.groupby('account')
account_totals = grouped_table['amount'].sum()
formatted_totals = format_account_totals(account_totals)
print('')
print('Spending by Account:')
print(formatted_totals)
print('')
def show_stats(table):
"""Calculate and display total spending and spending by account."""
show_total_spend(table)
show_spend_by_account(table)
def save_summary(table):
"""
Save summary statistics as CSV files in the output directory.
Creates summary CSV files with formatted text matching the console output.
"""
OUTPUT_DATA_DIR.mkdir(parents=True, exist_ok=True)
# Get summary data
start_date = str(table['date'].min())