aboutsummaryrefslogtreecommitdiffstats
path: root/python/book_bbg.py
blob: 4856ae5da1a2c1f03fc01d2e22589d388cf986b3 (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
from serenitas.utils.remote import SftpClient
import datetime
import csv
from trade_dataclasses import CDSDeal, BondDeal, BbgDeal, _funds, _cdx_cp, _fcms
from decimal import Decimal
from stat import S_ISREG


def get_indic_data(conn, redcode, tenor):
    sql_str = (
        "SELECT maturity, coupon "
        "FROM index_desc "
        "WHERE tenor=%s AND redindexcode=%s "
    )
    with conn.cursor() as c:
        c.execute(sql_str, (redcode, tenor))
        return c.fetchone()


def cdx_booking_process(path, conn):
    reader = csv.DictReader(path)
    for line in reader:
        trade = CDSDeal(
            fund=_funds[line["Account"]],
            folder="*",
            portfolio="UNALLOCATED",
            security_id=line["Red Code"],
            security_desc=line["Security"].removesuffix(" PRC"),
            traded_level=Decimal(line["Price (Dec)"]),
            notional=line["Quantity"],
            fixed_rate=float(line["Coupon"]) * 0.01,
            trade_date=datetime.datetime.strptime(line["Trade Dt"], "%m/%d/%Y").date(),
            maturity=datetime.datetime.strptime(line["Mat Dt"], "%m/%d/%Y").date(),
            currency=line["Curncy"],
            protection="Buyer" if line["Side"] == "B" else "Seller",
            upfront=line["Principal"],
            cp_code=_cdx_cp[line["Brkr"]],
            account_code=_fcms[line["Client FCM"]],
        )
        trade.stage()
    CDSDeal.commit()


def bond_booking_process(file_handle, index):
    for row in csv.DictReader(file_handle):
        line = {"bbg_ticket_id": index, **row}
        trade = BondDeal.from_bbg_line(line)
        trade.stage()
    BondDeal.commit()


def get_bbg_id(name):
    return name.split("_", 1)[1]


if __name__ == "__main__":
    import time

    booker = {"BOND": bond_booking_process, "CDX": cdx_booking_process}
    sftp = SftpClient.from_creds("bbg")
    while True:
        for f in sftp.client.listdir_iter("/"):
            if S_ISREG(f.st_mode):
                if (bbg_id := get_bbg_id(f.filename)) not in BbgDeal._cache:
                    with sftp.client.open(f.filename) as fh:
                        booker[f.filename.split("-", 1)[0]](fh, bbg_id)
                        BbgDeal._cache[bbg_id] = None

        time.sleep(60)