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
|
from db import serenitasdb
import datetime
company_id = 210065
lastdate = datetime.date(2015, 2, 19)
recovery = 15.875
nissuers = 100
#get list of concerned indices
with serenitasdb.cursor() as c:
sqlstr = """SELECT * FROM
(SELECT unnest(index_list) AS basketid FROM cds_issuers WHERE company_id=%s) a
JOIN index_version USING (basketid)
WHERE lastdate='infinity'"""
c.execute(sqlstr, (ticker,))
recordslist = c.fetchall()
insertstr = """INSERT INTO index_version(Index, Series, Version, IndexFactor,
CumulativeLoss, lastdate) Values(%(index)s, %(series)s, %(version)s, %(indexfactor)s,
%(cumulativeloss)s, %(lastdate)s) RETURNING basketid"""
with serenitasdb.cursor() as c:
newids = {}
for r in recordslist:
r['indexfactor'] -= 1
r['version'] += 1
r['cumulativeloss'] += 1-recovery/float(nissuers)
r['lastdate'] = 'infinity'
c.execute(insertstr, r)
newids[r['basketid']] = c.fetchone()[0]
updatestr = "UPDATE index_version SET lastdate=%s WHERE basketid=%s"
with serenitasdb.cursor() as c:
for oldid in newids.keys():
c.execute(updatestr, (lastdate, oldid))
serenitasdb.commit()
with serenitasdb.cursor() as c:
for oldid, newid in newids.items():
c.execute("""update cds_issuers set index_list=index_list||%s where company_id in
(select company_id from cds_issuers where %s=Any(index_list)
and company_id != %s)""", (newid, oldid, company_id))
serenitasdb.commit()
|