aboutsummaryrefslogtreecommitdiffstats
path: root/python/report_ops/utils.py
blob: bf9ed3d9c533d344e87998e6d13840be109d0746 (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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import datetime
import math
import logging
from dataclasses import dataclass
from typing import ClassVar
from exchangelib import HTMLBody
from tabulate import tabulate

from serenitas.utils.exchange import ExchangeMessage, FileAttachment
from serenitas.analytics.dates import next_business_day

from .misc import (
    _recipients,
    _cc_recipients,
    _settlement_recipients,
    _valuation_recipients,
)

logger = logging.getLogger(__name__)


def next_business_days(date, offset):
    for i in range(offset + 1):
        date = next_business_day(date)
    return date


def round_up(n, decimals=0):
    multiplier = 10**decimals
    return math.ceil(n * multiplier) / multiplier


def notify_payment_settlements(date, fund, conn):
    end_date = next_business_days(date, 2)
    with conn.cursor() as c:
        c.execute(
            "SELECT * from payment_settlements WHERE settle_date BETWEEN %s AND %s AND fund= %s AND asset_class in ('SPOT', 'SWAPTION', 'TRANCHE') ORDER BY settle_date asc",
            (date, end_date, fund),
        )
        for row in c:
            d = row._asdict()
            d["settlement_amount"] = d["payment_amount"]
            PaymentMonitor.stage(d)
    PaymentMonitor.email(fund)
    PaymentMonitor._staging_queue.clear()


def notify_fx_hedge(date, fund, conn):
    with conn.cursor() as c:
        c.execute(
            "SELECT * from fcm_moneyline LEFT JOIN accounts2 ON account=cash_account WHERE date=%s AND currency='EUR' AND fund=%s AND abs(current_excess_deficit) > 1000000",
            (date, fund),
        )
        for row in c:
            d = row._asdict()
            d["amount"] = d["current_excess_deficit"]
            d["category"] = "FCM"
            FxHedge.stage(d)
    FxHedge.email(fund)
    FxHedge._staging_queue.clear()


def check_cleared_cds(date, fund, conn):
    _tolerance = {"IG": 0.10, "HY": 0.20, "EU": 0.20, "XO": 0.30}
    with conn.cursor() as c:
        c.execute(
            "SELECT * FROM list_cds_marks(%s, NULL, %s), fx WHERE date=%s AND abs((notional*factor) - globeop_notional) < 100;",
            (date, fund, date),
        )
        for row in c:
            d = row._asdict()
            d["serenitas_quote"] = d["price"]
            match d["index"]:
                case "XO" | "EU":
                    d["admin_quote"] = 100 - (
                        ((d["globeop_nav"] - d["accrued"]) / d["eurusd"])
                        / (d["globeop_notional"] / 100)
                    )
                case _:
                    d["admin_quote"] = 100 - (
                        (d["globeop_nav"] - d["accrued"])
                        / (d["globeop_notional"] / 100)
                    )
            d["difference"] = abs(d["price"] - d["admin_quote"])
            if d["difference"] > _tolerance[d["index"]]:
                CDXQuoteMonitor.stage(d)
        CDXQuoteMonitor.email(fund)
        CDXQuoteMonitor._staging_queue.clear()


@dataclass
class Monitor:
    date: datetime.date
    headers: ClassVar = ()
    num_format: ClassVar = []
    _staging_queue: ClassVar[list] = []
    _em: ClassVar = ExchangeMessage()

    def __init_subclass__(cls, headers, num_format=[]):
        cls.headers = headers
        cls.num_format = num_format

    @classmethod
    def stage(cls, d: dict):
        cls._staging_queue.append(list(d[key] for key in cls.headers))

    @classmethod
    def format(cls):
        for line in cls._staging_queue:
            for f, i in cls.num_format:
                line[i] = f.format(line[i])

    @classmethod
    def to_tabulate(cls):
        cls.format()
        t = tabulate(
            cls._staging_queue,
            headers=cls.headers,
            tablefmt="unsafehtml",
        )
        return t

    @classmethod
    def clear(cls):
        cls._staging_queue.clear()


class GFSMonitor(
    Monitor,
    headers=(
        "date",
        "portfolio",
        "amount",
        "currency",
    ),
    num_format=[("{0:,.2f}", 2)],
):
    @classmethod
    def email(cls, fund):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"GFS Helper Strategy Issue: {fund}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  Good morning,<br><br>Could you please help us with the below transfer breaks:<br><br>{cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=_recipients[fund],
            cc_recipients=_cc_recipients[fund],
        )


class BondMarkMonitor(
    Monitor,
    headers=(
        "periodenddate",
        "invid",
        "geneva_identifier",
        "pricelist",
        "knowledgedate",
    ),
    num_format=[],
):
    @classmethod
    def email(cls, fund):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"Incorrectly marked trades: {fund}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  Good morning,<br><br>Could you please use Manager marks for the below trades:<br><br>{cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=_valuation_recipients[fund],
            cc_recipients=_cc_recipients[fund],
        )


class CDXQuoteMonitor(
    Monitor,
    headers=(
        "security_desc",
        "security_id",
        "maturity",
        "admin_quote",
        "serenitas_quote",
        "difference",
    ),
    num_format=[("{0:,.2f}", 3), ("{0:,.2f}", 4), ("{0:,.2f}", 5)],
):
    @classmethod
    def email(cls, fund):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"CDX Quote Outside of our Tolerance: {fund}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  Good morning,<br><br>Could you please help us with the below cleared CDX quotes outside of our tolerance:<br><br>{cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=_valuation_recipients[fund],
            cc_recipients=_cc_recipients[fund],
        )


class CDXNotionalMonitor(
    Monitor,
    headers=(
        "security_desc",
        "security_id",
        "maturity",
        "admin_notional",
        "serenitas_notional",
        "difference",
    ),
    num_format=[("{0:,.2f}", 3), ("{0:,.2f}", 4), ("{0:,.2f}", 5)],
):
    @classmethod
    def email(cls, fund):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"CDX Notional Mismatches: {fund}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  Good morning,<br><br>Mismatched cleared cds notional mismatches below:<br><br>{cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=_cc_recipients[fund],
        )


class SettlementMonitor(
    Monitor,
    headers=("date", "account", "currency", "projected_balance"),
    num_format=[("{0:,.2f}", 3)],
):
    @classmethod
    def email(cls, fund):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"*ACTION REQUESTED* Projected Overdraft: {fund}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  Hello,<br><br>We see a projected overdraft on the below dates. Please move to cover:<br><br>{cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=_recipients[fund],
            cc_recipients=_cc_recipients[fund],
        )


class PaymentMonitor(
    Monitor,
    headers=(
        "settle_date",
        "account",
        "name",
        "cp_code",
        "settlement_amount",
        "currency",
        "asset_class",
        "ids",
    ),
    num_format=[("{0:,.2f}", 4)],
):
    @classmethod
    def email(cls, fund):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"Projected Settlements: {fund}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  Hello,<br><br>We see the below settlements in the next two days (Positive=Receive, Negative=Pay):<br><br>{cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=_settlement_recipients[fund],
            cc_recipients=_cc_recipients[fund],
        )


class FxHedge(
    Monitor,
    headers=(
        "date",
        "account",
        "amount",
        "currency",
        "fund",
        "category",
    ),
    num_format=[("{0:,.2f}", 2)],
):
    @classmethod
    def email(cls, fund):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"Projected Hedges: {fund}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  Hello,<br><br>Here are the positions we need to hedge:<br><br>{cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=("fyu@lmcg.com",),
        )


class QuantifiMonitor(
    Monitor,
    headers=(
        "uploadtime",
        "filename",
        "errors",
        "warnings",
        "successes",
        "total",
    ),
    num_format=[],
):
    @classmethod
    def email(cls, filename, errors, buf):
        if not cls._staging_queue:
            return
        cls._em.send_email(
            f"Quantifi Report: {filename} {'**Errors**' if errors else ''}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  {cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=("fyu@lmcg.com",),
            attach=[FileAttachment(name=filename + ".xml", content=buf)],
        )


class CitcoMonitor(
    Monitor,
    headers=(
        "process_date",
        "submit_date",
        "identifier_type",
        "citco_id",
        "serenitas_id",
        "id",
    ),
    num_format=[],
):
    @classmethod
    def email(cls, filename, buf):
        if not cls._staging_queue:
            return
        recipients = _recipients["NY_CREW"]
        action_requested = ""
        if cls.check_csm():
            recipients += ("SYamamiya@citco.com", "DataOpsTC@citco.com")
            action_requested += "**Action Requested, TradeID Failed**"
        cls._em.send_email(
            f"(CITCO) UPLOAD REPORT: {filename} {action_requested}",
            HTMLBody(
                f"""
<html>
  <head>
    <style>
      table, th, td {{ border: 1px solid black;  border-collapse: collapse;}}
      th, td {{ padding: 5px; }}
    </style>
  </head>
  <body>
  {cls.to_tabulate()}
  </body>
</html>"""
            ),
            to_recipients=recipients,
            attach=[FileAttachment(name=filename, content=buf)],
        )

    @classmethod
    def check_csm(cls):
        for line in cls._staging_queue:
            if "TID NOT FOUND" in line[3]:
                return True