aboutsummaryrefslogtreecommitdiffstats
path: root/python/insert_fx_id.py
blob: 28e4b6ac13d5afe73fe9dc24c72dc0d4f2138d28 (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
import argparse
import datetime
import logging
import pandas as pd
from serenitas.utils.env import DAILY_DIR
from serenitas.analytics.dates import prev_business_day
from serenitas.utils.db import dawn_engine
from serenitas.utils.db import dbconn
from collateral.baml_isda import load_excel as load_excel_baml
from collateral.gs import load_file as load_excel_gs

from report_ops.enums import FundEnum

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

FX_REPORT_COLUMNS = [
    "cpty_id",
    "trade_date",
    "settle_date",
    "buy_currency",
    "buy_amount",
    "sell_currency",
    "sell_amount",
]


def get_tag(fund):
    if fund == "Serenitas":
        return "TSLP"
    elif fund == "BowdSt":
        return "TLLC"
    elif fund == "Selene":
        return "INC"
    else:
        return ""


def read_BAMSNY(fund, workdate):
    REPORTS_DIR = DAILY_DIR / fund / "BoA_reports"
    try:
        fname = next(
            REPORTS_DIR.glob(
                f"301__LMCG_INVESTMEN{get_tag(fund)}_CSA_{workdate:%m%d%Y}_*"
            )
        )
    except StopIteration:
        raise FileNotFoundError
    df = load_excel_baml(fname)
    df = df[df["ProductID"] == "FX_Fwd"]
    df = df[
        [
            "Back Office Number",
            "Trade Date",
            "Maturity Date",
            "Ccy1",
            "Notional 1",
            "Ccy2",
            "Notional 2",
        ]
    ]
    df.columns = FX_REPORT_COLUMNS
    for date_column in (
        "trade_date",
        "settle_date",
    ):
        df[date_column] = pd.to_datetime(df[date_column], infer_datetime_format=True)
    df[["buy_amount", "sell_amount"]] = df[["buy_amount", "sell_amount"]].apply(
        pd.to_numeric, errors="coerce"
    )
    yield from df.itertuples()


def read_MSCSNY(fund, workdate):
    df = pd.read_excel(
        DAILY_DIR
        / fund
        / "MS_reports"
        / f"Trade_Detail_FX_{prev_business_day(workdate):%Y%m%d}.xls"
    )
    df = df[
        [
            "trade_id",
            "trade_date",
            "settlement_date",
            "buy_ccy",
            "amt_buy_ccy",
            "sell_ccy",
            "amt_sell_ccy",
        ]
    ]
    df.columns = FX_REPORT_COLUMNS
    for date_column in (
        "trade_date",
        "settle_date",
    ):
        df[date_column] = pd.to_datetime(
            df[date_column], infer_datetime_format=True
        ).dt.date
    df[["buy_amount", "sell_amount"]] = df[["buy_amount", "sell_amount"]].apply(
        pd.to_numeric, errors="coerce"
    )
    yield from df.itertuples()


def extract_amounts_and_currencies(row):
    cpty_id = row["Trade Id"]
    trade_date = datetime.datetime.strptime(row["Trade Date"], "%d-%b-%Y").date()
    settle_date = datetime.datetime.strptime(row["Maturity Date"], "%d-%b-%Y").date()
    if row["Notional(1)"] < 0:  # From perspective of GSIL
        buy_amount = abs(row["Notional(1)"])
        buy_currency = row["Not1Ccy"]
        sell_amount = abs(row["Notional(2)"])
        sell_currency = row["Not2Ccy"]
    else:
        buy_amount = abs(row["Notional(2)"])
        buy_currency = row["Not2Ccy"]
        sell_amount = abs(row["Notional(1)"])
        sell_currency = row["Not1Ccy"]
    return {
        "cpty_id": cpty_id,
        "trade_date": trade_date,
        "settle_date": settle_date,
        "buy_amount": buy_amount,
        "buy_currency": buy_currency,
        "sell_amount": sell_amount,
        "sell_currency": sell_currency,
    }


def read_GOLDNY(fund, workdate):
    df = load_excel_gs(prev_business_day(workdate), fund, "Trade_Detail")
    df = df[df["Transaction Type"] == "FX"]
    result = df.apply(extract_amounts_and_currencies, axis=1)
    yield from pd.DataFrame.from_records(result).itertuples()


def get_forwards(cob):
    df = pd.read_sql_query("SELECT * FROM forward_trades", con=dawn_engine)
    df[["buy_amount", "sell_amount"]] = df[["buy_amount", "sell_amount"]].apply(
        pd.to_numeric, errors="coerce"
    )
    return df


def process_rows(fund, counterparty, workdate, dawn_trades, conn):
    read_fun = globals()[f"read_{counterparty}"]
    for row in read_fun(fund.name, workdate):
        if row.cpty_id not in dawn_trades.cpty_id.values:
            matching_candidates = dawn_trades.loc[
                (dawn_trades["cp_code"] == counterparty)
                & (dawn_trades["fund"] == fund.value)
            ]
            filters = {
                "trade_date": row.trade_date,
                "settle_date": row.settle_date,
                "buy_currency": row.buy_currency,
                "sell_currency": row.sell_currency,
                "buy_amount": row.buy_amount,
                "sell_amount": row.sell_amount,
            }
            matching_candidates = matching_candidates.loc[
                (matching_candidates[list(filters.keys())] == pd.Series(filters)).all(
                    axis=1
                )
            ]
            if not matching_candidates.empty:
                matched_candidate = matching_candidates.iloc[0, :]
                with conn.cursor() as c:
                    if matched_candidate.fx_type == "SPOT":
                        table = "spots"
                        column = "cpty_id"
                    elif matched_candidate.fx_type in ("NEAR", "FAR"):
                        table = "fx_swaps"
                        column = f"{matched_candidate.fx_type.lower()}_cpty_id"
                    c.execute(
                        f"UPDATE {table} SET {column}=%s WHERE id=%s",
                        (
                            row.cpty_id,
                            matched_candidate.id,
                        ),
                    )
                    logger.info(
                        f"MATCHED {matched_candidate.id}: {table} to {row.cpty_id}"
                    )
                conn.commit()
            else:
                raise ValueError(f"This is an unknown trade from us. {row.cpty_id}")
        else:
            pass  # Will later start verifying that our trades are matched right


def main(workdate):
    conn = dbconn("dawndb")
    dawn_trades = get_forwards(workdate)
    for fund in FundEnum:
        for counterparty in (
            "MSCSNY",
            "BAMSNY",
            "GOLDNY",
        ):
            try:
                process_rows(fund, counterparty, workdate, dawn_trades, conn)
            except FileNotFoundError as e:
                logger.warning(f"FileNotFound for {fund}: {counterparty} on {workdate}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "workdate",
        type=datetime.date.fromisoformat,
        nargs="?",
        default=datetime.date.today(),
        help="Workdate (YYYY-MM-DD)",
    )
    args = parser.parse_args()
    main(args.workdate)