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