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
|
import datetime
import json
import os
import pandas as pd
from . import DAILY_DIR
from pathlib import Path
from serenitas.utils.remote import FtpClient, SftpClient
from serenitas.analytics.dates import prev_business_day
import gnupg
import re
import logging
import sys
sys.path.append("..")
import load_globeop_report
logger = logging.getLogger(__name__)
def get_ped(s):
if m := re.search("PED=([^.]+)", s):
PED = datetime.date.fromisoformat(m.group(1))
elif m := re.search("([^.]+)", s):
PED = prev_business_day(
datetime.datetime.strptime(m.group(1), format="%Y%m%d").date()
)
else:
raise ValueError
return PED
def key_fun(s):
PED = get_ped(s)
if m := re.search("KD=([^.]+)", s):
KD = datetime.datetime.strptime(m.group(1), "%Y-%m-%d-%H-%M-%S")
elif m := re.search(r"([^.]+\.[^.]+)", s):
KD = datetime.datetime.strptime(m.group(1), "%Y%m%d.%H%M%S")
else:
raise ValueError
return (PED, KD)
def run_date(s):
if "SWO" in s:
date_string = s.split("_", 5)[4]
else:
date_string = s.split("_", 3)[2]
return datetime.datetime.strptime(date_string, "%Y%m%d.%H%M%S")
def get_ftp(folder):
ftp = FtpClient.from_creds("globeop")
ftp.client.cwd(folder)
return ftp
def get_gpg():
if os.name == "nt":
gpg = gnupg.GPG(
gpgbinary=r'"c:\\Program Files (x86)\\GNU\\GnuPG\\gpg2.exe"',
gnupghome=os.path.join(os.getenv("APPDATA"), "gnupg"),
)
elif os.name == "posix":
gpg = gnupg.GPG(gnupghome=Path.home() / ".gnupg")
gpg.encoding = "utf8"
return gpg
def convert_to_csv(f):
mapping = (("Credit Default Swap", "CDS"), ("Swaption", "Swaption"), ("ALL", "All"))
if f.exists():
for sheet, name in mapping:
df = pd.read_excel(f, sheet_name=sheet, skiprows=[0, 1, 2, 3])
df.to_csv(f.parent / f"{name}_Report.csv", index=False)
f.unlink()
def download_data(engine, workdate: datetime.date, fund="SERCGMAST"):
ftp = FtpClient.from_creds("globeop")
ftp.client.cwd("outgoing")
files = ftp.client.nlst()
pnlfiles = [
filename
for filename in files
if filename.endswith("csv.asc") and "Profit" in filename and fund in filename
if get_ped(filename) < workdate
]
valuationfiles = [
filename
for filename in files
if filename.endswith("csv.asc")
and "Valuation_TradeID" in filename
and fund in filename
if get_ped(filename) < workdate
]
cdsfiles = [
filename
for filename in files
if "TradeSearch" in filename
if run_date(filename).date() <= workdate
]
available_files = []
if pnlfiles:
available_files.append(max(pnlfiles, key=key_fun))
if valuationfiles:
available_files.append(max(valuationfiles, key=key_fun))
if cdsfiles:
available_files.append(max(cdsfiles, key=run_date))
if not available_files:
logger.error("no file available for date: %s" % str(workdate))
return
reports_dir = DAILY_DIR / str(workdate) / "Reports"
if not reports_dir.exists():
reports_dir.mkdir(parents=True)
for filename in available_files:
with (reports_dir / filename).open("wb") as fh:
ftp.client.retrbinary("RETR " + filename, fh.write)
logger.info(f"downloaded {filename}")
gpg = get_gpg()
for filename in available_files:
if "Profit" in filename:
newfilename = f"Pnl_Report_{fund}.csv"
elif "Valuation" in filename:
newfilename = f"Valuation_Report_{fund}.csv"
else:
newfilename = "CDS_Report.xls"
with (reports_dir / filename).open("rb") as fh:
creds = json.load((Path.home() / ".credentials" / "gpg-key.json").open())
dec = gpg.decrypt_file(
fh,
output=(reports_dir / newfilename).as_posix(),
passphrase=creds["password"],
always_trust=True,
)
logger.info(f"{filename}: {dec.status}")
(reports_dir / filename).unlink()
# convert xls to csv
convert_to_csv(reports_dir / "CDS_Report.xls")
insert_todb(engine, workdate, fund)
def insert_todb(engine, workdate: datetime.date, fund="SERCGMAST"):
reports_dir = DAILY_DIR / str(workdate) / "Reports"
if not reports_dir.exists():
reports_dir = (
DAILY_DIR
/ f"{workdate:%Y}"
/ f"{workdate:%Y_%m}"
/ str(workdate)
/ "Reports"
)
for report in ("Valuation", "Pnl", "CDS"):
fun = getattr(load_globeop_report, f"read_{report.lower()}_report")
table = f"{report.lower()}_reports"
report_file = reports_dir / f"{report}_Report_{fund}.csv"
alias_names = {
"SERCGMAST": ("SERCGMAST", "SERCGLTD", "SERCGLLC", "SER_TEST"),
"BOWDST": ("BOWDST",),
}
if not report_file.exists():
continue
df = fun(report_file)
if report == "Valuation":
period_end_date = pd.Timestamp(df.periodenddate[0])
sql_str = (
"DELETE FROM valuation_reports WHERE periodenddate=%s and fund in %s"
)
else:
df["date"] = period_end_date
sql_str = f"DELETE FROM {table} WHERE date=%s and fund in %s"
df["row"] = df.index
with engine.begin() as conn:
conn.execute(
sql_str,
(
period_end_date,
alias_names[fund],
),
)
df.to_sql(table, conn, if_exists="append", index=False)
def upload_bond_marks(engine, workdate: datetime.datetime):
d = workdate.date()
df = pd.read_sql_query(
"SELECT p.identifier, price from list_marks(%s) m "
"RIGHT JOIN list_positions(%s, NULL, False) p "
"ON m.identifier=p.figi; ",
engine,
params=(d, d),
)
df.rename(columns={"identifier": "IDENTIFIER", "price": "Price"}, inplace=True)
fullpath = DAILY_DIR / str(d) / f"securitiesNpv{workdate:%Y%m%d_%H%M%S}.csv"
df.to_csv(fullpath, index=False)
ftp = FtpClient.from_creds("globeop")
ftp.client.cwd("incoming")
ftp.put(fullpath)
sftp = SftpClient.from_creds("hm_globeop")
sftp.client.chdir("incoming/gopricing")
sftp.put(fullpath)
logger.info("upload bond marks done")
def upload_cds_marks(engine, workdate: datetime.datetime):
d = workdate.date()
df = pd.read_sql_query(
"""SELECT cds.dealid AS "DealID", 'CREDIT_SWAP' AS "Instrument Type",
(a.clean_nav+a.accrued) AS "NPV" from list_abscds_marks(%s) a
JOIN cds USING (security_id)""",
engine,
params=(d,),
)
fullpath = DAILY_DIR / str(d) / f"otcNpv{workdate:%Y%m%d}.csv"
df.to_csv(fullpath, index=False)
ftp = FtpClient.from_creds("globeop")
ftp.client.cwd("incoming")
ftp.put(fullpath)
sftp = SftpClient.from_creds("hm_globeop")
sftp.client.chdir("incoming/gopricing")
sftp.put(fullpath)
logger.info("upload cds marks done")
def upload_data(engine, workdate: datetime.datetime):
upload_bond_marks(engine, workdate)
upload_cds_marks(engine, workdate)
def back_fill(start_date="2017-07-20"):
date_rng = pd.date_range(start=start_date, end=pd.Timestamp.today(), freq="B")
for date in date_rng:
insert_todb(date.date())
|