aboutsummaryrefslogtreecommitdiffstats
path: root/python/mtm_upload.py
blob: a255218fbea40236e94fd721260aeaafad15e823 (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
from serenitas.utils.db import dbconn
from io import StringIO
import csv
from serenitas.utils.env import DAILY_DIR
from serenitas.utils.remote import SftpClient
from serenitas.analytics.dates import next_business_day
import datetime
from trade_dataclasses import CDSDeal, SwaptionDeal

HEADERS = {
    "tranche": [
        "Swap ID",
        "Allocation ID",
        "Description",
        "Broker Id",
        "DTCC CounterParty ID",
        "Trade ID",
        "Trade Date",
        "Effective Date",
        "Settle Date",
        "Maturity Date",
        "Account Abbreviation",
        "1st Leg Notional",
        "Currency Code",
        "1st Leg Rate",
        "Initial Payment",
        "Initial Payment Currency",
        "Original Issue Date",
        "Interest Payment Method Description",
        "First Payment Date",
        "Product Type",
        "Product Sub Type",
        "Transaction Type",
        "Protection",
        "Transaction Code",
        "Remaining Party",
        "DTCC Remaining CounterParty ID",
        "Independent Amount (%)",
        "Independent Amount ($)",
        "RED",
        "Issuer Name",
        "Settlement Amount",
        "Trader",
        "Executing Broker",
        "Dealer Trade ID",
        "Notes",
        "Parent Transaction Code",
        "Parent Trade Date",
        "Parent Notional",
        "Parent Currency Code",
        "Parent Net Amount",
        "Parent Effective Date",
        "Parent First Payment Date",
        "Parent Settle Date",
        "ComplianceHubAction",
        "DTCC Ineligible",
        "Master Document Date",
        "Master Document Version",
        "Include Contractual Supplement",
        "Contractual Supplement",
        "Supplement Date",
        "Entity Matrix",
        "Entity Matrix Date",
        "Modified Equity Delivery",
        "Calculation Agent Business Center",
        "Calculation Agent",
        "Attachment Point",
        "Exhaustion Point",
        "Strategy",
        "First Payment Period Accrual Start Date",
        "TieOut Ineligible",
        "Electronic Consent Ineligible",
        "External OMS ID",
        "Independent Amount Currency",
        "Independent Amount Payer",
        "Trade Revision",
        "Alternate Swap ID",
        "Alternate Trade ID",
        "Definitions Type",
    ],
    "swaption": [
        "Swap ID",
        "Broker Id",
        "Trade ID",
        "Trade Date",
        "Settle Date",
        "Supplement Date",
        "Supplement 2 Date",
        "Maturity Date",
        "Account Abbreviation",
        "1st Leg Notional",
        "Currency Code",
        "1st Leg Rate",
        "Initial Payment Currency",
        "Initial Payment",
        "Product Type",
        "Transaction Type",
        "Transaction Code",
        "Independent Amount (%)",
        "RED",
        "Issuer Name",
        "Entity Matrix",
        "Definitions Type",
        "Swaption Expiration Date",
        "Strike Price",
        "Swaption Settlement Type",
        "Master Document Date",
        "OptionBuySellIndicator",
        "Clearing House",
        "Protection",
        "Swaption Quotation Rate Type",
        "Effective Date",
    ],
}


def rename_keys(d, mapping):
    """rename keys in dictionary according to mapping dict inplace"""
    for k, v in mapping.items():
        if k in d:
            d[v] = d.pop(k)


def tranche_trades(tradeids, conn):
    trades = []
    for tradeid in tradeids:
        obj = CDSDeal.from_tradeid(tradeid).to_markit()
        trades.append(obj)
    return trades


def swaption_trades(tradeids, conn):
    trades = []
    for tradeid in tradeids:
        obj = SwaptionDeal.from_tradeid(tradeid).to_markit()
        trades.append(obj)
    return trades


def tranche_term_trades(conn):
    with conn.cursor() as c:
        trades = []
        c.execute(
            "SELECT terminations.*, cds.fund, cds.cp_code FROM terminations left join cds using (dealid) where termination_date >= %s and dealid LIKE %s",
            (datetime.date(2022, 3, 1), "SCCDS%"),
        )
        for row in c:
            obj = row._asdict()
            rename_keys(
                obj,
                {
                    "dealid": "Swap ID",
                    "termination_cp": "Broker Id",
                    "termination_amount": "1st Leg Notional",
                    "termination_fee": "Initial Payment",
                    "termination_date": "Trade Date",
                    "fee_payment_date": "Settle Date",
                    "fund": "Account Abbreviation",
                    "termination_cp": "Broker Id",
                    "cp_code": "Remaining Party",
                },
            )
            if obj["Initial Payment"] >= 0:
                obj["Transaction Code"] = "Receive"
            else:
                obj["Initial Payment"] = abs(obj["Initial Payment"])
                obj["Transaction Code"] = "Pay"
            obj["Currency Code"] = "USD"
            obj["Product Type"] = "TRN"
            obj["Entity Matrix"] = "Publisher"
            obj["Definitions Type"] = "ISDA2003Credit"
            obj["Trade ID"] = obj["Swap ID"] + "-" + str(obj["id"])
            obj["Transaction Type"] = "Partial Assignment"
            obj["Effective Date"] = obj["Trade Date"] + datetime.timedelta(days=1)
            trades.append(obj)
    return trades


def build_line(obj, asset_type):
    return [obj.get(h, None) for h in HEADERS[asset_type]]


def process_upload(trades, asset_type, upload):
    buf = StringIO()
    csvwriter = csv.writer(buf)
    csvwriter.writerow(HEADERS[asset_type])
    csvwriter.writerows(build_line(trade, asset_type) for trade in trades)
    buf = buf.getvalue().encode()
    fname = f"MTM.{datetime.datetime.now():%Y%m%d.%H%M%S}.{asset_type.capitalize()}.csv"
    sftp = SftpClient.from_creds("mtm")
    sftp.put(buf, fname)
    dest = DAILY_DIR / str(datetime.date.today()) / fname
    dest.write_bytes(buf)


def upload_mtm_trades(trade_type, tradeid):
    _funs = {
        "swaption": (SwaptionDeal, "swaption"),
        "cds": (CDSDeal, "tranche"),
    }
    process_upload(
        (_funs[trade_type][0].from_tradeid(tradeid).to_markit(),),
        _funs[trade_type][1],
        upload=True,
    )


if __name__ == "__main__":
    conn = dbconn("dawndb")
    upload_trades(conn)