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
|
#! /usr/bin/python
import argparse
import csv
import datetime
from process_queue import build_termination, upload_file
from env import DAILY_DIR
from utils.db import dbconn
from io import StringIO
def build_termination(
base_dir,
dawndb,
dealid,
fee,
*,
termination_date=datetime.date.today(),
termination_amount=None,
termination_cp=None,
deal_type="CreditDefaultSwapDeal",
):
""" if termination_amount is None, assume full termination
if termination_cp is None assume termination, otherwise assignment
"""
if deal_type == "CreditDefaultSwapDeal":
table = "cds"
elif deal_type == "SwaptionDeal":
table = "swaptions"
else:
raise ValueError("Unkown deal_type: {deal_type}")
with dawndb.cursor() as c:
c.execute(
"SELECT dealid, cp_code, notional, termination_amount, "
"globeop_id, currency "
f"FROM {table} where id=%s",
(dealid,),
)
dealid, cp_code, notional, partial_amounts, globeopid, ccy = c.fetchone()
if partial_amounts is not None:
remaining_notional = notional - sum(partial_amounts)
else:
remaining_notional = notional
termination_amount = termination_amount or remaining_notional
if deal_type == "CreditDefaultSwapDeal":
c.execute(
f"UPDATE {table} "
"SET termination_amount=termination_amount||%s::float8, "
"termination_cp=termination_cp||%s::text, "
"termination_fee=termination_fee||%s::float8, "
"termination_date=termination_date||%s::date "
"WHERE dealid=%s",
(
termination_amount,
termination_cp or cp_code,
fee,
termination_date,
dealid,
),
)
else:
c.execute(
f"UPDATE {table} "
"SET termination_amount=%s::float8, "
"termination_cp=%s::text, "
"termination_fee=%s::float8, "
"termination_date=%s::date "
"WHERE dealid=%s",
(
termination_amount,
termination_cp or cp_code,
fee,
termination_date,
dealid,
),
)
dawndb.commit()
headers = [
"DealType",
"DealId",
"Action",
"Client",
"SubAction",
"PartialTermination",
"TerminationAmount",
"TerminationDate",
"FeesPaid",
"FeesReceived",
"DealFunction",
"Reserved",
"ClientReference",
]
if deal_type == "CreditDefaultSwapDeal":
headers += ["TradeDate", "EffectiveDate", "FirstCouponDate"]
else:
headers += ["Reserved"] * 3
headers += ["FeePaymentDate", "SpecialInstructions"]
if termination_cp is not None:
headers += ["AssignedCounterparty"]
else:
headers += ["Reserved"]
if deal_type == "CreditDefaultSwapDeal" and termination_cp is not None:
headers += [
"AssignmentFee",
"AssignedFeeTradeDate",
"AssignedFeeValueDate",
"AssignedCustodian",
"AssignedCashAccount",
"Reserved",
"FeeCurrency",
]
else:
headers += ["Reserved"] * 7
headers += ["GoTradeId"]
if deal_type == "CreditDefaultSwapDeal":
headers += ["FeeComments", "ZeroOutInterestCashFlows"]
else:
headers += ["Reserved"] * 2
headers += ["Reserved"] * 4
if deal_type == "SwaptionDeal":
headers += ["Reserved"] * 2 + ["InMoney", "FeeCurrency"]
elif deal_type == "CreditDefaultSwapDeal":
if termination_cp is None:
headers += ["Reserved"] * 3
else:
headers += ["AssignedDealFunction"] + ["Reserved"] * 2
headers += ["InitialMargin", "InitialMarginCurrency"]
if termination_cp is None:
headers += ["Reserved"] * 4 + ["CreditEventOccured"]
d = {
"DealType": deal_type,
"GoTradeId": int(globeopid[3:9]),
"Action": "Update",
"Client": "Serenitas",
"SubAction": "Termination",
"PartialTermination": "Y"
if remaining_notional - termination_amount > 0
else "N",
"TerminationAmount": termination_amount,
"TerminationDate": termination_date,
"FeesPaid": -fee if fee < 0 else None,
"FeesReceived": fee if fee > 0 else None,
"FeePaymentDate": (termination_date + 3 * bus_day).date(),
}
if "FeeCurrency" in headers:
d["FeeCurrency"] = ccy
if termination_cp is not None:
d["AssignedCounterparty"] = termination_cp
buf = StringIO()
csvwriter = csv.DictWriter(buf, headers)
csvwriter.writeheader()
csvwriter.writerow(d)
timestamp = datetime.datetime.now()
trade_type = f"{deal_type}A" if termination_cp is not None else f"{deal_type}T"
file_path = (
base_dir
/ str(timestamp.date())
/ f"Serenitas.ALL.{timestamp:%Y%m%d.%H%M%S}.{trade_type}.csv"
)
file_path.write_bytes(buf.getvalue().encode())
return file_path
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="helper script to terminate or assign a trade"
)
parser.add_argument("dealid", help="Serenitas id", type=int)
parser.add_argument(
"fee", help="termination fee ( >0 we receive money)", type=float
)
parser.add_argument(
"--date",
"-d",
help="termination date, default to today's date",
type=datetime.date.fromisoformat,
default=datetime.date.today(),
)
parser.add_argument(
"--amount",
"-a",
help="termination amount, if missing full termination",
default=None,
required=False,
)
parser.add_argument(
"--counterparty",
"-c",
help="termination counterparty, if missing, original counterparty is used (termination)",
default=None,
required=False,
)
args = parser.parse_args()
dawndb = dbconn("dawndb")
if "tranche" in __file__:
deal_type = "CreditDefaultSwapDeal"
elif "swaption" in __file__:
deal_type = "SwaptionDeal"
else:
raise RuntimeError("Incorrect deal type")
p = build_termination(
DAILY_DIR,
dawndb,
args.dealid,
args.fee,
termination_date=args.date,
termination_cp=args.counterparty,
termination_amount=args.amount,
deal_type=deal_type,
)
upload_file(p)
|