]> piware.de Git - bin.git/blob - consors-report.py
f791e9cddfa5823ca7fc3470f7d0aa56e27e9f31
[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|Labor|Physio|(Drescher.*Lung)|(Debeka.*Überweisung)|(DKV.*Überweisung)', re.I),
18     'Versicherung': re.compile('(debeka|DKV|Hallesche|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|Malteser|(Aktion Tier.*Mensch)|'
27                           'campact', re.I),
28 }
29
30
31 def parse_args() -> argparse.Namespace:
32     parser = argparse.ArgumentParser(description='Read Consorsbank CSV and generate report')
33     parser.add_argument('-d', '--date', metavar='REGEX', default='.', help='date filter regex')
34     parser.add_argument('-s', '--summary', action='store_true', help='only show category sums')
35     parser.add_argument('csv', type=Path, nargs='+', help='CSV files to parse')
36     return parser.parse_args()
37
38
39 def get_category(item: str) -> str:
40     for category, pattern in CATEGORIES.items():
41         if pattern.search(item):
42             return category
43     return 'Sonstiges'
44
45
46 def parse_entry(line: str) -> Entry:
47     fields = [f.strip() for f in line.strip().split(';')]
48     # last field is the value, parse as float
49     value = float(fields.pop().replace('.', '').replace(',', '.'))
50     # match on who, IBAN, type, or desc
51     category = get_category(fields[2] + fields[3] + fields[5] + fields[6])
52     return Entry._make([category, *fields, value])
53
54
55 def parse_csv(path: Path, date_filter: str) -> Iterable[Entry]:
56     filter_re = re.compile(date_filter, re.I)
57
58     def filter_entry(entry: Entry):
59         # ignore from/to Tagesgeldkonto
60         if entry.iban == 'DE13760300800853589101':
61             return None
62         return filter_re.search(entry.date)
63
64     with path.open() as f:
65         # first line is the column headers, chop it off
66         entries = map(parse_entry, f.readlines()[1:])
67         return filter(filter_entry, entries)
68
69
70 def main():
71     args = parse_args()
72
73     entries = itertools.chain.from_iterable(map(lambda p: parse_csv(p, args.date), args.csv))
74     by_category = collections.defaultdict(lambda: [])
75     category_sum = collections.defaultdict(lambda: 0.0)
76     balance = 0.0
77     for e in entries:
78         by_category[e.category].append(e)
79         category_sum[e.category] += e.value
80         balance += e.value
81
82     if args.summary:
83         for cat in sorted(by_category):
84             print(f'| {category_sum[cat]:>8.2f} | {cat:20} |')
85         print('|----------|----------------------|')
86         print(f'| {balance:>8.2f} | {"Saldo":20} |')
87
88     else:
89         for cat in sorted(by_category):
90             print(f'## {cat}: {category_sum[cat]:.2f}\n')
91             for entry in by_category[cat]:
92                 print(f'| {entry.date:7} | {entry.value:>7.2f} | _{entry.type}_ - {entry.who} - {entry.desc} |')
93             print()
94
95         print(f'## Saldo: {balance:.2f}')
96
97
98 if __name__ == '__main__':
99     main()