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