]> piware.de Git - bin.git/blob - consors-report.py
consors-report.py: updates
[bin.git] / consors-report.py
1 #!/usr/bin/python3
2
3 import argparse
4 import collections
5 import csv
6 import itertools
7 import re
8 from collections import namedtuple
9 from pathlib import Path
10 from typing import Iterable
11
12 Entry = namedtuple('Entry', ['category', 'date', 'valuta', 'who', 'iban', 'bic', 'type', 'desc', 'value'])
13
14 CATEGORIES = {
15     'Gehalt/Steuern': re.compile('Gehalt/Rente|RED HAT|Finanzamt|FK Guenzburg', re.I),
16     'Wohnung': re.compile('Telekom|hands4home|Goetzfried|Green Planet Energy|Beitragsservice.*Rundfunk', re.I),
17     'Medizin': re.compile(r'Apotheke|MVZ|\bmed\b|ZAB Abrechnung|Caika|HNOeins|PVS|Dr\..*Sellier|'
18                           r'BFS Health|Streifeneder|Labor|Physio|(Drescher.*Lung)|Osteopath|'
19                           '(Dr.*Borchers)|(Debeka.*Überweisung)|(DKV.*Überweisung)|Beihilfe|Klinik', re.I),
20     'Versicherung': re.compile('((debeka|DKV|Hallesche|Versicherung|Alte Leipziger|ConceptIF|'
21                                'Baloise).*Lastschrift)|Hallesche.*Bonu', re.I),
22     'Transport': re.compile('DB Vertrieb|Deutsche Bahn|Nextbike|Carsharing', re.I),
23     'Lebensmittel': re.compile('BIOS|Bäcker|Baecker|Ruta|Rewe', re.I),
24     'Eigentumswohnungen': re.compile('Rechnung Darl.-Leistung|Semmelweis', re.I),
25     'Hobby/Sport': re.compile('Holstein|Mrs. Sporty|Kieser|DJK|Dimaso', re.I),
26     'Sparen': re.compile('Bausparkasse Mainz AG|FIL Fondsbank|MIG (Fonds|GmbH)|Netfonds AG', re.I),
27     'Spenden': re.compile('Spende|Signal Foundation|nebenan.de|(paypal.*Sabine.Hossenf)|'
28                           'Patreon|Umwelthilfe|Foerderer|Malteser|(Aktion Tier.*Mensch)|'
29                           'campact|Amnesty', re.I),
30 }
31
32
33 def parse_args() -> argparse.Namespace:
34     parser = argparse.ArgumentParser(description='Read Consorsbank CSV and generate report')
35     parser.add_argument('-d', '--date', metavar='REGEX', default='.', help='date filter regex')
36     parser.add_argument('-s', '--summary', action='store_true', help='only show category sums')
37     parser.add_argument('csv', type=Path, nargs='+', help='CSV files to parse')
38     return parser.parse_args()
39
40
41 def get_category(item: str) -> str:
42     for category, pattern in CATEGORIES.items():
43         if pattern.search(item):
44             return category
45     return 'Sonstiges'
46
47
48 def parse_entry(raw_fields: Iterable[str]) -> Entry:
49     fields = [f.strip() for f in raw_fields]
50     # last field is the value, parse as float
51     value = float(fields.pop().replace('.', '').replace(',', '.'))
52     # match on who, IBAN, type, or desc
53     category = get_category(fields[2] + fields[3] + fields[5] + fields[6])
54     return Entry._make([category, *fields, value])
55
56
57 def parse_csv(path: Path, date_filter: str) -> Iterable[Entry]:
58     filter_re = re.compile(date_filter, re.I)
59
60     def filter_entry(entry: Entry):
61         # ignore from/to Tagesgeldkonto
62         if entry.iban == 'DE13760300800853589101':
63             return None
64         return filter_re.search(entry.date)
65
66     with path.open() as f:
67         reader = csv.reader(f)
68         next(reader)  # skip header
69         # first line is the column headers, chop it off
70         entries = map(parse_entry, reader)
71         # do the actual iteration here, as the files get closed afterwards
72         return list(filter(filter_entry, entries))
73
74
75 def main():
76     args = parse_args()
77
78     entries = itertools.chain.from_iterable(map(lambda p: parse_csv(p, args.date), args.csv))
79     by_category = collections.defaultdict(lambda: [])
80     category_sum = collections.defaultdict(lambda: 0.0)
81     balance = 0.0
82     for e in entries:
83         by_category[e.category].append(e)
84         category_sum[e.category] += e.value
85         balance += e.value
86
87     if args.summary:
88         for cat in sorted(by_category):
89             print(f'| {category_sum[cat]:>8.2f} | {cat:20} |')
90         print('|----------|----------------------|')
91         print(f'| {balance:>8.2f} | {"Saldo":20} |')
92
93     else:
94         for cat in sorted(by_category):
95             print(f'## {cat}: {category_sum[cat]:.2f}\n')
96             for entry in by_category[cat]:
97                 print(f'| {entry.date:7} | {entry.value:>7.2f} | _{entry.type}_ - {entry.who} - {entry.desc} |')
98             print()
99
100         print(f'## Saldo: {balance:.2f}')
101
102
103 if __name__ == '__main__':
104     main()