aboutsummaryrefslogtreecommitdiffstats
path: root/python/report_ops/wires.py
blob: 6da3ac292ac4a1f30f044b426ff08e2791b1792d (plain)
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
import datetime
from csv import DictReader
from typing import ClassVar
from functools import partial
from dataclasses import dataclass, field, Field
import pandas as pd

from serenitas.ops.trade_dataclasses import Ccy
from serenitas.ops.dataclass_mapping import Fund
from serenitas.analytics.dates import prev_business_day
from serenitas.analytics.exceptions import MissingDataError
from serenitas.utils.env import DAILY_DIR
from serenitas.utils.db2 import dbconn

from .misc import get_dir, dt_from_fname, Custodian
from .base import Report


@dataclass
class WireReport(Report, table_name="custodian_wires"):
    date: datetime.date
    fund: Fund
    custodian: ClassVar[Custodian]
    entry_date: datetime.date
    value_date: datetime.date
    pay_date: datetime.date
    currency: Ccy
    amount: float
    wire_details: str
    unique_ref: str
    dtkey: ClassVar = field(metadata={"insert": False})
    _registry: ClassVar = field(default={}, metadata={"insert": False})

    def __init_subclass__(cls, custodian, dtkey):
        cls.custodian = custodian
        cls._registry[custodian] = cls
        cls.dtkey = dtkey

    def __class_getitem__(cls, custodian):
        return cls._registry[custodian]

    def __post_init__(self):
        if isinstance(self.amount, str):
            self.amount = self.amount.replace(",", "")
            if "(" in self.amount:
                self.amount = -float(self.amount[1:-1])
            else:
                self.amount = float(self.amount)

    @classmethod
    def get_report(cls, date, fund, prefix=None):
        report_dir = get_dir(date)
        report_dir.mkdir(exist_ok=True, parents=True)
        prefix = prefix if prefix else f"{cls.custodian}_WIRE_{fund}"
        p = max(
            [f for f in get_dir(date).iterdir() if f.name.startswith(prefix)],
            key=partial(dt_from_fname, dt_format=cls.dtkey),
            default=None,
        )
        if not p:
            raise MissingDataError(
                f"No reports found for fund: {prefix.split('_')[-1]} date: {date}"
            )
        return p


class BNYWireReport(WireReport, custodian="BNY", dtkey="%Y%m%d%H%M%S"):
    @classmethod
    def from_report_line(cls, line: dict):
        return cls(
            date=line["Report Run Date"],
            entry_date=line["Cash Entry Date"],
            value_date=line["Cash Value Date"],
            pay_date=line["Settle / Pay Date"],
            currency=line["Local Currency Code"],
            amount=line["Local Amount"],
            wire_details=line["Transaction Description 1"]
            if line["Transaction Type Code"] == "CW"
            else line["Transaction Description 2"],
            unique_ref=line["Reference Number"],
            fund=line["fund"],
        )

    @classmethod
    def yield_rows(cls, date, fund):
        p = cls.get_report(date, fund)
        with open(p) as fh:
            reader = DictReader(fh)
            yield from reader


class NTWireReport(WireReport, custodian="NT", dtkey="%Y%m%d%H%M"):
    @classmethod
    def from_report_line(cls, line: dict):
        return cls(
            date=line["Through date"],
            entry_date=line["D-GL-POST"],
            value_date=line["D-TRAN-EFF"],
            pay_date=line["D-TRAN-EFF"],
            currency=cls.nt_to_enum(line["N-GL-AC30"]),
            amount=line["Net amount - local"],
            wire_details=line["narrative"],
            unique_ref=line["C-EXTL-SYS-TRN-DSC-3"],
            fund=line["fund"],
        )

    @classmethod
    def yield_rows(cls, date, fund):
        p = cls.get_report(date, fund)
        with open(p) as fh:
            reader = DictReader(fh)
            for line in reader:
                if "sponsor" in line["narrative"].lower():
                    yield line

    @staticmethod
    def nt_to_enum(ccy):
        _mapping = {"EURO - EUR": "EUR", "U.S. DOLLARS - USD": "USD"}
        return _mapping[ccy]


class UMBWireReport(WireReport, custodian="UMB", dtkey="%Y%m%d%H%M"):
    @classmethod
    def from_report_line(cls, line: dict):
        return cls(
            date=line["Transaction Date"],
            entry_date=line["Transaction Date"],
            value_date=line["Transaction Date"],
            pay_date=line["Transaction Date"],
            currency=line["Local Currency Code"],
            amount=line["Net Amount"],
            wire_details=line["Transaction Description"],
            unique_ref=f'{line["Transaction Date"]}-{line["index"]}',
            fund=line["fund"],
        )

    @classmethod
    def yield_rows(cls, date, fund):
        p = cls.get_report(date, fund)
        conn = cls._conn
        # We only have one report for UMB with no unique identifier. Delete and reupload recent is the only way
        with conn.cursor() as c:
            c.execute(
                "DELETE FROM custodian_wires WHERE date=%s AND fund=%s AND custodian=%s",
                (
                    date,
                    fund,
                    cls.custodian,
                ),
            )
        conn.commit()
        df = pd.read_excel(p, skiprows=3)
        df["index"] = df.index
        for line in df.to_dict(orient="records"):
            if line["Transaction Date"].startswith(
                "No records"
            ):  # No wires at the moment
                return
            yield line


class SCOTIAWireReport(WireReport, custodian="SCOTIA", dtkey=None):
    @classmethod
    def from_report_line(cls, line: dict):
        return cls(
            date=line["Value Date"],
            entry_date=line["Posting Date"],
            value_date=line["Value Date"],
            pay_date=line["Value Date"],
            currency=line["Curr."],
            amount=line["Cr Amount"] if line["Dr/Cr"] == "Cr" else -line["Dr Amount"],
            wire_details=line["Reference Data"],
            unique_ref=line["Bank Ref."],
            fund=line["fund"],
        )

    @classmethod
    def yield_rows(cls, date, fund):
        p = cls.get_report(date, fund)
        conn = cls._conn
        with conn.cursor() as c:
            c.execute(
                "SELECT 1 FROM custodian_wires WHERE date=%s AND fund=%s AND custodian=%s",
                (
                    prev_business_day(date),
                    fund,
                    cls.custodian,
                ),
            )
            if not (_ := c.fetchone()):
                df = pd.read_excel(p, skipfooter=2)
                df["index"] = df.index
                yield from df.to_dict(orient="records")

    @classmethod
    def get_report(cls, date, fund):
        REPORT_DIR = DAILY_DIR / "Selene" / "Scotia_reports"
        return next(
            REPORT_DIR.glob(
                f"IsoSelene_{prev_business_day(date):%d-%b-%Y}_*_xlsx.JOAAPKO3.JOAAPKO1"
            )
        )