aboutsummaryrefslogtreecommitdiffstats
path: root/sql/dawn.sql
blob: a682cd239eb3bc2a2043c5048e3d20016cc53c6a (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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
-- -*- mode: sql; sql-product: postgres; -*-
CREATE TYPE bond_strat AS ENUM('M_STR_MAV', 'M_STR_MEZZ', 'CSO_TRANCH',
       'M_CLO_BB20', 'M_CLO_AAA', 'M_CLO_BBB', 'M_MTG_IO', 'M_MTG_THRU',
       'M_MTG_GOOD', 'M_MTG_B4PR', 'M_MTG_RW', 'M_MTG_FP', 'M_MTG_LMG',
       'M_MTG_SD', 'M_MTG_PR', 'M_MTG_CRT_SD', 'CRT_LD', 'CRT_LD_JNR',
       'CRT_SD',
       'IGNORE',
       'MTG_REPO',
       'CRT_MI',
       );

CREATE TYPE cds_strat AS ENUM('HEDGE_CSO', 'HEDGE_CLO', 'HEDGE_MAC', 'HEDGE_MBS',
       'SER_IGSNR', 'SER_IGMEZ', 'SER_IGEQY', 'SER_IGINX', 'SER_HYSNR',
       'SER_HYMEZ', 'SER_HYEQY', 'SER_HYINX', 'SER_IGCURVE', 'MBSCDS',
       'IGOPTDEL', 'HYOPTDEL', 'SER_ITRXCURVE',
       'HYEQY', 'HYMEZ', 'HYSNR', 'HYINX',
       'IGEQY', 'IGMEZ', 'IGSNR', 'IGINX',
       'XOEQY', 'XOMEZ', 'XOINX',
       'EUEQY', 'EUMEZ', 'EUSNR', 'EUINX',
       'BSPK', 'XCURVE', 'SER_HYCURVE', 'CASH_BASIS', '*');

CREATE TYPE swaption_strat AS ENUM('IGPAYER', 'IGREC', 'HYPAYER', 'HYREC', 'STEEP', 'DV01');
CREATE TYPE swaption_type AS ENUM('CD_INDEX_OPTION', 'SWAPTION');

CREATE TYPE repo_strat AS ENUM('');

CREATE TYPE spot_strat AS ENUM('M_STR_MAV', 'M_STR_MEZZ', 'SER_ITRXCURVE', 'M_CSH_CASH', 'TCSH');

CREATE TYPE future_strat AS ENUM('M_STR_MAV', 'M_MTG_IO', 'M_STR_MEZZ', 'M_MTG_RW',
       'SER_ITRXCURVE', 'M_CSH_CASH', 'DELTAONE', 'TCSH', 'SOFR');

CREATE TYPE cash_strat AS ENUM('M_CSH_CASH', 'MBSCDSCSH', 'SER_IGCVECSH',
       'SER_ITRXCVCSH', 'CSOCDSCSH', 'IGCDSCSH', 'HYCDSCSH', 'CLOCDSCSH',
       'IGTCDSCSH', 'MACCDSCSH', 'M_STR_MEZZ', 'IRDEVCSH', 'TCSH', 'COCSH',
       'SER_ITRXCURVE', 'XCURVE', 'BSPK', 'SER_HYINX', 'IGOPTDEL', 'IGINX',
       'HYINX', 'HEDGE_CLO', 'CVECSH');

CREATE TYPE asset_class AS ENUM('CSO', 'Subprime', 'CLO', 'Tranches', 'Futures',
       'Cash', 'FX', 'Cleared', 'CRT');

CREATE TYPE action AS ENUM('NEW', 'UPDATE', 'CANCEL');
CREATE TYPE currency AS ENUM('USD', 'CAD', 'EUR', 'JPY', 'GBP');
CREATE TYPE bbg_type AS ENUM('Mtge', 'Corp');
CREATE type day_count AS ENUM('ACT/360', 'ACT/ACT', '30/360', 'ACT/365');
CREATE type bus_day_convention AS ENUM('Modified Following', 'Following',
       'Modified Preceding', 'Preceding', 'Second-Day-After', 'End-of-Month');
CREATE type last_period_convention AS ENUM('Adjusted', 'Unadjusted');
CREATE type index_type AS ENUM('IG', 'HY', 'EU', 'LCDX', 'XO', 'BS', 'HYBB');
CREATE TYPE tenor AS ENUM('6mo', '1yr', '2yr', '3yr', '4yr', '5yr', '7yr', '10yr');

CREATE TYPE swap_type AS ENUM('CD_INDEX', 'CD_INDEX_TRANCHE', 'CD_BASKET_TRANCHE',
       'ABS_CDS', 'CD_INDEX_OPTION', 'SWAPTION', 'CREDIT_DEFAULT_SWAP', 'OIS_SWAP', 'TOTAL_RETURN_SWAP');
CREATE TYPE repo_type AS ENUM('REPO', 'REVERSE REPO');
CREATE TYPE option_type AS ENUM('PAYER', 'RECEIVER');

CREATE TYPE isda AS ENUM('ISDA2014', 'ISDA2003Cred');
CREATE TYPE protection AS ENUM('Buyer', 'Seller');

CREATE TYPE call_notice AS ENUM('24H', '48H', '3D', '4D', '5D', '6D',
'1W', '8D', '9D', '10D', '2W', '1M', '2M');

CREATE TYPE settlement_type AS ENUM('Delivery', 'Cash');

CREATE TYPE beta_type AS ENUM('IG', 'CRT', 'EU', 'SUBPRIME', 'XO');

CREATE TYPE account_type AS ENUM('Cash', 'Brokerage', 'Fcm', 'Future');

CREATE TYPE equity_option_type AS ENUM ('CALL', 'PUT');

CREATE TYPE deal_type AS ENUM ('CreditSwaption', 'CDS', 'TRS', 'CAP', 'IRS', "EquityOption", "IRSwaption");

CREATE TABLE accounts(
       code varchar(5) PRIMARY KEY,
       name text,
       custodian text NOT NULL,
       cash_account text NOT NULL,
       counterparty varchar(12) REFERENCES counterparties(code),
       fund fund NOT NULL,
       account_type account_type NOT NULL,
       active boolean NOT NULL);

CREATE TABLE accounts2 (
	id int4 NOT NULL GENERATED ALWAYS AS IDENTITY,
	"name" text NULL,
	custodian text NOT NULL,
	cash_account text NOT NULL,
	"fund" fund NOT NULL,
	"account_type" account_type NOT NULL,
	active bool NOT NULL,
    cp_code varchar(10),
	CONSTRAINT accounts2_cash_account_key UNIQUE (cash_account),
	CONSTRAINT accounts2_pkey PRIMARY KEY (id)
);

CREATE TABLE counterparties(code varchar(12) PRIMARY KEY,
       name text,
       city text,
       state varchar(2),
       location text,
       dtc_number integer,
       sales_contact text,
       sales_email text,
       sales_phone text,
       valuation_contact1 text,
       valuation_email1 text,
       valuation_contact2 text,
       valuation_email2 text,
       valuation_contact3 text,
       valuation_email3 text,
       valuation_contact4 text,
       valuation_email4 text,
       notes text,
       instructions text,
       cash_counterparty boolean NOT NULL DEFAULT true,
       cds_counterparty boolean NOT NULL DEFAULT false),
       ctm_code text;

CREATE INDEX ON counterparties(name);

-- deprecated
CREATE TABLE bond_old(id serial primary key,
       dealid varchar(28) UNIQUE,
       fund fund NOT NULL DEFAULT 'SERCGMAST';
       lastupdate timestamp DEFAULT now(),
       action action NOT NULL,
       folder bond_strat NOT NULL,
       custodian varchar(12) NOT NULL,
       cashaccount varchar(12) NOT NULL,
       cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
       trade_date date NOT NULL,
       settle_date date NOT NULL,
       cusip varchar(9),
       isin varchar(12),
       identifier varchar(12),
       description varchar(32) NOT NULL,
       buysell bool NOT NULL,
       faceamount float NOT NULL,
       price float NOT NULL,
       accrued float,
       asset_class asset_class,
       ticket text,
       principal_payment float,
       accrued_payment float,
       CONSTRAINT bonds2_check CHECK (cusip IS NOT NULL OR isin IS NOT NULL));

CREATE TABLE bonds(id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
       dealid varchar(28) GENERATED ALWAYS AS ('SC_'||CASE WHEN asset_class ='Subprime' THEN 'SUB'
                                                           WHEN asset_class='CLO' THEN 'CLO'
                                                           WHEN asset_class='CSO' THEN 'CSO'
                                                           WHEN asset_class='CRT' THEN 'CRT'
                                                      END
                                                    ||id::text) STORED,
       folder bond_strat,
       portfolio portfolio NOT NULL,
       cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
       trade_date date NOT NULL,
       settle_date date NOT NULL,
       cusip varchar(9),
       isin varchar(12),
       identifier varchar(12),
       description varchar(32) NOT NULL,
       buysell bool NOT NULL,
       faceamount float NOT NULL,
       price numeric NOT NULL,
       accrued numeric,
       asset_class asset_class NOT NULL,
       ticket text,
       principal_payment float,
       accrued_payment float,
       current_face float,
       allocated boolean NOT NULL DEFAULT false,
       stale bool NOT NULL DEFAULT true,
       emailed bool NULL DEFAULT false,
       bbg_ticket_id text NULL REFERENCES bond_tickets(bbg_ticket_id) ON DELETE SET NULL,
      CONSTRAINT bonds_check CHECK (((cusip IS NOT NULL) OR (isin IS NOT NULL)));


CREATE OR REPLACE FUNCTION notify_id()
RETURNS TRIGGER
AS $$
BEGIN
PERFORM pg_notify(TG_TABLE_NAME, NEW.id::text);
NEW.stale = true;
RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE TABLE portfolio_folder_mapping (
	folder "strategy_dirty" NOT NULL,
	"portfolio" "portfolio" NOT NULL,
	active bool NOT NULL DEFAULT true,
	clean_folder text NULL,
	CONSTRAINT portfolio_folder_mapping_pkey PRIMARY KEY (folder)
);


CREATE OR REPLACE TRIGGER portf BEFORE
INSERT OR UPDATE OF
    folder
ON
    bonds
FOR EACH ROW
EXECUTE PROCEDURE update_portf2();


CREATE OR REPLACE FUNCTION update_portf2()
RETURNS TRIGGER
AS $$
BEGIN
SELECT pfm.portfolio FROM portfolio_folder_mapping pfm INTO NEW.portfolio where folder::text=NEW.folder::text;
RETURN NEW;
END
$$ LANGUAGE plpgsql;


CREATE OR REPLACE TRIGGER bond_notify BEFORE
INSERT OR UPDATE OF
    identifier,
    cusip,
    isin,
	faceamount,
    price,
    trade_date,
	settle_date,
    accrued,
    asset_class
ON
	bonds
FOR EACH ROW
WHEN (current_setting('application_name') != 'update_loop')
EXECUTE PROCEDURE notify_id();


CREATE OR REPLACE FUNCTION set_identifier()
RETURNS trigger
AS $$
BEGIN
NEW.identifier =  COALESCE(NEW.identifier, NEW.cusip, NEW.isin);
RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_identifier BEFORE
INSERT OR UPDATE OF
    identifier,
    cusip,
    isin
ON
	bonds
FOR EACH ROW EXECUTE PROCEDURE set_identifier();

CREATE TABLE bond_allocation(
       id integer generated always as identity primary key,
       tradeid integer not null references bonds ON DELETE CASCADE,
       notional float not null,
       code text not null references accounts,
       submitted boolean default False,
       UNIQUE (tradeid, code));

CREATE TYPE status AS ENUM('Pending', 'Processed', 'Submitted', 'Acknowledged', 'Failed',);

CREATE TABLE bond_submission(
       id integer generated always as identity primary key,
       allocation_id integer not null references allocation on delete cascade,
       "action" action not null,
       submit_date = timestamptz DEFAULT now(),
       status status NOT NULL DEFAULT 'Pending'
);


CREATE TABLE cds(id serial primary key,
       dealid varchar(28) NOT NULL,
       fund fund NOT NULL DEFAULT 'SERCGMAST',
       lastupdate timestamptz DEFAULT now(),
       action action NOT NULL DEFAULT 'NEW',
       portfolio portfolio NOT NULL,
       folder cds_strat NOT NULL,
       custodian varchar(12) NOT NULL,
       cashaccount varchar(12) NOT NULL,
       cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
       trade_date date NOT NULL,
       effective_date date NOT  NULL,
       maturity date NOT NULL,
       currency currency NOT NULL,
       payment_rolldate bus_day_convention NOT NULL DEFAULT 'Following',
       notional float NOT NULL,
       fixed_rate float NOT NULL,
       day_count day_count NOT NULL DEFAULT 'ACT/360',
       frequency smallint NOT NULL DEFAULT 4,
       protection protection NOT NULL,
       security_id varchar(12) NOT NULL,
       security_desc varchar(32) NOT NULL,
       upfront float NOT NULL,
       upfront_settle_date date NOT NULL,
       swap_type swap_type NOT NULL,
       orig_attach smallint,
       orig_detach smallint,
       attach float,
       detach float,
       clearing_facility varchar(12) DEFAULT NULL,
       isda_definition isda,
       initial_margin_percentage float DEFAULT NULL,
       index_ref float DEFAULT NULL,
       corr_attach float DEFAULT NULL,
       corr_detach float DEFAULT NULL,
       account_code varchar(5) NOT NULL REFERENCES accounts(code),
       cpty_id text,
       globeop_id int,
       stale bool default true,
       traded_level numeric(9, 5) NULL,
       exercised_from text REFERENCES swaptions(dealid),
       delta_id integer REFERENCES cds(id),
       delta_alloc float,
       CONSTRAINT tranche_check CHECK ((
       swap_type IN ('CD_INDEX_TRANCHE',  'BESPOKE') AND
       (orig_attach IS NOT NULL AND orig_detach IS NOT NULL AND clearing_facility IS NULL))
       OR (swap_type='CD_INDEX' AND orig_attach IS NULL AND orig_detach IS NULL AND clearing_facility='ICE-CREDIT')
       OR (swap_type='ABS_CDS' AND orig_attach IS NULL AND orig_detach IS NULL AND clearing_faciliy IS NULL))
       );

ALTER TABLE cds OWNER TO dawn_user;

CREATE TRIGGER cds_dealid BEFORE INSERT ON cds
FOR EACH ROW EXECUTE PROCEDURE auto_dealid();


CREATE TRIGGER cds_notify AFTER
INSERT
	OR
UPDATE
	OF security_id,
	maturity,
	trade_date,
	upfront_settle_date,
	traded_level,
	notional,
	protection ON
	cds FOR EACH ROW WHEN (current_setting('application_name') != 'autobooker') EXECUTE FUNCTION notify_id();

CREATE OR REPLACE FUNCTION cds_enrich()
RETURNS TRIGGER
AS $$
from serenitas.analytics.api import CreditIndex
trade = TD["new"]
if trade["swap_type"] == "BESPOKE":
    return
if TD["event"] == "INSERT" and all([trade["upfront"], trade["traded_level"]]):
    return
index = CreditIndex(
        redcode=trade["security_id"],
        maturity=trade["maturity"],
        notional=trade["notional"],
        value_date=trade["trade_date"],
)
index.direction = trade["protection"]
if trade["traded_level"]:
    if trade["swap_type"] == "CD_INDEX":
        index.ref = float(trade["traded_level"])
        upfront = -index.pv
    else:
        tranche_factor = (trade["detach"] - trade["attach"]) / (
            trade["orig_detach"] - trade["orig_attach"]
        )
        accrued = index._accrued * trade["fixed_rate"]
        match index.index_type:
            case "HY":
                dirty_price = float(trade["traded_level"]) + accrued
                upfront = (
                    -(100 - dirty_price)
                    * index.notional
                    * tranche_factor
                    * 0.01
                )
            case "EU" | "XO" if trade["orig_attach"] in (6, 12, 35):
                if trade["orig_attach"] == 6:
                    index.recovery = 0.0
                index.spread = float(trade["traded_level"])
                upfront = -index._pv * trade["notional"] * tranche_factor
            case _:
                dirty_protection = float(trade["traded_level"]) - accrued
                upfront = (
                    -dirty_protection
                    * index.notional
                    * tranche_factor
                    * 0.01
                )
        trade["upfront"] = upfront
else:
    index.pv = trade["upfront"]
    trade["traded_level"] = index.ref
return "MODIFY"
$$ LANGUAGE plpython3u;


CREATE OR REPLACE TRIGGER upfront_setter AFTER
INSERT
	OR
UPDATE OF
    security_id,
	maturity,
	trade_date,
	upfront_settle_date,
	traded_level,
	notional,
	protection
ON
	cds FOR EACH ROW WHEN (current_setting('application_name') != 'autobooker') EXECUTE FUNCTION cds_enrich();


CREATE OR REPLACE function update_attach()
RETURNS TRIGGER AS $$
DECLARE
  factor float;
  cum_loss float;
BEGIN
IF NEW.orig_attach IS NULL AND NEW.orig_detach IS NULL THEN
RETURN NEW;
ELSE
SELECT indexfactor, cumulativeloss INTO factor, cum_loss
  FROM index_version WHERE redindexcode=NEW.security_id;
NEW.attach = factor*LEAST(GREATEST((NEW.orig_attach - cum_loss)/factor, 0), 1);
NEW.detach = factor*LEAST(GREATEST((NEW.orig_detach - cum_loss)/factor, 0), 1);
RETURN NEW;
END IF;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER cds_attach BEFORE
INSERT OR UPDATE OF orig_attach, orig_detach, security_id
ON cds
FOR EACH ROW EXECUTE PROCEDURE update_attach();

CREATE TABLE repos (
	id int4 GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
	dealid varchar(28) NULL GENERATED ALWAYS AS ((('SCREPO'::text || id::text))) STORED,
	"fund" fund NOT NULL,
	lastupdate timestamptz NULL DEFAULT now(),
	"action" action NULL,
	folder bond_strat NOT NULL,
	cp_code varchar(12) NOT NULL REFERENCES counterparties(code),
	trade_date date NOT NULL,
	settle_date date NOT NULL,
	cusip varchar(9) NULL,
	isin varchar(12) NULL,
	identifier varchar(12) NULL,
	description varchar(32) NOT NULL,
	transaction_indicator repo_type NULL,
	faceamount float8 NOT NULL,
	price float8 NOT NULL,
	"currency" currency NOT NULL DEFAULT 'USD'::currency,
	expiration_date date NULL,
	weighted_amount float8 NULL,
	haircut float8 NULL,
	repo_rate float8 NOT NULL,
	"call_notice" call_notice NULL,
	day_count day_count NULL,
	ticket varchar NULL,
	open_repo bool NULL,
    cash_account text REFERENCES accounts2(cash_account),
    CHECK ((haircut IS NOT NULL AND weighted_amount IS NULL) OR
            (haircut IS NULL AND weighted_amount IS NOT NULL)),
    CHECK (cusip IS NOT NULL OR isin IS NOT NULL)
);


ALTER TABLE repo OWNER TO dawn_user;

CREATE TRIGGER cash_account BEFORE
INSERT OR UPDATE OF
   fund,
   cp_code
ON
    repos
FOR EACH ROW
EXECUTE PROCEDURE update_account('Bonds');


CREATE TABLE swaptions(id serial PRIMARY KEY,
       dealid varchar(28) NOT NULL UNIQUE,
       fund fund NOT NULL DEFAULT 'SERCGMAST',
       lastupdate timestamptz DEFAULT now(),
       action action NOT NULL,
       portfolio portfolio NOT NULL,
       folder swaption_strat NOT NULL,
       cash_account text NOT NULL REFERENCES accounts2(cash_account),
       cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
       swap_type swaption_type NOT NULL,
       trade_date date NOT NULL,
       settle_date date NOT NULL,
       buysell bool NOT NULL,
       notional float NOT NULL,
       option_type option_type NOT NULL,
       strike float NOT NULL,
       price float NOT NULL,
       expiration_date date NOT NULL,
       initial_margin_percentage float,
       security_id varchar(12) NOT NULL,
       security_desc varchar(32),
       maturity date NOT NULL,
       currency currency NOT NULL,
       settlement_type settlement_type NOT NULL,
       fixed_rate float,
       termination_date date,
       termination_fee float,
       termination_amount float,
       termination_cp varchar(12) REFERENCES counterparties(code) ON UPDATE CASCADE,
       cpty_id text,
       globeop_id int,
       full_globeop_id text GENERATED ALWAYS AS ('SWO'||lpad(cast(globeop_id as text), 6, '0')|| 'K00SCLMA') STORED,
       delta_id int REFERENCES cds(id),
       delta_alloc float
);

CREATE TRIGGER swaptions_dealid BEFORE INSERT ON swaptions
FOR EACH ROW EXECUTE PROCEDURE auto_dealid();

CREATE TABLE account_counterparty (
	account_id int4 NULL,
	cp_code varchar(12) NULL,
	"trade_type" text NOT NULL,
	id int4 NOT NULL GENERATED ALWAYS AS IDENTITY,
	"name" text NULL,
	CONSTRAINT account_counterparty_account_id_cp_code_trade_type_key UNIQUE (account_id, cp_code, trade_type),
	CONSTRAINT account_counterparty_pkey PRIMARY KEY (id),
	CONSTRAINT account_counterparty_account_id_fkey FOREIGN KEY (account_id) REFERENCES accounts2(id),
	CONSTRAINT account_counterparty_cp_code_fkey FOREIGN KEY (cp_code) REFERENCES counterparties(code) ON UPDATE CASCADE
);


CREATE OR REPLACE FUNCTION update_account()
RETURNS TRIGGER
AS $$
BEGIN
SELECT cash_account INTO STRICT NEW.cash_account FROM accounts2 LEFT JOIN account_counterparty ON accounts2.id=account_id WHERE trade_type=TG_ARGV[0] AND fund=NEW.fund AND account_counterparty.cp_code=NEW.cp_code AND active;
RETURN NEW;
END
$$ LANGUAGE plpgsql;


CREATE TRIGGER cash_account BEFORE
INSERT OR UPDATE OF
   fund,
   cp_code
ON
    swaptions
FOR EACH ROW
EXECUTE PROCEDURE update_account('ISDA');

CREATE TABLE capfloors (
	id serial PRIMARY KEY,
	fund fund NOT NULL DEFAULT 'SERCGMAST',
	dealid varchar(28) UNIQUE,
	lastupdate timestamp NULL DEFAULT now(),
	"action" action NOT NULL,
	folder swaption_strat NOT NULL,
	custodian varchar(12) NOT NULL,
	cashaccount varchar(12) NOT NULL,
	cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
    "comments" varchar(100),
	floating_rate_index varchar(12) NOT NULL,
	floating_rate_index_desc varchar(32),
	buysell bool NOT NULL,
	cap_or_floor cap_or_floor NOT NULL,
	strike float8 NOT NULL,
	value_date date NOT NULL,
	expiration_date date NOT NULL,
	premium_percent float8 NOT NULL,
	pricing_type pricing_type NOT NULL,
	payment_frequency frequency NOT NULL,
	fixing_frequency frequency NOT NULL,
	day_count_counvention day_count NULL,
	bdc_convention bus_day_convention NULL,
	payment_mode payment_mode NOT NULL,
	payment_at_beginning_or_end begin_or_end NOT NULL,
	initial_margin_percentage float8 NULL,
	initial_margin_currency currency NULL,
	amount float8 NOT NULL,
	trade_date date NOT NULL,
	swap_type capfloor_type NOT NULL,
	reset_lag int4,
	trade_confirm varchar,
	cpty_id text,
	globeop_id text
)

CREATE TRIGGER dealid BEFORE INSERT ON capfloors
FOR EACH ROW EXECUTE PROCEDURE auto_dealid();

CREATE TABLE futures (
	id serial NOT NULL,
	dealid varchar(28),
	lastupdate timestamp NULL DEFAULT now(),
	"action" action NOT NULL,
    portfolio portfolio NOT NULL,
	folder future_strat NOT NULL,
	cash_account text NOT NULL REFERENCES accounts2(cash_account),
	trade_date date NOT NULL,
	settle_date date NOT NULL,
	buysell bool NOT NULL,
	bbg_ticker varchar(32) NOT NULL,
	quantity float8 NOT NULL,
	price float8 NOT NULL,
	commission float8 NULL,
	swap_type future_type NOT NULL,
	security_desc varchar(32) NOT NULL,
	maturity date NOT NULL,
	currency currency NOT NULL,
	exchange varchar(3) NOT NULL,
	fund fund NOT NULL DEFAULT 'SERCGMAST'::fund,
	CONSTRAINT futures_dealid_key UNIQUE (dealid),
	CONSTRAINT futures_pkey PRIMARY KEY (id),
);

ALTER TABLE futures OWNER TO dawn_user;

CREATE TRIGGER dealid BEFORE
INSERT ON futures
FOR EACH ROW
EXECUTE PROCEDURE auto_dealid();

CREATE TRIGGER portf BEFORE
INSERT OR UPDATE OF
    folder
ON
    futures
FOR EACH ROW
EXECUTE PROCEDURE update_portf2();

CREATE TABLE wires (
    id serial NOT NULL,
    fund fund NOT NULL,
    dealid varchar(28) NOT NULL,
    lastupdate timestamp NULL DEFAULT now(),
    "action" action NOT NULL,
    folder cash_strat NOT NULL,
    portfolio portfolio NOT NULL,
    cash_account text NOT NULL REFERENCES accounts2(cash_account),
    amount float8 NOT NULL,
    currency currency NOT NULL,
    trade_date date NOT NULL,
    author author default 'manual',
    CONSTRAINT wires_pkey PRIMARY KEY (id),
);

ALTER table wires OWNER TO dawn_user;

CREATE TRIGGER dealid BEFORE
INSERT ON wires
FOR EACH ROW
EXECUTE PROCEDURE auto_dealid();

CREATE TRIGGER portf2 BEFORE
INSERT OR UPDATE OF
    folder
ON
    wires
FOR EACH ROW
EXECUTE PROCEDURE update_portf2();



CREATE TABLE spots (
	id serial NOT NULL,
	fund fund NOT NULL DEFAULT 'SERCGMAST'::fund,
	dealid varchar(28) NOT NULL,
	lastupdate timestamp NULL DEFAULT now(),
	"action" action NOT NULL,
    portfolio portfolio NOT NULL,
	folder spot_strat NOT NULL,
	cash_account text NOT NULL REFERENCES accounts2(cash_account),
    cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
	trade_date date NOT NULL,
	settle_date date NOT NULL,
	spot_rate float8 NOT NULL,
	buy_currency currency NOT NULL,
	buy_amount float8 NOT NULL,
	sell_currency currency NOT NULL,
	sell_amount float8 NOT NULL,
	commission_currency currency NULL,
	commission float8 NULL,
    initial_margin_percentage float8,
    cpty_id text,
    globeop_id text,
    bbg_ticket_id text UNIQUE REFERENCES fx_tickets(bbg_ticket_id),
	CONSTRAINT spots_pkey PRIMARY KEY (id),
);

CREATE TRIGGER fx_portf BEFORE
INSERT OR UPDATE OF
    folder
ON
    spots
FOR EACH ROW
EXECUTE PROCEDURE update_portf2();

CREATE TRIGGER dealid BEFORE
INSERT ON
spots
FOR EACH ROW
EXECUTE PROCEDURE auto_dealid();

CREATE TABLE fx_swaps (
	id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
	dealid varchar(28) NOT NULL GENERATED ALWAYS AS ((('FXSWAP_'::text || id::text))) STORED,
	"fund" fund NOT NULL DEFAULT 'SERCGMAST'::fund,
	lastupdate timestamp NULL DEFAULT now(),
	"portfolio" portfolio NOT NULL,
	folder spot_strat NOT NULL,
    cash_account text NOT NULL REFERENCES accounts2(cash_account),
	cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
	trade_date date NOT NULL,
	near_rate float8 NOT NULL,
	near_settle_date date NOT NULL,
	near_buy_currency currency NOT NULL,
	near_buy_amount float8 NOT NULL,
	near_sell_currency currency NOT NULL,
	near_sell_amount float8 NOT NULL,
	far_rate float8 NOT NULL,
	far_settle_date date NOT NULL,
	far_buy_currency currency NULL,
	far_buy_amount float8 NOT NULL,
	far_sell_currency currency NULL,
	far_sell_amount float8 NOT NULL,
	near_cpty_id text NULL,
	far_cpty_id text NULL,
    bbg_ticket_id text UNIQUE REFERENCES fx_tickets(bbg_ticket_id),
    action action not null,
);

CREATE OR REPLACE VIEW forwards AS
     SELECT  UNNEST(ARRAY[dealid || '_near', dealid || '_far']) AS dealid, trade_date, unnest(ARRAY[near_settle_date, far_settle_date]) AS settle_date,
            fund,
            portfolio,
            folder,
            cp_code,
            UNNEST(ARRAY[near_buy_currency, far_buy_currency]) AS buy_currency,
            UNNEST(ARRAY[near_sell_currency, far_sell_currency]) AS sell_currency,
            UNNEST(ARRAY[near_buy_amount, far_buy_amount]) AS buy_amount,
            UNNEST(ARRAY[near_sell_amount, far_sell_amount]) AS sell_amount,
            UNNEST(ARRAY[near_cpty_id, far_cpty_id]) AS cpty_id
     FROM fx_swaps
   UNION
     SELECT  dealid, trade_date, settle_date, fund, portfolio, folder, cp_code, buy_currency, sell_currency, buy_amount, sell_amount, cpty_id FROM spots;

CREATE TABLE terminations (
    id int GENERATED BY default as identity primary KEY,
    dealid varchar(28) NOT NULL,
    termination_date date NOT NULL,
    termination_cp varchar(12) REFERENCES counterparties(code),
    termination_amount float8,
    termination_fee float8 NOT NULL,
    partial_termination bool NOT null default false,
    new_gtid int,
    fee_payment_date date NOT NULL,
    traded_level numeric(9, 5) NULL,
    "deal_type" "deal_type" NOT NULL,
    "currency" "currency" NOT NULL,
    delta_id int4 NULL,
    delta_alloc float8 NULL,
    cpty_id text null
);



CREATE OR REPLACE FUNCTION auto_dealid()
    RETURNS TRIGGER AS $$
    DECLARE stub text;
    BEGIN
      IF NEW.dealid is NULL THEN
         IF (TG_TABLE_NAME = 'bonds') THEN
            NEW.dealid := 'SC_' || upper(left(NEW.asset_class::text,3)) || NEW.id;
         ELSE
            CASE TG_TABLE_NAME
            WHEN 'cds' THEN
               stub := 'SCCDS';
            WHEN 'swaptions' THEN
               stub := 'SWPTN';
            WHEN 'futures' THEN
               stub := 'SCFUT';
            WHEN 'wires' THEN
               stub := 'SCCSH';
            WHEN 'capfloors' THEN
               stub := 'CAP';
            WHEN 'spots' THEN
               stub := 'SCFX';
            END CASE;
            NEW.dealid := stub || NEW.id;
         END IF;
      END IF;
      RETURN NEW;
    END;
$$ language plpgsql;

ALTER TABLE swaptions OWNER TO dawn_user;

CREATE TABLE securities(identifier varchar(12) PRIMARY KEY,
       cusip varchar(9),
       isin varchar(12),
       description varchar(32),
       face_amount float,
       maturity date,
       floater boolean,
       spread float,
       coupon float,
       frequency smallint,
       day_count day_count,
       first_coupon_date date,
       pay_delay smallint,
       currency currency default 'USD',
       bbg_type bbg_type default 'Mtge',
       asset_class asset_class,
       paid_down date default 'Infinity',
       start_accrued_date date,
       issuer text,
       reset_index text,
       coupon_type text,
       payment_day integer,
       issue_date date,
       figi text);

ALTER TABLE securities OWNER TO dawn_user;

CREATE TABLE marks(
       date date NOT NULL,
       price float NOT NULL,
       identifier varchar(12) NOT NULL REFERENCES securities(figi) ON DELETE CASCADE ON UPDATE CASCADE,
       id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
       UNIQUE (date, identifier)
);

CREATE UNIQUE INDEX ON marks(date, identifier);

CREATE TABLE external_marks_deriv(date date NOT NULL,
       identifier text NOT NULL,
       local_nav float, --trade ccy nav
       base_nav float, --USD nav
       cpty varchar(4),
       ia float, -- ia in USD
       PRIMARY KEY(identifier, date));

CREATE OR REPLACE VIEW id_mappings AS
       SELECT trade_date, dealid, cpty_id, notional*price/100 as nav,
       'SWAPTION'::trade_type as trade_type from swaptions
       UNION SELECT trade_date, dealid, cds.cpty_id, upfront as nav,
       'TRANCHE' FROM cds WHERE attach IS NOT NULL ORDER BY trade_date;

CREATE TABLE cashflow_history(
       identifier varchar(12) NOT NULL REFERENCES securities(figi) ON UPDATE CASCADE,
       date date NOT NULL,
       principal_bal float,
       principal float,
       interest float,
       coupon float,
       factor float,
       PRIMARY KEY (identifier, date));

CREATE TABLE risk_numbers(
       identifier varchar(12) REFERENCES securities,
       date date,
       delta float,
       index_delta index_type,
       duration float,
       wal float,
       undiscounted_price float,
       model_price float,
       PRIMARY KEY (identifier, date));

CREATE TABLE fx(date date PRIMARY KEY,
       eurusd float,
       cadusd float);

CREATE TABLE external_marks(
       identifier varchar(12) REFERENCES securities ON UPDATE CASCADE,
       date date,
       mark float,
       source text,
       PRIMARY KEY (identifier, date, source));

CREATE TABLE mark_source_mapping(
       globeop text,
       final text,
       PRIMARY KEY (globeop));

CREATE TABLE subscription_and_fee(
       date date,
       fund fund,
       subscription float,
       redemption float,
       incentive_fee float,
       management_fee float,
       PRIMARY KEY (fund, date));

CREATE TYPE LS AS ENUM('L', 'S');

CREATE TABLE bbh_val(
       accounting_date date NOT NULL,
       row integer NOT NULL,
       custody_head_account_number float,
       security_id text,
       security_description text,
       asset_currency currency,
       original_face float,
       base_price float,
       local_unit_cost float,
       base_unit_cost float,
       local_market_value float,
       base_market_value float,
       security_id_type text,
       sub_security_type_code text,
       source text,
       investment_type_code text,
       investment_type_description text,
       security_long_description  text,
       security_type_code  text,
       total_current_assets float,
       total_current_liabilities float,
       total_net_assets float,
       interest_rate float,
       quantity float,
       quantity_scale float,
       long_short_indicator LS,
       fx_rate float,
       maturity_date date,
       PRIMARY KEY (accounting_date, row));

CREATE TABLE bbh_pnl(
       accounting_date date NOT NULL,
       row integer NOT NULL,
       security_id text,
       custody_head_account_number int,
       issue_name text,
       local_currency currency,
       base_market_value float,
       base_change_income float,
       base_change_fx_realized_gain_loss float,
       base_change_fx_unrealized_gain_loss float,
       base_change_unrealized_gain_loss float,
       base_change_realized_gain_loss float,
       base_change_miscellaneous_income float,
       base_change_expense float,
       base_change_total float,
       sub_security_type_code text,
       source text,
       PRIMARY KEY (accounting_date, row));


CREATE TYPE bony_asset_type AS ENUM(
'CASH & CASH EQUIVALENTS', 'FIXED INCOME SECURITIES', 'FUTURES CONTRACTS', 'NON CUSIP RELATED INCOME');

CREATE TABLE bowdst_val(
       row integer not null,
       as_of_date                  date not null,
       source_account_number       integer REFERENCES bowdst_accounts(account_number),
       mellon_security_id          text,
       asset_type                  bony_asset_type,
       security_description_1      text,
       security_description_2      text,
       maturity_date               date,
       coupon_rate                 float,
       current_notional            float,
       local_price                 float,
       local_currency_code         currency,
       base_price                  float,
       local_cost                  float,
       base_cost                   float,
       local_market_value          float,
       base_market_value           float,
       local_unrealized_pnl        float,
       base_unrealized_pnl         float,
       local_notional_cost         float,
       base_notional_cost          float,
       local_notional_value        float,
       base_notional_value         float,
       gen_ledger_acct             integer,
       report_run_date             date,
       link_ref                    text,
       counterparty_name           text,
       exchange_rate               float,
       original_strike_price       float,
       current_strike_price        float,
       cusip                       text,
       ticker                      text,
       isin                        text,
       PRIMARY KEY (as_of_date, row)
);

CREATE TABLE bowdst_accounts(
       account_number integer NOT NULL PRIMARY KEY,
       account_name text NOT NULL
);

CREATE TABLE bowdst_pnl(
       row integer not null,
      begin_date	date not null,
      end_date	date not null,
      derivative_type	text,
      security_id	text,
      security_description_1	text,
      security_description_2	text,
      local_currency	currency,
      coupon_rate	float,
      asset_type_name	text,
      asset_type_category	bony_asset_type,
      unrealized_currency	float,
      unrealized_investment	float,
      total_unrealized	float,
      ending_shares_par	float,
      opening_receivables	float,
      closing_receivables	float,
      income	float,
      journal_entry_income	float,
      accretion_amortization	float,
      journal_entry_accretion_amortization	float,
      realized_gain_loss	float,
      journal_entry_realized_gl	float,
      realized_loss_impaired_securities	float,
      net_investment_income	float,
      cusip	text,
      ticker	text,
      isin	text,
      link_ref	text,
      realized_investment	float,
      realized_currency	float,
      realized_settled	float,
      realized_traded	float,
       PRIMARY KEY (begin_date, end_date, row)
);

CREATE TABLE crt_model_versions(
  begin_date date,
  model_version text
);

CREATE OR REPLACE function list_marks(p_date date)
RETURNS TABLE(p_date date, identifier varchar(12), price float) AS $$
BEGIN
  RETURN SELECT DISTINCT ON (identifier) marks.date, marks.identifier, marks.price FROM marks
WHERE date<= p_date ORDER BY identifier, marks.date DESC;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_marks_var(p_date date, VARIADIC p_identifier varchar(12)[])
RETURNS TABLE(identifier varchar(12), price float) AS $$
BEGIN
  RETURN QUERY SELECT a.identifier, b.price FROM (SELECT unnest(p_identifier) AS identifier) a
  LEFT JOIN
(SELECT DISTINCT ON (identifier) date, marks.identifier, marks.price FROM marks
WHERE date<= p_date ORDER BY identifier, date DESC) b USING (identifier);
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_risk_numbers(p_date date, assetclass asset_class,
       include_unsettled boolean DEFAULT False, p_fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(identifier varchar(12), description varchar(32), mark float,
              delta float, index_delta index_type, duration float, wal float,
              undiscounted_price float, model_price float) AS $$
BEGIN
  RETURN QUERY SELECT a.identifier, a.description, b.price, c.delta, c.index_delta,
  c.duration, c.wal, c.undiscounted_price, c.model_price
  FROM list_positions(p_date, assetclass, include_unsettled, p_fund) a
  LEFT JOIN (SELECT DISTINCT ON (identifier) date, marks.identifier, marks.price FROM marks
WHERE date <= p_date ORDER BY identifier, date DESC) b ON a.figi=b.identifier
  LEFT JOIN (SELECT DISTINCT ON (identifier) * FROM risk_numbers
  WHERE date <=p_date ORDER BY identifier, date DESC) c USING ON a.figi=c.identifier;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE VIEW bond_trades
AS SELECT bonds.dealid,
    bond_allocation.tradeid,
    bond_allocation.id,
    bonds.identifier,
    bonds.description,
    bonds.asset_class,
    bonds.trade_date,
    bonds.settle_date,
    bonds.buysell,
    bonds.price,
    bonds.accrued,
    bonds.folder,
    bonds.portfolio,
    ((bond_allocation.notional / sum(bond_allocation.notional) OVER w) * bonds.principal_payment)::numeric(11, 2) AS principal_payment,
    ((bond_allocation.notional / sum(bond_allocation.notional) OVER w) * bonds.accrued_payment)::numeric(11, 2) AS accrued_payment,
    ((bond_allocation.notional / sum(bond_allocation.notional) OVER w) * (bonds.principal_payment + bonds.accrued_payment))::numeric(11, 2) AS net_amount,
    bonds.current_face * bond_allocation.notional / sum(bond_allocation.notional) OVER w AS current_face,
    bond_allocation.notional AS faceamount,
    accounts.fund,
    counterparties.code AS cp_code,
    counterparties.name AS counterparty,
    counterparties.dtc_number,
    bond_allocation.code as account
   FROM bonds
     LEFT JOIN bond_allocation ON bonds.id = bond_allocation.tradeid
     LEFT JOIN accounts USING (code)
     LEFT JOIN counterparties ON bonds.cp_code = counterparties.code
  WINDOW w AS (PARTITION BY bond_allocation.tradeid);


CREATE OR REPLACE function list_positions(p_date date,
       p_class asset_class DEFAULT NULL,
       include_unsettled boolean DEFAULT True,
       p_fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(identifier varchar(12), description varchar(32), notional float, strategy strategy,
              curr_cpn float, start_accrued_date date, last_settle_date date,
              principal_payment numeric(11, 2), accrued_payment numeric(11, 2), currency currency, daycount day_count,
              bbg_type bbg_type, figi varchar(12)) AS $$
DECLARE sqlquery text;
DECLARE asset_opt text;
DECLARE trade_or_settle text;
BEGIN

  IF p_class is not NULL THEN
	   asset_opt := 'AND securities.asset_class=$2 ';
  ELSE
     asset_opt := '';
  END IF;
  IF include_unsettled THEN
     trade_or_settle = 'trade_date';
  ELSE
     trade_or_settle = 'settle_date';
  END IF;
  sqlquery := format(
  'WITH temp AS (SELECT bond_trades.identifier, asset_class, settle_date, folder,'
  '              principal_payment, accrued_payment, sum(faceamount*(2*buysell::int-1) )'
  '              OVER (PARTITION BY bond_trades.identifier) notional'
  '              FROM bond_trades'
  '              WHERE %I<=$1 AND fund=$3)'
  'SELECT DISTINCT ON (identifier) securities.identifier, securities.description, notional,'
  'substring(folder::text FROM ''(?:M_)?(.*)'')::strategy AS folder,'
  'securities.coupon, start_accrued_date, settle_date, temp.principal_payment,'
  'temp.accrued_payment, securities.currency, securities.day_count, securities.bbg_type, securities.figi '
  'FROM temp LEFT JOIN securities USING (identifier) '
  'WHERE (temp.notional>0) AND paid_down>$1 %s '
  'ORDER BY identifier, settle_date desc',
  trade_or_settle,
  asset_opt);
  RETURN QUERY EXECUTE sqlquery USING p_date, p_class, p_fund;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_positions_range(start_date date,
          end_date date,
          p_class asset_class DEFAULT NULL)
RETURNS TABLE(identifier varchar(12), description varchar(32), notional float, strategy bond_strat,
              curr_cpn float, start_accrued_date date, last_settle_date date,
              principal_payment numeric(11, 2), accrued_payment numeric(11, 2), currency currency, daycount day_count,
              bbg_type bbg_type) AS $$
DECLARE sqlquery text;
DECLARE asset_opt text;
DECLARE unsettled_opt text;
BEGIN

  sqlquery := 'WITH temp AS (SELECT bonds.identifier, asset_class, settle_date, folder,
          principal_payment, accrued_payment, sum(faceamount*(2*buysell::int-1) )
          OVER (PARTITION BY bonds.identifier) notional FROM bonds
          WHERE trade_date <=$2)
  SELECT DISTINCT ON (temp.identifier) temp.identifier, securities.description, notional, folder,
  securities.coupon, start_accrued_date, settle_date, temp.principal_payment,
  temp.accrued_payment, securities.currency, securities.day_count, securities.bbg_type
  FROM temp LEFT JOIN securities USING (identifier)
  WHERE (temp.notional>0 or (temp.notional==0 and settle_date>=$1)) AND paid_down>$1 '||asset_opt
  ||' ORDER BY identifier, settle_date desc';
  RETURN QUERY EXECUTE sqlquery USING start_date, end_date, p_class;
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE function risk_positions(p_date date,
                                          p_assetclass asset_class,
                                          p_fund fund DEFAULT 'SERCGMAST'::fund,
                                          include_unsettled boolean DEFAULT True) RETURNS TABLE
(description varchar(32), identifier varchar(12), notional float, price float,
strategy strategy, factor float, local_market_value float, usd_market_value float,
curr_cpn float, int_acc float, last_pay_date date, principal_payment numeric(11, 2),
accrued_payment numeric(11, 2), last_settle_date date, figi varchar(12)) AS $$
BEGIN
  RETURN QUERY
  SELECT a.description, a.identifier, a.notional, c.price, a.strategy, coalesce(b.factor, 1),
      c.price/100. * a.notional * (CASE WHEN coalesce(b.factor,1)=0 THEN 1 ELSE coalesce(b.factor,1) END),
      c.price/100. * a.notional * (CASE WHEN coalesce(b.factor,1)=0 THEN 1 ELSE coalesce(b.factor,1) END) * fxrate,
      b.coupon,
      a.notional * coalesce(b.factor,1) * fxrate *
      yearfrac(case WHEN start_accrued_date>=p_date+1 THEN b.prev_cpn_date ELSE start_accrued_date END, p_date+1, daycount) * b.coupon/100.,
      b.last_pay_date, a.principal_payment, a.accrued_payment, a.last_settle_date, a.figi
  FROM list_positions(p_date, p_assetclass, include_unsettled, p_fund) a
  LEFT JOIN factors_history(p_date) b ON a.figi = b.identifier
  LEFT JOIN list_marks(p_date) c ON a.figi = c.identifier
  LEFT JOIN fx_rate(p_date) USING (currency)
  ORDER by identifier asc;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE VIEW orig_cds AS
SELECT DISTINCT ON (dealid) dealid, folder, index, series,
       version, tenor, fixed_rate, notional, upfront,
       protection, attach, detach, trade_date, upfront_settle_date
       FROM cds
       JOIN index_desc
       ON index_desc.redindexcode=cds.security_id AND index_desc.maturity=cds.maturity
ORDER BY dealid, trade_date;

CREATE OR REPLACE VIEW isosel_pnl_report AS
SELECT citco_reports.period_end_date,
    citco_reports."quantity(end)",
    citco_reports.bloomberg_code,
    citco_reports.symbol,
    split_part(citco_reports.strategy,'/',1) as Port,
    split_part(citco_reports.strategy,'/',2) as Strat,
    citco_reports."prime_broker/clearing_broker",
    citco_reports.subfund,
    citco_reports.cusip,
    citco_reports.isin,
    citco_reports.base_price,
    citco_reports.base_market_value,
    citco_reports.underlying_currency_code,
    citco_reports.security_description,
    citco_reports.security_asset_name,
    citco_reports.security_asset_class,
    citco_reports.underlying_symbol,
    citco_reports.factor,
    citco_reports.underlying_red,
    citco_reports."mtd_base_unrealized_p&l",
    citco_reports."mtd_base_realized_p&l",
    citco_reports."daily_base_p/l",
    citco_reports."monthly_base_p/l"
   FROM citco_reports
  WHERE citco_reports.subfund = 'ISOSEL_DFLT'::text;

CREATE OR REPLACE VIEW isosel_val_report AS
SELECT citco_reports.period_end_date,
    citco_reports."quantity(end)",
    citco_reports.bloomberg_code,
    citco_reports.symbol,
    split_part(citco_reports.strategy,'/',1) as Port,
    split_part(citco_reports.strategy,'/',2) as Strat,
    citco_reports."prime_broker/clearing_broker",
    citco_reports.subfund,
    citco_reports.cusip,
    citco_reports.isin,
    citco_reports.base_price,
    citco_reports.base_market_value,
    citco_reports.base_bond_accrued_interest,
    citco_reports.end_face_value as factored_notional,
    citco_reports.issue_ccy,
    citco_reports.security_description,
    citco_reports.security_asset_name,
    citco_reports.security_asset_class,
    citco_reports.underlying_symbol,
    citco_reports.factor,
    citco_reports.underlying_red,
    citco_reports.base_nav_contribution,
    citco_reports.total_fund_capital
   FROM citco_reports
  WHERE citco_reports.subfund = 'ISOSEL_DFLT'::text;

CREATE OR REPLACE VIEW external_marks_mapped AS
select date, identifier, mark, b.final as source from external_marks a
left join mark_source_mapping b on a.source = b.globeop order by a.date asc;

CREATE OR REPLACE function query_positions(p_type text DEFAULT NULL)
RETURNS text AS $$
DECLARE
  query text;

BEGIN
  query := 'WITH tmp AS (SELECT cds.security_id, cds.security_desc, cds.maturity,
cds.fixed_rate, cds.currency, %s %s SUM(cds.notional)
OVER (PARTITION BY cds.security_id, cds.maturity, cds.orig_attach, cds.orig_detach)  AS notional
FROM list_cds($1, $2) cds WHERE %s)
SELECT DISTINCT ON (tmp.security_id, tmp.maturity %s) * FROM tmp WHERE tmp.notional!=0';

IF p_type = 'tranche' THEN
   RETURN format(query, 'cds.orig_attach,cds.orig_detach,cds.attach,cds.detach,'
                        'cds.initial_margin_percentage,',
                        'sum(initial_margin_percentage * abs(notional)/100) '
                        'OVER (PARTITION BY cds.security_id, cds.maturity, cds.orig_attach, cds.orig_detach)'
                        'as initial_margin, ',
                        'cds.orig_attach is NOT NULL', ',tmp.orig_attach');
ELSIF p_type = 'cds' THEN
   RETURN format(query, '', '', 'cds.attach is NULL AND cds.folder!=''MBSCDS''', '');
ELSIF p_type = 'abs' THEN
   RETURN format(query, '', '', 'cds.folder=''MBSCDS''', '');
ELSE
   RETURN format(query, 'cds.attach, cds.detach,', '', '', ',tmp.attach');
END IF;
END;
$$ LANGUAGE plpgsql;

CREATE TYPE "LIST_CDS" AS(
       id integer,
       fund fund,
       trade_date date,
       security_id varchar(12),
       security_desc varchar(32),
       maturity date,
       fixed_rate float,
       currency currency,
       folder cds_strat,
       protection protection,
       notional float,
       orig_attach smallint,
       orig_detach smallint,
       attach float,
       detach float,
       fcm text,
       initial_margin_percentage float,
       cpty_id text,
       cp_code varchar(12)
);

CREATE OR REPLACE function list_cds(p_date date, VARIADIC p_fund fund[] DEFAULT '{SERCGMAST}'::fund[])
RETURNS SETOF "LIST_CDS" AS $$
BEGIN
RETURN QUERY
SELECT id, fund, trade_date, security_id, security_desc, maturity, fixed_rate, currency,
       folder, protection, (notional - coalesce(terminated_amount, 0.)) *
       (CASE WHEN cds.protection='Buyer' THEN 1 ELSE -1 END)
       AS notional,
       orig_attach, orig_detach, attach, detach, account_code, initial_margin_percentage,
       cpty_id,
       cp_code
FROM cds LEFT JOIN (
     SELECT dealid, SUM(termination_amount) AS terminated_amount
     FROM terminations WHERE termination_date <= p_date GROUP BY dealid) b USING (dealid)
WHERE fund=ANY(p_fund) and notional IS DISTINCT FROM terminated_amount
      AND trade_date <= p_date AND maturity > p_date;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_cds2(p_date date, VARIADIC p_fund fund[] DEFAULT '{SERCGMAST}'::fund[])
-- Do not include unsettled terminations
RETURNS SETOF "LIST_CDS" AS $$
BEGIN
RETURN QUERY
SELECT id, fund, trade_date, security_id, security_desc, maturity, fixed_rate, currency,
       folder, protection, (notional - coalesce(terminated_amount, 0.)) *
       (CASE WHEN cds.protection='Buyer' THEN 1 ELSE -1 END)
       AS notional,
       orig_attach, orig_detach, attach, detach, account_code, initial_margin_percentage,
       cpty_id,
       cp_code
FROM cds LEFT JOIN (
     SELECT dealid, SUM(termination_amount) AS terminated_amount
     FROM terminations WHERE fee_payment_date < p_date GROUP BY dealid) b USING (dealid)
WHERE fund=ANY(p_fund) and notional IS DISTINCT FROM terminated_amount
      AND trade_date <= p_date AND maturity > p_date;
END;
$$ LANGUAGE plpgsql;


CREATE TYPE LIST_SWAPTION AS(
       id integer,
       trade_date date,
       busell bool,
       option_type option_type,
       security_id varchar(12),
       security_desc varchar(32),
       maturity date,
       fixed_rate float,
       currency currency,
       folder swaption_strat,
       notional float,
       strike float,
       expiration_date date,
       initial_margin_percentage float,
       cpty_id text,
       cp_code varchar(12)
);

CREATE OR REPLACE function list_swaptions(p_date date, p_fund fund DEFAULT 'SERCGMAST'::fund)
-- Do not include unsettled terminations
RETURNS SETOF LIST_SWAPTION AS $$
BEGIN
RETURN QUERY
SELECT id, trade_date, security_id, security_desc, maturity, fixed_rate, currency,
       folder, buysell, (notional - coalesce(terminated_amount, 0.)) *
       (2* buysell -1) AS notional,
       strike, expiration_date, initial_margin_percentage,
       cpty_id,
       cp_code
FROM swaptions LEFT JOIN (
     SELECT dealid, SUM(termination_amount) AS terminated_amount
     FROM terminations WHERE fee_payment_date < p_date GROUP BY dealid) b USING (dealid)
WHERE fund=p_fund and notional IS DISTINCT FROM terminated_amount
      AND trade_date <= p_date AND expiration_date > p_date;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_cds_positions (p_date date,
                                               strat cds_strat DEFAULT NULL::cds_strat,
                                               fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), maturity date,
              fixed_rate float, currency currency, notional float) AS $$
BEGIN
IF strat IS NULL THEN
   RETURN QUERY EXECUTE query_positions('cds') USING p_date, fund;
ELSE
   RETURN QUERY SELECT a.security_id, a.security_desc, a.maturity, a.fixed_rate,
                       a.currency, a.notional
                FROM list_cds_positions_by_strat(p_date, fund) a
                WHERE folder=strat;
END IF;
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE function list_cds_positions_by_strat(p_date date,
                                                       p_fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), maturity date,
              fixed_rate float, currency currency, folder cds_strat, notional float) AS $$
BEGIN
RETURN QUERY
  WITH tmp AS (SELECT cds.security_id, cds.security_desc, cds.maturity, cds.fixed_rate,
       cds.currency, cds.folder,
       SUM(cds.notional)
       OVER (PARTITION BY cds.security_id, cds.maturity, cds.folder)  AS notional
       FROM list_cds(p_date, p_fund) cds WHERE (cds.attach is NULL AND cds.folder != 'MBSCDS'))
  SELECT DISTINCT ON (tmp.security_id, tmp.maturity, tmp.folder) * FROM tmp WHERE tmp.notional!=0;
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE function list_cds_positions_by_strat_fcm(p_date date,
                                                           p_fcm text,
                                                           p_fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), maturity date,
              fixed_rate float, currency currency, folder cds_strat, notional float) AS $$
BEGIN
RETURN QUERY
  WITH tmp AS (SELECT cds.security_id, cds.security_desc, cds.maturity, cds.fixed_rate,
       cds.currency, cds.folder,
       SUM(cds.notional)
       OVER (PARTITION BY cds.security_id, cds.maturity, cds.folder, cds.fcm)  AS notional
       FROM list_cds(p_date, p_fund) cds WHERE (cds.attach is NULL AND cds.folder != 'MBSCDS' AND cds.fcm=p_fcm))
  SELECT DISTINCT ON (tmp.security_id, tmp.maturity, tmp.folder) * FROM tmp WHERE tmp.notional!=0;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_cds_positions_fcm(p_date date,
                                                  p_fcm text,
                                                  p_fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), maturity date,
              fixed_rate float, currency currency, notional float) AS $$
BEGIN
RETURN QUERY
  WITH tmp AS (SELECT cds.security_id, cds.security_desc, cds.maturity, cds.fixed_rate,
       cds.currency,
       SUM(cds.notional)
       OVER (PARTITION BY cds.security_id, cds.maturity, cds.fcm)  AS notional
       FROM list_cds(p_date, p_fund) cds WHERE (cds.attach is NULL AND cds.folder != 'MBSCDS' AND cds.fcm=p_fcm))
  SELECT DISTINCT ON (tmp.security_id, tmp.maturity) * FROM tmp WHERE abs(tmp.notional) > 0.1;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION trade_upload_baml(p_date date, p_fcm text, p_fund fund DEFAULT 'SERCGMAST::fund')
RETURNS TABLE("Type" text, "CCP ID" text, "B/S Protection" text, "Identifier" text, "Notional" float, "Fixed Rate" integer, "Trade Date" date, "Maturity Date" date, CCY text, "Payment Freq" text)
SELECT 'CDX',
       123456,
       CASE WHEN notional >0 THEN 'BUY' ELSE 'SELL' END,
       tradeid,
       abs(notional),
       fixed_rate * 100,
       '6/27/2022',
       l.maturity,
       currency,
       'QUARTERLY'
FROM
    list_cds_positions_fcm('2022-06-27', 'BAML') l
LEFT JOIN
     index_maturity_markit imm ON redindexcode=security_id AND imm.maturity=l.maturity
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION cds_globeop_name(redcode text, fixed_rate float, maturity date,
       index index_type, tenor tenor)
RETURNS text AS $$
DECLARE
    result text;
    stub text;
    fcm text;

BEGIN
result := 'CDS_%s%s_%s.0000000000_ICE-CREDIT_%s_%s';
IF tenor = '3yr' AND redcode = '2I65BYDJ1' THEN
   stub := '.3';
ELSE
   stub := '';
END IF;
IF redcode = '2I65BRQY9' OR redcode = '2I65BYBE4' OR redcode = '2I666VCT0' THEN
   fcm = 'WELLSFCM';
ELSE
   fcm = 'BOMLCM';
END IF;
result := format(result, redcode, stub, fixed_rate, fcm, to_char(maturity, 'YYYYMMDD'));
RETURN result;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_tranche_positions(p_date date, fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), maturity date,
              fixed_rate float, currency currency, orig_attach smallint,
              orig_detach smallint, attach float, detach float,
              initial_margin_percentage float, initial_margin float,
              notional float) AS $$
BEGIN
RETURN QUERY EXECUTE query_positions('tranche') USING p_date, fund;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_tranche_positions_by_strat(p_date date,
                                                           p_fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), maturity date,
              fixed_rate float, currency currency, orig_attach smallint,
              orig_detach smallint, attach float, detach float,
              folder cds_strat, notional float) AS $$
BEGIN
RETURN QUERY
  WITH tmp AS (SELECT cds.security_id, cds.security_desc, cds.maturity, cds.fixed_rate,
       cds.currency, cds.orig_attach, cds.orig_detach,
       cds.attach, cds.detach, cds.folder,
       SUM(cds.notional)
       OVER (PARTITION BY cds.security_id, cds.maturity, cds.orig_attach, cds.orig_detach, cds.folder)  AS notional
       FROM list_cds(p_date, p_fund) cds WHERE cds.orig_attach is NOT NULL)
  SELECT DISTINCT ON (tmp.security_id, tmp.maturity, tmp.orig_attach, tmp.folder) * FROM tmp WHERE tmp.notional!=0;
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE function list_abscds_positions(p_date date, fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), maturity date,
              fixed_rate float, currency currency, notional float) AS $$
BEGIN
RETURN QUERY EXECUTE query_positions('abs') USING p_date, fund;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_cds_marks_old(p_date date, strat cds_strat DEFAULT NULL::cds_strat)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), p_index index_type, p_series smallint,
              p_version smallint, tenor tenor, maturity date, notional float, factor float,
              name text, coupon float, duration float, theta float, price float, closespread float,
              clean_nav float, accrued float) AS $$
DECLARE
  eur_fx float;
  params text;
  sqlquery text;
BEGIN
SELECT eurusd INTO eur_fx FROM fx WHERE date=p_date;
IF strat IS NOT NULL THEN
   params := '$1, $3';
ELSE
   params := '$1';
END IF;

sqlquery := format(
'WITH temp AS (SELECT a.*, c.index, c.series, c.version, c.tenor, c.indexfactor/100. AS fact,
              cds_globeop_name(a.security_id, a.fixed_rate, a.maturity, c.index, c.tenor)
              FROM list_cds_positions(%s) a
              LEFT JOIN index_desc c ON (a.security_id=c.redindexcode AND a.maturity=c.maturity)),
index_price AS (SELECT index, series, version, d.tenor, closeprice, d.duration, d.closespread, d.theta2
                FROM index_quotes d WHERE date=$1)
SELECT
    temp.security_id, temp.security_desc, temp.index, temp.series, temp.version, temp.tenor,
    temp.maturity, temp.notional, temp.fact, temp.cds_globeop_name, temp.fixed_rate/100,
    index_price.duration, index_price.theta2, index_price.closeprice, index_price.closespread,
    (1.-index_price.closeprice/100.) * temp.notional * temp.fact *
    (CASE WHEN temp.currency = ''EUR'' THEN $2 ELSE 1 END),
    -temp.notional * temp.fact * cds_accrued($1, temp.fixed_rate/100., TRUE, temp.currency)
    (CASE WHEN temp.currency = ''EUR'' THEN $2 ELSE 1 END)
FROM temp
LEFT JOIN index_price USING (index, series, version, tenor)', params);
IF strat IS NOT NULL THEN
   RETURN QUERY EXECUTE sqlquery USING p_date, eur_fx, strat;
ELSE
    RETURN QUERY EXECUTE sqlquery USING p_date, eur_fx;
END IF;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_cds_marks_pre(p_date date, strat cds_strat DEFAULT NULL::cds_strat, fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), p_index index_type,
              p_series smallint,
              p_version smallint, tenor tenor, maturity date, notional float,
              factor float, coupon float, duration float, theta float, price float,
              closespread float, clean_nav float, accrued float) AS $$
DECLARE
  eur_fx float;
  params text;
  sqlquery text;
  and_clause text;
BEGIN
SELECT DISTINCT ON (date) eurusd INTO eur_fx FROM fx WHERE date BETWEEN p_date - INTERVAL '3 DAYS' AND p_date;
IF strat IS NOT NULL THEN
   params := '$1, $4, $2';
   and_clause := 'AND strat = ltrim($4::text, ''SER_'')::strategy';
ELSE
   params := '$1, NULL, $2';
   and_clause := '';
END IF;

sqlquery := format(
'WITH temp AS (SELECT a.*, c.index, c.series, c.version, c.tenor, c.indexfactor/100. AS fact
              FROM list_cds_positions(%s) a
              LEFT JOIN index_desc c ON (a.security_id=c.redindexcode AND a.maturity=c.maturity)),
index_price AS (SELECT DISTINCT ON (index, series, version, d.tenor) index, series, version, d.tenor, closeprice, d.duration2, d.closespread, d.theta2
                FROM index_quotes d WHERE date BETWEEN $1 - INTERVAL ''3 days'' AND $1 ORDER BY index, series, version, d.tenor, date desc)
SELECT
    temp.security_id, temp.security_desc, temp.index, temp.series, temp.version, temp.tenor,
    temp.maturity, temp.notional, temp.fact, temp.fixed_rate/100,
    index_price.duration2, index_price.theta2, index_price.closeprice, index_price.closespread,
    (1.-index_price.closeprice/100.) * temp.notional * temp.fact *
    (CASE WHEN temp.currency = ''EUR'' THEN $3 ELSE 1 END),
    -temp.notional * temp.fact * cds_accrued($1, temp.fixed_rate/100, FALSE, temp.currency::text) *
    (CASE WHEN temp.currency = ''EUR'' THEN $3 ELSE 1 END)
FROM temp
LEFT JOIN index_price USING (index, series, version, tenor)', params);
IF strat IS NOT NULL THEN
   RETURN QUERY EXECUTE sqlquery USING p_date, fund, eur_fx, strat;
ELSE
    RETURN QUERY EXECUTE sqlquery USING p_date, fund, eur_fx;
END IF;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE VIEW bowdst_index AS
SELECT as_of_date, p_index, p_series, maturity, admin_notional, admin_clean_nav FROM (
SELECT as_of_date, substring(security_description_1 FROM '(IG|HY|EU|XO)(?:R|VER)?(?:\.| )(?:[0-9]{2})')::index_type AS p_index,
    substring(security_description_1 FROM '(?:IG|HY|EUR|XOVER)(?:\.| )([0-9]{2})')::smallint as p_series,
    maturity_date AS maturity,
    (CASE WHEN coupon_rate=0 THEN current_notional ELSE -current_notional END) AS admin_notional,
    sum(base_market_value) OVER w as admin_clean_nav,
    row_number() OVER w
FROM bowdst_val WHERE security_description_1 LIKE '%CCP%'
WINDOW w AS (PARTITION BY
                as_of_date,
                substring(security_description_1 FROM '(IG|HY|EU|XO)(?:R|VER)?(?:\.| )(?:[0-9]{2})')::index_type,
                substring(security_description_1 FROM '(?:IG|HY|EUR|XOVER)(?:\.| )([0-9]{2})')::smallint,
                maturity_date)
) AS ss WHERE row_number=1;

CREATE OR REPLACE FUNCTION list_cds_marks(p_date date, strat cds_strat DEFAULT NULL::cds_strat, p_fund fund DEFAULT 'SERCGMAST'::fund)
 RETURNS TABLE(security_id character varying, security_desc character varying, index index_type, series smallint, version smallint, tenor tenor, maturity date, notional double precision, factor double precision, coupon double precision, duration double precision, theta double precision, price double precision, closespread double precision, clean_nav double precision, accrued double precision, globeop_nav double precision, globeop_notional double precision)
 LANGUAGE plpgsql
AS $function$
DECLARE
  sqlquery text;
  and_clause text;
BEGIN
IF strat IS NOT NULL THEN
   IF p_fund = 'ISOSEL' OR p_fund = 'CRSE' THEN
       and_clause := 'AND split_part(strategy, ''/'', 2) = $2::text';
   ELSE
       and_clause := 'AND strat = ltrim($2::text, ''SER_'')::strategy';
   END IF;
ELSE
   and_clause := '';
END IF;
IF p_fund = 'SERCGMAST' OR p_fund = 'BOWDST' THEN
sqlquery := format('
SELECT l.*, b.globeop_nav, b.globeop_notional FROM list_cds_marks_pre($1, $2, $3) l
JOIN (SELECT a.security_id, a.maturity, sum(endbooknav) AS globeop_nav,
             sum(endqty) AS globeop_notional
        FROM (SELECT periodenddate as date,
                    fund,
                    endqty,
                    endbooknav,
                    split_part(invid, ''_'', 2) AS security_id,
                    split_part(invid, ''_'', 6)::date AS maturity
              FROM valuation_reports WHERE invid LIKE ''CDS\_%%'' %s) a
      GROUP BY date, fund, a.security_id, a.maturity HAVING date=$1 AND fund=$3) b
USING (security_id, maturity)', and_clause);
-- ELSIF p_fund = 'BOWDST' THEN
-- sqlquery := 'SELECT a.*, bowdst_index.admin_clean_nav, bowdst_index.admin_notional FROM list_cds_marks_pre($1, $2, $3) a LEFT JOIN bowdst_index USING (p_index, p_series, maturity) WHERE as_of_date=$1';
ELSIF p_fund = 'BRINKER'  THEN
sqlquery := 'SELECT  *, 0::double precision, 0::double precision FROM list_cds_marks_pre($1, $2, $3)';
ELSIF p_fund = 'ISOSEL' OR p_fund = 'CRSE' THEN
sqlquery := format('
SELECT l.*, b.dirty_nav, b.position FROM list_cds_marks_pre($1, $2, $3) l
LEFT JOIN index_version ON security_id=redindexcode
LEFT JOIN index_maturity USING (INDEX, series, maturity)
LEFT JOIN (
SELECT ticker_bbg AS bbg_id, -sum(position*end_princ_factor) AS position, sum(end_mkt_value+total_acc_int) AS dirty_nav
FROM isosel_accrued WHERE instr_type=''Credit Default Swap''
AND ticker_bbg IS NOT NULL AND status in (''Open'', ''P'') %s GROUP BY period_end_date, fund, ticker_bbg HAVING period_end_date=$1 AND fund=$3) b USING (bbg_id)', and_clause);
END IF;
RETURN QUERY EXECUTE sqlquery USING p_date, strat, p_fund;
END;
$function$
;




CREATE OR REPLACE function list_cds_marks_by_strat(p_date date)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), strategy cds_strat,
              p_index index_type, p_series smallint,
              p_version smallint, tenor tenor, maturity date, notional float, factor float,
              name text, coupon float, duration float, theta float, price float, closespread float,
              clean_nav float, accrued float) AS $$
DECLARE
  days integer;
  eur_fx float;
  params text;
  sqlquery text;
BEGIN
days:=days_accrued(p_date);
SELECT eurusd INTO eur_fx FROM fx WHERE date=p_date;

sqlquery := 'WITH temp AS (SELECT a.*, c.index, c.series, c.version, c.tenor, c.indexfactor/100. AS fact,
              cds_globeop_name(a.security_id, a.fixed_rate, a.maturity, c.index, c.tenor)
              FROM list_cds_positions_by_strat($1) a
              LEFT JOIN index_desc c ON (a.security_id=c.redindexcode AND a.maturity=c.maturity)),
index_price AS (SELECT index, series, version, d.tenor, closeprice, d.duration, d.closespread, d.theta
                FROM index_quotes d WHERE date=$1)
SELECT
    temp.security_id, temp.security_desc, temp.folder, temp.index, temp.series, temp.version, temp.tenor,
    temp.maturity, temp.notional, temp.fact, temp.cds_globeop_name, temp.fixed_rate/100,
    index_price.duration, index_price.theta, index_price.closeprice, index_price.closespread,
    (1.-index_price.closeprice/100.) * temp.notional * temp.fact *
    (CASE WHEN temp.currency = ''EUR'' THEN $2 ELSE 1 END),
    -temp.notional * temp.fixed_rate/100. * temp.fact * $3 / 360 *
    (CASE WHEN temp.currency = ''EUR'' THEN $2 ELSE 1 END)
FROM temp
LEFT JOIN index_price USING (index, series, version, tenor)';
RETURN QUERY EXECUTE sqlquery USING p_date, eur_fx, days;
END;
$$ LANGUAGE plpgsql;

CREATE TABLE index_risk(
       date date,
       fund fund,
       security_id text,
       maturity date,
       folder cds_strat,
       notional float,
       index_factor float,
       hy_equiv float,
       PRIMARY KEY (date, fund, security_id, maturity, folder));

CREATE TABLE tranche_risk(
       date date,
       tranche_id integer REFERENCES cds(id),
       notional float,
       clean_nav float,
       accrued float,
       duration float,
       delta float,
       gamma float,
       theta float,
       corr01 float,
       tranche_factor float,
       upfront float,
       running float,
       corr_attach float,
       corr_detach float,
       index_refprice float,
       index_refspread float,
       index_duration float,
       hy_equiv float,
       theta_amount float,
       ir_dv01 float,
       index_factor float,
       corr01_vec float[2],
       PRIMARY KEY (date, tranche_id));

CREATE TABLE ir_swaption_risk(
       date date,
       swpt_id integer REFERENCES swaptions(id),
       notional float,
       pv float,
       vol float,
       vol_type text,
       "DV01" float,
       "IRGamma1bp" float,
       vega float,
       PRIMARY KEY (date, swpt_id));

CREATE TABLE ir_swap_risk(
       date date,
       swp_id integer REFERENCES irs(id),
       notional float,
       pv float,
       "DV01" float,
       "IRGamma1bp" float,
       PRIMARY KEY (date, swp_id));

CREATE OR REPLACE function list_tranche_marks(p_date date, fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), security_desc varchar(32), p_index index_type,
              p_series smallint, p_version smallint, p_tenor tenor, maturity date,
              notional float, factor float, coupon integer, clean_nav float,
              accrued float, initial_margin float, theta float,
              duration float, tranchedelta float4, trancheupfrontmid float,
              indexrefprice float4, indexrefspread smallint,
              attach smallint, detach smallint, index_duration float) AS $$
DECLARE
  days integer;
  eur_fx float;
BEGIN
days:=days_accrued(p_date);
SELECT eurusd INTO eur_fx FROM fx WHERE date=p_date;
RETURN QUERY
WITH temp AS (SELECT a.*, c.index, c.series, c.version, c.basketid, d.tenor,
             (a.detach-a.attach)/(a.orig_detach-a.orig_attach) * c.indexfactor / 100 AS fact
              FROM list_tranche_positions(p_date, fund) a
              LEFT JOIN index_version c ON a.security_id=c.redindexcode
              LEFT JOIN index_maturity d USING (index, series, maturity)),
risk_num AS (SELECT DISTINCT ON (index, series, a.attach, a.detach, tenor) * from risk_num_per_quote a
              WHERE quotedate BETWEEN p_date - interval '1 week' AND p_date + interval '1 day'
              ORDER by index, series, a.attach, a.detach, tenor, quotedate desc)
SELECT temp.security_id, temp.security_desc, temp.index, temp.series, temp.version, temp.tenor,
       temp.maturity, temp.notional, temp.fact,
       trancherunningmid::integer,
       temp.notional * temp.fact * (case when temp.index = 'HY' then (1.-risk_num.trancheupfrontmid/100) else risk_num.trancheupfrontmid/100 end) *
       (CASE WHEN temp.currency = 'EUR' THEN eur_fx ELSE 1 END),
       -temp.notional * temp.fact * trancherunningmid/10000. * days / 360 *
       (CASE WHEN temp.currency = 'EUR' THEN eur_fx ELSE 1 END),
       temp.initial_margin, risk_num.theta, risk_num.duration, risk_num.tranchedelta,
       risk_num.trancheupfrontmid, risk_num.indexrefprice, risk_num.indexrefspread,
       temp.orig_attach, temp.orig_detach, risk_num.index_duration
FROM temp
LEFT JOIN risk_num  ON
     temp.series=risk_num.series
     AND temp.orig_attach = risk_num.attach
     AND temp.orig_detach = risk_num.detach
     AND temp.tenor = risk_num.tenor;
END
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION list_swaption_positions_and_risks(IN p_date date, p_fund fund DEFAULT 'SERCGMAST'::fund)
  RETURNS TABLE(deal_id character varying, security_id character varying,
  maturity date, notional double precision, option_type option_type,
  strike double precision, expiration_date date, serenitas_nav double precision,
  globeop_nav double precision,
  initial_margin double precision, latest_model_date date,
  delta double precision, gamma double precision, vega double precision,
  theta double precision, hy_equiv double precision,index index_type,
  series smallint, tenor tenor,
  duration double precision, portfolio portfolio, indexfactor float) AS $$
BEGIN
RETURN QUERY
-- TODO: fix the case of multiple index versions
SELECT DISTINCT ON (a.dealid) a.dealid, a.security_id, c.maturity,
       (CASE WHEN buysell = 't' THEN 1 ELSE -1 END) * (a.notional -  coalesce(terminated_amount, 0.)),
       a.option_type, a.strike, a.expiration_date, b.market_value,
       coalesce(endbooknav, base_market_value, end_mkt_value),
       f.ia, b.date, b.delta, b.gamma, b.vega,
       b.theta, b.hy_equiv, c.index, c.series, c.tenor, d.duration, a.portfolio, c.indexfactor
FROM swaptions a
LEFT JOIN (SELECT * FROM swaption_marks where date <= p_date) b USING (dealid)
LEFT JOIN index_desc c ON a.security_id=redindexcode AND a.maturity=c.maturity
LEFT JOIN (SELECT * FROM index_quotes WHERE date=p_date) d USING (index, series, tenor)
LEFT JOIN valuation_reports ON NULLIF(substring(invid FROM '\D{3}[0]*(\d*)K'), '')::integer = a.globeop_id
LEFT JOIN bowdst_val ON link_ref = a.dealid AND as_of_date=p_date
LEFT JOIN isosel_accrued ON a.dealid=isosel_accrued.init_fix_id AND period_end_date=p_date
LEFT JOIN (SELECT dealid, SUM(termination_amount) AS terminated_amount
           FROM terminations WHERE termination_date <= p_date GROUP BY dealid) e USING (dealid)
LEFT JOIN external_marks_deriv f ON identifier=cpty_id AND f.date=p_date
WHERE a.notional IS DISTINCT FROM terminated_amount
AND a.expiration_date > p_date AND trade_date <= p_date
AND swap_type = 'CD_INDEX_OPTION'
AND (periodenddate IS NULL OR periodenddate <= p_date)
AND a.fund = p_fund
ORDER BY dealid, date DESC, periodenddate DESC;
END
$$ LANGUAGE plpgsql;


CREATE OR REPLACE FUNCTION list_ir_capfloor_positions(p_date date, p_fund fund DEFAULT 'SERCGMAST'::fund)
  RETURNS TABLE(deal_id character varying, strategy swaption_strat, amount double precision,
  cap_or_floor cap_or_floor, strike double precision, floating_rate_index character varying,
  expiration_date date, initial_margin_percentage double precision,
  comments character varying, cp_code character varying, nav double precision ) AS $$
BEGIN
RETURN QUERY
SELECT a.dealid, folder,
       (CASE WHEN buysell = 't' THEN 1 ELSE -1 END) * (a.amount -  coalesce(terminated_amount, 0.)),
      a.cap_or_floor, a.strike, a.floating_rate_index, a.expiration_date, a.initial_margin_percentage,
      a.comments, a.cp_code, c.base_nav
FROM capfloors a
LEFT JOIN (SELECT dealid, SUM(termination_amount) AS terminated_amount
           FROM terminations WHERE termination_date <= p_date GROUP BY dealid) b USING (dealid)
LEFT JOIN (SELECT identifier, base_nav FROM external_marks_deriv WHERE date=p_date) c ON a.cpty_id = c.identifier
WHERE a.amount IS DISTINCT FROM terminated_amount
AND  a.expiration_date > p_date
AND a.trade_date <= p_date
AND fund=p_fund;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION list_ir_swaption_positions(IN p_date date, p_fund fund DEFAULT 'SERCGMAST'::fund)
  RETURNS TABLE(deal_id character varying, strategy swaption_strat, notional double precision,
  option_type option_type, strike double precision, security_id varchar, expiration_date date, maturity date,
  initial_margin_percentage double precision, cp_code character varying, nav double precision) AS $$
BEGIN
RETURN QUERY
SELECT a.dealid, folder,
       (CASE WHEN buysell = 't' THEN 1 ELSE -1 END) * (a.notional -  coalesce(terminated_amount, 0.)),
       a.option_type, a.strike/100, a.security_id, a.expiration_date, a.maturity, a.initial_margin_percentage,
       a.cp_code, c.base_nav
FROM swaptions a
LEFT JOIN (SELECT dealid, SUM(termination_amount) AS terminated_amount
           FROM terminations WHERE termination_date <= p_date GROUP BY dealid) b USING (dealid)
LEFT JOIN (SELECT identifier, base_nav FROM external_marks_deriv where date = p_date) c on a.cpty_id = c.identifier
WHERE a.notional IS DISTINCT FROM terminated_amount
AND  a.expiration_date > p_date
AND a.trade_date <= p_date
AND a.swap_type = 'SWAPTION'
AND fund=p_fund;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_abscds_marks(p_date date, fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(security_id varchar(12), cusip varchar(9), security_desc varchar(32), maturity date,
              notional float, factor float, fixed_rate float, clean_nav float, accrued float) AS $$
BEGIN
RETURN QUERY
WITH temp AS (SELECT a.*, b.price, c.factor, d.start_accrued_date, d.cusip FROM list_abscds_positions(p_date, fund) a
LEFT JOIN (SELECT DISTINCT ON (identifier) date, marks.identifier, marks.price
           FROM marks WHERE date<=p_date ORDER BY identifier, date desc) b
ON a.security_id=b.identifier
LEFT JOIN factors_history(p_date) c ON a.security_id=c.identifier
LEFT JOIN securities d ON a.security_id=d.identifier)
SELECT temp.security_id, temp.cusip, temp.security_desc, temp.maturity, temp.notional, temp.factor,
temp.fixed_rate, temp.notional*temp.factor*(100.-temp.price)/100,
-yearfrac(temp.start_accrued_date, p_date+1, 'ACT/360')*temp.fixed_rate/100*temp.notional*temp.factor
FROM temp;
END
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function imm_date(p_date date)
RETURNS date AS $$
from dates import imm_date
return imm_date(p_date)
$$ LANGUAGE plpython3u;

CREATE OR REPLACE FUNCTION cds_accrued(date, double precision, bool, text DEFAULT 'USD') RETURNS double precision
AS '$libdir/serenitas_date', 'cds_accrued'
LANGUAGE C STRICT;


CREATE MATERIALIZED VIEW factors_history AS
 WITH temp AS (
         SELECT c.date,
            c.identifier,
            c.principal,
            c.principal_bal,
            c.interest,
            lead(c.coupon) OVER w AS coupon,
            (- c.principal) - c.principal_bal + lag(c.principal_bal) OVER w AS losses,
            c.principal_bal / NULLIF(c.factor, 0.) AS face_amount,
            c.factor
           FROM cashflow_history c
          WINDOW w AS (PARTITION BY c.identifier ORDER BY c.date)
        )
 SELECT temp.date AS last_pay_date,
    temp.date-securities.pay_delay AS prev_cpn_date,
    temp.identifier,
    temp.factor,
    temp.principal / COALESCE(temp.face_amount, securities.face_amount) * 100::float AS principal,
    temp.interest / COALESCE(temp.face_amount, securities.face_amount) * 100::float AS interest,
    temp.losses / COALESCE(temp.face_amount, securities.face_amount) * 100::float AS losses,
    COALESCE(temp.coupon, securities.coupon) AS coupon
    FROM temp
    JOIN securities ON temp.identifier=securities.figi
;

CREATE UNIQUE INDEX factors_history_pkey ON factors_history(prev_cpn_date, identifier);

CREATE OR REPLACE function factors_history(p_date date)
RETURNS SETOF factors_history AS $$
BEGIN
RETURN QUERY
SELECT DISTINCT ON (identifier) * FROM factors_history
       WHERE prev_cpn_date<=p_date ORDER BY identifier, prev_cpn_date desc;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION isleapyear (
  D date
) RETURNS boolean
AS $$
DECLARE
  y INTEGER;
BEGIN
 y := extract (year from D);
 if (y % 4) != 0 then
   return false;
 end if;

 if (y % 400) = 0 then
   return true;
 end if;

 return (( y % 100) != 0);
END;
$$ LANGUAGE 'plpgsql';

CREATE OR REPLACE FUNCTION yearfrac(date1 date, date2 date, daycount day_count)
RETURNS float AS $$
DECLARE
  factor float;
  y1 integer;
  y2 integer;
  m1 integer;
  m2 integer;
  d1 integer;
  d2 integer;
BEGIN

IF daycount='30/360' THEN
   y1 := extract(YEAR FROM date1);
   y2 := extract(YEAR FROM date2);
   m1 := extract(MONTH FROM date1);
   m2 := extract(MONTH FROM date2);
   d1 := extract(DAY FROM date1);
   d2 := extract(DAY FROM date2);
   IF d2=31 and (d1=30 or d1=31) THEN
      d2:=30;
   END IF;
   IF d1=31 THEN
      d1:=30;
   END IF;
   factor:= (360*(y2-y1) + 30*(m2-m1)+d2-d1)/360.;
ELSIF daycount='ACT/365' THEN
  factor:=(date2-date1)/365.;
ELSIF daycount='ACT/360' THEN
  factor:=(date2-date1)/360.;
ELSIF daycount='ACT/ACT' THEN
  IF isleapyear(date1) THEN
    factor:=(date2-date1)/366.;
  ELSE
    factor:=(date2-date1)/365.;
  END IF;
END IF;
RETURN factor;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function tranche_factor(attach smallint, detach smallint,
                  index_factor float, cumulativeloss float)
RETURNS float AS $$
-- index_factor and cumulativeloss are in percents, eg:
-- tranche_factor(15::smallint, 25::smallint, 98, 0.71)
DECLARE
  newattach float;
  newdetach float;

BEGIN
newattach:=LEAST(GREATEST((attach-cumulativeloss)/index_factor, 0), 1);
newdetach:=LEAST(GREATEST((detach-cumulativeloss)/index_factor, 0), 1);
RETURN (newdetach-newattach)/(detach-attach)*index_factor;
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE function fx_rate(p_date date) RETURNS TABLE(currency currency, fxrate float) AS $$
BEGIN
  RETURN QUERY SELECT unnest(Array['USD', 'EUR', 'CAD'])::currency,
  unnest(Array[1, eurusd, cadusd]) FROM fx WHERE date<=p_date ORDER by date desc LIMIT 3;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function latest_sim(p_date date) RETURNS integer AS $$
DECLARE
	id integer;
BEGIN
SELECT model_id_sub into id
  FROM priced
  INNER JOIN model_versions USING (model_id_sub)
  INNER JOIN model_versions_nonagency USING (model_id_sub)
  INNER JOIN simulations_nonagency USING (simulation_id)
    WHERE description = 'normal' AND timestamp >= p_date
    LIMIT 1;
RETURN id;
End;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION id_translate(VARIADIC id1 varchar(9)[])
RETURNS TABLE(id2 varchar(12)) AS $$
BEGIN
       RETURN QUERY SELECT figi FROM securities
       JOIN unnest(id1) WITH ORDINALITY AS t(cusip, id)
       USING (cusip) ORDER BY id;
END;
$$ LANGUAGE plpgsql;

-- Not sure how to map enums so use text for now
CREATE FOREIGN TABLE priced(
     model_id_sub smallint,
     cusip varchar(9),
     model_version smallint,
     normalization text,
     timestamp timestamp,
     pv float,
     pv_RnW float,
     pv_FB float,
     pv_io float,
     pv_po float,
     modDur float,
     modDur_io float,
     modDur_po float,
     wal float,
     wal_width float,
     wal_io float,
     wal_po float,
     delta_hpi float,
     delta_ir float,
     delta_ir_io float,
     delta_ir_po float,
     delta_mult float,
     delta_yield float,
     delta_quantile float,
     delta_RnW float,
     tot_gamma_hpi float,
     tot_gamma_ir float,
     tot_gamma float)
     SERVER mysql_server
     OPTIONS (dbname 'rmbs_model');

-- We want to use INHERITS here, but will only be available on 9.5
CREATE FOREIGN TABLE priced_orig_ntl(
     model_id_sub smallint,
     cusip varchar(9),
     model_version smallint,
     normalization text,
     timestamp timestamp,
     pv float,
     pv_RnW float,
     pv_FB float,
     pv_io float,
     pv_po float,
     modDur float,
     modDur_io float,
     modDur_po float,
     wal float,
     wal_width float,
     wal_io float,
     wal_po float,
     delta_hpi float,
     delta_ir float,
     delta_ir_io float,
     delta_ir_po float,
     delta_mult float,
     delta_yield float,
     delta_quantile float,
     delta_RnW float,
     tot_gamma_hpi float,
     tot_gamma_ir float,
     tot_gamma float)
     SERVER mysql_server
     OPTIONS (dbname 'rmbs_model');

CREATE FOREIGN TABLE priced_percentiles(
     model_id_sub smallint,
     cusip varchar(9),
     model_version smallint,
     percentile float,
     normalization text,
     timestamp timestamp,
     pv float,
     pv_io float,
     pv_po float,
     modDur float,
     modDur_io float,
     modDur_po float,
     wal float,
     wal_width float,
     wal_io float,
     wal_po float)
     SERVER mysql_server
     OPTIONS (dbname 'rmbs_model');

CREATE FOREIGN TABLE priced_percentiles_orig_ntl(
     model_id_sub smallint,
     cusip varchar(9),
     model_version smallint,
     percentile float,
     normalization text,
     timestamp timestamp,
     pv float,
     pv_io float,
     pv_po float,
     modDur float,
     modDur_io float,
     modDur_po float,
     wal float,
     wal_width float,
     wal_io float,
     wal_po float)
     SERVER mysql_server
     OPTIONS (dbname 'rmbs_model');

CREATE TYPE INDEXFAMILY AS ENUM('ITRAXX-Asian', 'LCDXNA', 'MCDXNA',
'ITRAXX-SOVX', 'ITRAXX-SDI', 'ITRAXX-L', 'CDX', 'ITRAXX-European');
CREATE TYPE curr AS ENUM('USD', 'EUR', 'JPY', 'GBP', 'CAD');

IMPORT FOREIGN SCHEMA public LIMIT TO
(index_desc,
 index_version,
 index_factors,
 index_maturities,
 index_version_markit,
 index_maturity,
 index_maturity_markit,
 index_quotes,
 markit_tranche_quotes,
 risk_num_per_quote,
 rates) FROM SERVER postgresql_server INTO public;


CREATE FOREIGN TABLE model_versions(
     model_id smallint,
     asset_class text,
     start_time timestamp,
     model_id_sub smallint)
     SERVER mysql_server
     OPTIONS (dbname 'rmbs_model');

CREATE FOREIGN TABLE model_versions_nonagency(
     model_id_sub smallint,
     granularity_agg text,
     num_LS_mult smallint,
     d_LS_mult float,
     simulation_id smallint,
     remark text)
     SERVER mysql_server
     OPTIONS (dbname 'rmbs_model');

CREATE FOREIGN TABLE simulations_nonagency(
     simulation_id smallint,
     granularity_simu text,
     num_hpi_scens smallint,
     num_ir_scens smallint,
     macro_timestamp timestamp,
     data_source text,
     forecast_date_roll date,
     forecast_date date,
     hamp_stepup_credit float,
     description text)
     SERVER mysql_server
     OPTIONS (dbname 'rmbs_model');

CREATE FOREIGN TABLE bond_types(
    bond text,
    bond_type crt_bond_type)
    SERVER mysql_server
    OPTIONS(dbname 'crt');

-- #bonds that get written down
-- update securities set identifier='073879R75_A' where identifier='073879R75';
-- update bonds set identifier='073879R75_A' where identifier='073879R75';
-- refresh materialized view factors_history;

CREATE OR REPLACE function list_subprime_data(p_date date, orig_flag bool, VARIADIC p_cusip varchar(9)[])
RETURNS TABLE(v1 float, v2 float, v3 float, duration float, percentile5 float, percentile25 float,
        percentile50 float, percentile75 float, percentile95 float, yield_delta float, wal float,
        io_pv float, po_pv float, rnw float, ir_io_delta float, ir_po_delta float, hpi_delta float, delta_rnw float, delta_mult float,
        v1pv_RnW float, v1_lsdel float, v1_hpidel float, v1_irdel float, pv_FB float) AS $$
DECLARE
  query text;
  opt_constraint text;
BEGIN
IF NOT orig_flag THEN
   opt_constraint := 'AND normalization =''current_notional''';
ELSE
  opt_constraint := '';
END IF;
query:=
'WITH left_table AS (
     WITH temp AS (SELECT cusip, model_version, pv, modDur, delta_yield,
                          wal, pv_io, pv_po, pv_RnW, delta_ir_io, delta_ir_po,
                          delta_hpi, delta_RnW, delta_mult, delta_ir, pv_FB
                   FROM %I
                   WHERE timestamp BETWEEN $1 AND $1 + INTERVAL ''1 day''
                   AND model_id_sub=$3 ' || opt_constraint || ')
          SELECT a.cusip, a.pv as v1, b.pv as v2, c.pv AS v3, a.modDur, c.delta_yield,
                 c.wal, c.pv_io, c.pv_po, c.pv_RnW, c.delta_ir_io, c.delta_ir_po,
                 c.delta_hpi, c.delta_RnW, c.delta_mult, a.pv_RnW as v1pv_RnW,
                 a.delta_mult as v1_lsdel, a.delta_hpi as v1_hpidel, a.delta_ir as v1_irdel, c.pv_FB
          FROM (SELECT * FROM temp WHERE model_version=1) a,
               (SELECT * FROM temp WHERE model_version=2) b,
               (SELECT * FROM temp WHERE model_version=3) c
          WHERE a.cusip = b.cusip AND a.cusip=c.cusip),
     right_table AS (
     WITH temp AS(
          SELECT cusip, PV, percentile
          FROM %I
          WHERE timestamp BETWEEN $1 AND $1 + INTERVAL ''1 day''
                AND model_version=3
                AND model_id_sub=$3
                AND percentile in (5, 25, 50, 75, 95)' || opt_constraint
                 ||')
          SELECT a.cusip, a.PV AS pv5, b.PV AS pv25, c.PV AS pv50, d.PV AS pv75, e.PV AS pv95
          FROM (SELECT cusip, PV FROM temp WHERE percentile=5) a,
               (SELECT cusip, PV FROM temp WHERE percentile=25) b,
               (SELECT cusip, PV FROM temp WHERE percentile=50) c,
               (SELECT cusip, PV FROM temp WHERE percentile=75) d,
               (SELECT cusip, PV FROM temp WHERE percentile=95) e
          WHERE a.cusip=b.cusip AND b.cusip=c.cusip and c.cusip=d.cusip and d.cusip=e.cusip and e.cusip=a.cusip)
SELECT left_table.v1, left_table.v2, left_table.v3,
       left_table.moddur, right_table.pv5, right_table.pv25, right_table.pv50, right_table.pv75, right_table.pv95,
       left_table.delta_yield, left_table.wal, left_table.pv_io, left_table.pv_po, left_table.pv_RnW,
       left_table.delta_ir_io, left_table.delta_ir_po, left_table.delta_hpi, left_table.delta_RnW, left_table.delta_mult,
       left_table.v1pv_RnW, left_table.v1_lsdel, left_table.v1_hpidel, left_table.v1_irdel, left_table.pv_FB
FROM (SELECT unnest($2) AS cusip) l
LEFT JOIN left_table ON left_table.cusip=l.cusip
LEFT JOIN right_table ON left_table.cusip=right_table.cusip';
IF orig_flag THEN
   query := format(query, 'priced_orig_ntl', 'priced_percentiles_orig_ntl');
ELSE
   query := format(query, 'priced', 'priced_percentiles');
END IF;
SET enable_nestloop = off;
RETURN QUERY EXECUTE query USING p_date, p_cusip, latest_sim(p_date);
SET enable_nestloop = on;
END
$$ LANGUAGE plpgsql;

CREATE OR REPLACE function list_crt_data(p_date date, fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(identifier varchar(9), description varchar, model_time timestamp, notional double precision, factor double precision, pv float, duration float4, dm float4, delta_ir float4, delta_economy float4,
  convexity_ir float4, convexity_economy float4, bondtype crt_bond_type, delta numeric, usd_market_value float) as $$
BEGIN
  RETURN QUERY
  SELECT DISTINCT ON (identifier) c.identifier, c.description, a.timestamp, c.notional, c.factor, a.pv, duration_fw, a.dm, "delta.ir", "delta.economy",
  "convexity.ir", "convexity.economy", bond_type, value, c.usd_market_value FROM risk_positions(p_date, 'CRT', fund) c
  LEFT JOIN priced_at_market a on c.identifier = a.cusip
  JOIN crt_model_versions ON model_des=model_version
  LEFT JOIN map_cusip USING (cusip)
  LEFT JOIN bond_types USING (bond)
  LEFT JOIN beta_estimates USING (bond_type)
  WHERE until_date > p_date
  AND timestamp BETWEEN p_date AND p_date + INTERVAL '1 DAY'
  AND date <= greatest(p_date, DATE '2021-02-01')
ORDER BY identifier, until_date ASC, timestamp DESC, date DESC;
END
$$ LANGUAGE plpgsql;

CREATE TABLE swaption_marks(
       dealid varchar(28) REFERENCES swaptions(dealid),
       market_value float,
       delta float,
       gamma float,
       vega float,
       theta float,
       hy_equiv float)

CREATE TABLE subprime_risk(
       date           date,
       figi         varchar(12) NOT NULL,
       pv1            float,
       pv2            float,
       pv3            float,
       modDur         float,
       pv5            float,
       pv25           float,
       pv50           float,
       pv75           float,
       pv95           float,
       delta_yield    float,
       wal            float,
       pv_io          float,
       pv_po          float,
       pv_RnW         float,
       delta_ir_io    float,
       delta_ir_po    float,
       delta_hpi      float,
       delta_RnW      float,
       delta_mult     float,
       v1pv_RnW       float,
       v1_lsdel       float,
       v1_hpidel      float,
       v1_irdel       float,
       pv_FB          float,
       bond_yield     float,
       hy_equiv       float,
       delta_ir       float,
       PRIMARY KEY (date, figi))

CREATE TABLE beta(
        date            date,
        asset_class     beta_type,
        beta            float,
        PRIMARY KEY (date, asset_class))

CREATE TYPE portfolio AS ENUM('CASH', 'CLO', 'CURVE', 'GFS_HELPER_BUSINESS_UNIT',
       'HEDGE_MAC', 'HY', 'IG', 'LQD_TRANCH', 'MORTGAGES', 'OPTIONS',
       'SERCGLLC__SERCGLLC', 'SERCGLTD__SERCGLTD', 'SER_TEST__SER_TEST', 'STRUCTURED',
       'IR', 'TRANCHE');

CREATE TYPE fund AS ENUM('SERCGLLC', 'SERCGLTD', 'SERCGMAST', 'SER_TEST', 'BRINKER', 'BOWDST', 'LIMBO', 'ISOSEL', 'CRSE')

CREATE TYPE strategy AS ENUM(
-- CLO portfolio
'CLOCDSCSH', 'CLO_AAA', 'CLO_BB20', 'CLO_BBB', 'HEDGE_CLO',
-- TRANCHE portfolio
'HYEQY', 'HYMEZ', 'HYSNR', 'HYINX', 'IGEQY', 'IGMEZ', 'IGSNR', 'IGINX', 'BSPK', 'TCSH',
'XOEQY', 'XOMEZ', 'XOINX', 'EUEQY', 'EUMEZ', 'EUSNR', 'EUINX',
-- CURVE portfolio
'IGCURVE', 'IGCVECSH', 'ITRXCURVE', 'ITRXCVCSH', 'HYCURVE', 'XCURVE', 'CVECSH',
-- OPTIONS portfolio
'IGOPTDEL', 'IGPAYER', 'IGREC', 'HYOPTDEL', 'HYPAYER', 'HYREC', 'IGCDSCSH', 'HYCDSCSH', 'COCSH'
-- IR portfolio
'IR', 'IRDEVCSH', 'STEEP', 'FLAT', 'DELTAONE', 'DV01',
-- STRUCTURED portfolio
'STR_MAV', 'STR_MEZZ', 'HEDGE_CSO', 'CSO_TRANCH', 'CSOCDSCSH',
-- MORTGAGES portfolio
'HEDGE_MBS', 'MTG_B4PR', 'MTG_FP', 'MTG_GOOD', 'MTG_IO', 'MTG_LMG', 'MTG_REPO'
'MTG_PR', 'MTG_RW', 'MTG_SD', 'MTG_THRU', 'MBSCDS', 'MBSCDSCSH',
'CRT_LD', 'CRT_SD', 'CRT_LD_JNR', 'CRT_MI',
-- IG portfolio (deprecated)
'IGTCDSCSH', 'IGCURVE', 'IGEQY', 'IGINX', 'IGMEZ', 'IGSNR',
-- HY portfolio (deprecated)
'HYTCDSCSH', 'HYCURVE', 'HYEQY', 'HYINX', 'HYMEZ', 'HYSNR',
-- HEDGE_MAC portfolio
'HEDGE_MAC', 'MACCDSCSH', 'CASH_BASIS', 'SOFR',
-- CASH portfolio
'M_CSH_CASH', 'M_CSH_EXP',
-- GFS_HELPER_BUSINESS_UNIT portfolio
'GFS_TRANSFER_HELPER',
-- UNALLOCATED portfolio
'*',
-- LQD_TRANCH (deprecated)
'LQD_TRANCH')

CREATE TYPE strategy_dirty AS ENUM (
	'M_CLO_BB20',
	'M_CLO_AAA',
	'M_CLO_BBB',
	'M_MTG_IO',
	'M_MTG_THRU',
	'M_MTG_GOOD',
	'M_MTG_B4PR',
	'M_MTG_RW',
	'M_MTG_FP',
	'M_MTG_LMG',
	'M_MTG_SD',
	'M_MTG_PR',
	'M_MTG_CRT_SD',
	'CRT_LD',
	'CRT_LD_JNR',
	'MTG_REPO',
	'HEDGE_CSO',
	'HEDGE_CLO',
	'HEDGE_MAC',
	'HEDGE_MBS',
	'SER_IGSNR',
	'SER_IGMEZ',
	'SER_IGEQY',
	'SER_IGINX',
	'SER_HYSNR',
	'SER_HYMEZ',
	'SER_HYEQY',
	'SER_HYINX',
	'SER_IGCURVE',
	'MBSCDS',
	'IGOPTDEL',
	'HYOPTDEL',
	'SER_ITRXCURVE',
	'M_STR_MEZZ',
	'M_STR_MAV',
	'HYEQY',
	'HYMEZ',
	'HYSNR',
	'HYINX',
	'IGEQY',
	'IGMEZ',
	'IGSNR',
	'IGINX',
	'XOEQY',
	'XOMEZ',
	'XOINX',
	'EUEQY',
	'EUMEZ',
	'EUSNR',
	'EUINX',
	'BSPK',
	'XCURVE',
	'SER_HYCURVE',
	'IGPAYER',
	'IGREC',
	'HYPAYER',
	'HYREC',
	'STEEP',
	'FLAT',
	'DV01',
	'DELTAONE',
	'M_CSH_CASH',
	'M_CSH_EXP',
	'MBSCDSCSH',
	'SER_IGCVECSH',
	'SER_ITRXCVCSH',
	'CVECSH',
	'CSOCDSCSH',
	'IGCDSCSH',
	'HYCDSCSH',
	'CLOCDSCSH',
	'MACCDSCSH',
	'IRDEVCSH',
	'TCSH',
	'IGTCDSCSH',
	'COCSH',
	'*',
	'CASH_BASIS',
    'SOFR',
	'CRT_SD');

CREATE TABLE valuation_reports(
        custacctname text,
        endbookcost float,
        endbookmv float,
        endbooknav float,
        endbookunrealfxgl float,
        endbookunrealincome float,
        endbookunrealmtm float,
        endlocalcost float,
        endlocalmv float,
        endlocalmarketprice float,
        endqty float,
        fund fund Not NULL,
        gfstranid1 text,
        invccy currency,
        invdesc text,
        invid text,
        invtype text,
        knowledgedate timestamp NOT NULL,
        periodenddate date NOT NULL,
        port portfolio,
        strat strategy,
        row integer NOT NULL,
        counterparty varchar(12) REFERENCES counterparties(code),
        invticker varchar(12) NULL,
        pricelist text NULL,
        externalid text NULL,
        PRIMARY KEY(periodenddate, fund, row)
);

CREATE INDEX on valuation_reports (periodenddate);

CREATE TYPE longshort AS ENUM('L', 'S');

CREATE TABLE pnl_reports(
        date date NOT NULL,
        fund fund NOT NULL,
        port portfolio,
        strat strategy,
        longshortindicator longshort,
        custacctname text,
        pricelist text,
        invassettype text,
        invccy currency,
        invdesc text,
        invid text,
        endqty float,
        endlocalmarketprice float,
        dailybookrealmtm float,
        dailybookunrealmtm float,
        dailybookrealfxgl float,
        dailybookunrealfxgl float,
        dailybookrealincome float,
        dailybookunrealincome float,
        dailybookmiscrevexp float,
        dailytotalbookpl float,
        mtdbookrealmtm float,
        mtdbookunrealmtm float,
        mtdbookrealfxgl float,
        mtdbookunrealfxgl float,
        mtdbookrealincome float,
        mtdbookunrealincome float,
        mtdbookmiscrevexp float,
        mtdtotalbookpl float,
        row integer NOT NULL,
        PRIMARY KEY(date, fund, row)
);

CREATE INDEX on pnl_reports (date);

CREATE TYPE clearing_cp AS ENUM('ICE-CREDIT', 'NOT CLEARED', 'LCH-LTD');
CREATE TYPE trade_type AS ENUM('CREDIT_DEFAULT_SWAP', 'SWAPTION', 'TRANCHE');
CREATE TYPE transaction_status AS ENUM('Bilateral', 'Cleared');
CREATE TYPE calendar AS ENUM('Payment-GB,US', 'Payment-US,GB', 'Payment-EU,GB', 'Payment-US');
CREATE TYPE clearing_broker AS ENUM('ML', 'SGFCM', 'BOMLCM', 'WELLSFCM', 'UMB');
CREATE TYpe frequency AS ENUM('Monthly', 'Quarterly');

CREATE TABLE cds_reports(
       date date NOT NULL,
       row integer NOT NULL,
       attachment_point float,
       exhaustion_point float,
       basis day_count,
       "buy/sell" protection,
       ccp clearing_cp,
       calendar calendar,
       cash_account text,
       ccy currency,
       client_ref_id text,
       comments text,
       commission float,
       contractual_definition isda,
       counterparty text REFERENCES counterparties(code),
       cpty_ref_id text,
       created_date timestamp,
       description text,
       effective_date date,
       external_trade_id text,
       factor float,
       fixed_rate float,
       frequency frequency,
       fund fund,
       gtid text,
       geneva_id text,
       independent_amount float,
       independent_perc float,
       maturity_date  date,
       notional float,
       original_gtid text,
       original_notional float,
       period_end_date last_period_convention,
       price float,
       prime_broker clearing_broker,
       product_sub_type swap_type,
       red_code text,
       recovery_rate float,
       remaining_notional float,
       roll_convention bus_day_convention,
       strategy strategy,
       strike float,
       swapswire_id text,
       trade_date date,
       trade_type trade_type,
       transaction_status transaction_status,
       underlying_id text,
       underlying_name text,
       upfront_fee float,
       upfront_fee_date date,
       executing_broker text,
       "1st_cpn_date" date,
       PRIMARY KEY(date, row));

CREATE INDEX on cds_reports (date);

CREATE TYPE mark_list AS (date date,
                      identifier text,
                      "BROKER" float,
                      "BVAL" float,
                      "IDC" float,
                      "MANAGER" float,
                      "MARKIT" float,
                      "PB" float,
                      "PRICESERVE" float,
                      "PRICINGDIRECT" float,
                      "REUTERS" float,
                      "S&P" float);

CREATE OR REPLACE FUNCTION get_mark_matrix(identifier varchar(9)) RETURNS SETOF mark_list
AS $$

import numpy as np
import pandas as pd

source_list = ["BROKER", "BVAL", "IDC", "MANAGER", "MARKIT", "PB",
               "PRICESERVE", "PRICINGDIRECT", "REUTERS", "S&P"]
sql_string = """SELECT identifier, date, source, mark
FROM external_marks_mapped WHERE identifier = $1 ORDER BY date, source"""
plan = plpy.prepare(sql_string, ["varchar"])
df = pd.DataFrame.from_records(plpy.cursor(plan, [identifier]))

df = df.groupby(['date', 'identifier', 'source']).mean().unstack(-1)
df.columns = df.columns.droplevel(level=0)
df = df.reindex(columns=source_list).reset_index()

for t in (df.itertuples(index=False)):
   yield [t[0], t[1]] + [None if np.isnan(v) else v for v in t[2:]]

$$ LANGUAGE plpython3u;

CREATE OR REPLACE VIEW tranche_risk_serenitas AS
SELECT tranche_risk.date, tranche_id as trade_id, b.globeop_id, security_desc, index, series, maturity, orig_attach,
       orig_detach, tranche_risk.notional,
       admin_notional,
       clean_nav as serenitas_clean_nav,
       admin_clean_nav,
       accrued as serenitas_accrued, admin_accrued,
       base_nav AS cpty_nav,
       duration, delta, gamma, theta, theta_amount, tranche_factor,
       tranche_risk.corr_attach, tranche_risk.corr_detach,
       tranche_risk.upfront, tranche_risk.running,
       index_refprice, index_refspread, index_duration, hy_equiv, initial_margin_percentage
FROM tranche_risk
LEFT JOIN LATERAL
(SELECT globeop_id FROM id_mapping WHERE id_mapping.serenitas_id=tranche_id AND date <= tranche_risk.date ORDER by date desc LIMIT 1) b ON true
LEFT JOIN cds ON (tranche_id=id)
FULL JOIN (SELECT invid, periodenddate,
                  sum(endbookunrealincome) AS admin_accrued,
                  sum(endbooknav-endbookunrealincome) AS admin_clean_nav,
                  sum(endqty) AS admin_notional
           FROM valuation_reports GROUP BY invid, periodenddate) a
     ON (NULLIF(substring(invid FROM '\D{3}[0]*(\d*)K00SCLMA'), '')::integer IS NOT DISTINCT FROM b.globeop_id AND periodenddate=tranche_risk.date)
LEFT JOIN index_version ON (security_id=redindexcode)
LEFT JOIN external_marks_deriv ON cpty_id=identifier AND external_marks_deriv.date=tranche_risk.date
WHERE fund='SERCGMAST'
ORDER BY index, series, orig_attach;

CREATE OR REPLACE VIEW ir_swaption_risk_serenitas AS
SELECT ir_swaption_risk.date, swpt_id as trade_id, swaptions.globeop_id, security_desc, maturity,
       admin_notional,
       pv as serenitas_pv,
       admin_pv,
       base_nav AS cpty_nav,
       vol, vol_type, "DV01", "IRGamma1bp", vega
       FROM ir_swaption_risk
LEFT JOIN swaptions ON (swpt_id=id)
FULL JOIN (SELECT invid, periodenddate,
                  sum(endbooknav) AS admin_pv,
                  sum(endqty) AS admin_notional
           FROM valuation_reports GROUP BY invid, periodenddate) a
     ON (NULLIF(substring(invid FROM '\D{3}[0]*(\d*)K00SCLMA'), '')::integer=swaptions.globeop_id AND periodenddate=ir_swaption_risk.date)
LEFT JOIN external_marks_deriv ON cpty_id=identifier AND external_marks_deriv.date=ir_swaption_risk.date
WHERE fund='SERCGMAST'
ORDER BY ir_swaption_risk.date DESC;

CREATE OR REPLACE VIEW ir_swaption_risk_bowdst AS
SELECT ir_swaption_risk.date, swpt_id as trade_id, swaptions.globeop_id, security_desc, maturity,
       admin_notional,
       pv as serenitas_pv,
       admin_pv,
       base_nav AS cpty_nav,
       vol, vol_type, "DV01", "IRGamma1bp", vega
       FROM ir_swaption_risk
LEFT JOIN swaptions ON (swpt_id=id)
FULL JOIN (SELECT invid, periodenddate,
                  sum(endbooknav) AS admin_pv,
                  sum(endqty) AS admin_notional
           FROM valuation_reports GROUP BY invid, periodenddate) a
     ON (NULLIF(substring(invid FROM '\D{3}[0]*(\d*)K00HEEAD'), '')::integer=swaptions.globeop_id AND periodenddate=ir_swaption_risk.date)
LEFT JOIN external_marks_deriv ON cpty_id=identifier AND external_marks_deriv.date=ir_swaption_risk.date
WHERE fund='BOWDST'
ORDER BY ir_swaption_risk.date DESC;

-- bony reports version
-- CREATE OR REPLACE VIEW tranche_risk_bowdst AS
-- SELECT tranche_risk.date, tranche_id as trade_id, security_desc, index, series, maturity, orig_attach,
--        orig_detach, tranche_risk.notional,
--        admin_notional,
--        clean_nav as serenitas_clean_nav,
--        admin_clean_nav,
--        accrued as serenitas_accrued,
--        NULL AS admin_accrued,
--        base_nav AS cpty_nav,
--        duration, delta, gamma, theta, theta_amount, tranche_factor,
--        tranche_risk.corr_attach, tranche_risk.corr_detach,
--        tranche_risk.upfront, tranche_risk.running,
--        index_refprice, index_refspread, index_duration, hy_equiv, initial_margin_percentage
-- FROM tranche_risk
-- LEFT JOIN cds ON (tranche_id=id)
-- LEFT JOIN (SELECT as_of_date, link_ref, (CASE WHEN coupon_rate=0 THEN current_notional ELSE -current_notional END) AS admin_notional, base_market_value AS admin_clean_nav FROM bowdst_val WHERE security_description_1 LIKE 'TR%NCH%' AND abs(base_market_value) > 1.0) b ON link_ref=format('SCCDS%s',tranche_id) AND as_of_date=tranche_risk.date
-- LEFT JOIN index_version ON (security_id=redindexcode)
-- LEFT JOIN external_marks_deriv ON cpty_id=identifier AND external_marks_deriv.date=tranche_risk.date
-- WHERE fund='BOWDST'
-- ORDER BY index, series, orig_attach;

CREATE OR REPLACE VIEW tranche_risk_bowdst AS
SELECT tranche_risk.date, tranche_id as trade_id, b.globeop_id, security_desc, index, series, maturity, orig_attach,
       orig_detach, tranche_risk.notional,
       admin_notional,
       clean_nav as serenitas_clean_nav,
       admin_clean_nav,
       accrued as serenitas_accrued,
       admin_accrued,
       base_nav AS cpty_nav,
       duration, delta, gamma, theta, theta_amount, tranche_factor,
       tranche_risk.corr_attach, tranche_risk.corr_detach,
       tranche_risk.upfront, tranche_risk.running,
       index_refprice, index_refspread, index_duration, hy_equiv, initial_margin_percentage
FROM tranche_risk
LEFT JOIN LATERAL
(SELECT globeop_id FROM id_mapping WHERE id_mapping.serenitas_id=tranche_id AND date <= tranche_risk.date ORDER by date desc LIMIT 1) b ON true
LEFT JOIN cds ON (tranche_id=id)
FULL JOIN (SELECT invid, periodenddate,
                  sum(endbookunrealincome) AS admin_accrued,
                  sum(endbooknav-endbookunrealincome) AS admin_clean_nav,
                  sum(endqty) AS admin_notional
           FROM valuation_reports GROUP BY invid, periodenddate) a
     ON (NULLIF(substring(invid FROM '\D{3}[0]*(\d*)K00HEEAD'), '')::integer=b.globeop_id AND periodenddate=tranche_risk.date)
LEFT JOIN index_version ON (security_id=redindexcode)
LEFT JOIN external_marks_deriv ON cpty_id=identifier AND external_marks_deriv.date=tranche_risk.date
WHERE fund='BOWDST'
ORDER BY index, series, orig_attach;

CREATE OR REPLACE VIEW tranche_risk_brinker AS
SELECT tranche_risk.date, tranche_id as trade_id, security_desc, index, series, maturity, orig_attach,
       orig_detach, tranche_risk.notional,
       admin_notional,
       clean_nav as serenitas_clean_nav,
       admin_clean_nav,
       accrued as serenitas_accrued,
       NULL AS admin_accrued,
       base_nav AS cpty_nav,
       duration, delta, gamma, theta, theta_amount, tranche_factor,
       tranche_risk.corr_attach, tranche_risk.corr_detach,
       tranche_risk.upfront, tranche_risk.running,
       index_refprice, index_refspread, index_duration, hy_equiv, initial_margin_percentage
FROM tranche_risk
LEFT JOIN cds ON (tranche_id=id)
LEFT JOIN (SELECT accounting_date, security_id, quantity * (CASE WHEN long_short_indicator = 'S' THEN 1. ELSE -1. END) AS admin_notional, (local_market_value - quantity) * fx_rate AS admin_clean_nav
FROM bbh_val WHERE sub_security_type_code ='CXT' AND interest_rate IS NOT NULL) b ON b.security_id=format('SCCDS%s', tranche_id) AND accounting_date=tranche_risk.date
LEFT JOIN index_version ON (cds.security_id=redindexcode)
LEFT JOIN external_marks_deriv ON cpty_id=identifier AND external_marks_deriv.date=tranche_risk.date
WHERE fund='BRINKER'
ORDER BY index, series, orig_attach;

CREATE OR REPLACE FUNCTION tranche_risk_agg(p_date date, p_fund fund DEFAULT 'SERCGMAST'::fund)
RETURNS TABLE(date date, security_desc varchar(32), index index_type, series smallint, admin_notional float, admin_clean_nav float,
maturity date, serenitas_notional float, tranche_factor float, running float, serenitas_clean_nav float, serenitas_accrued float, initial_margin float, theta float, theta_amount float, duration float, delta float, gamma float, hy_equiv float, upfront float, index_refprice float, index_refspread float, index_duration float, orig_attach smallint, orig_detach smallint) AS $$
DECLARE
    query text;
    fund text;
BEGIN
IF p_fund = 'SERCGMAST' THEN
   fund := 'serenitas';
ELSE
    fund := lower(p_fund::text);
END IF;
query := 'SELECT date, security_desc, index, series, sum(admin_notional),
                 sum(admin_clean_nav), maturity, sum(notional),
                 avg(tranche_factor), avg(running),
                 sum(serenitas_clean_nav),
                 sum(serenitas_accrued),
                 sum(initial_margin_percentage * tranche_factor * abs(notional)/100),
                 avg(theta), sum(theta_amount), avg(duration), avg(delta),
                 avg(gamma), sum(hy_equiv), avg(upfront), avg(index_refprice),
                 avg(index_refspread), avg(index_duration),
                 orig_attach, orig_detach
          FROM tranche_risk_%I
          GROUP BY date, index, security_desc, series, orig_attach, orig_detach, maturity
	      HAVING date=$1
          ORDER BY index, series';
query := format(query, fund);
RETURN QUERY EXECUTE query USING p_date;
END
$$ LANGUAGE plpgsql;


CREATE OR REPLACE VIEW tranche_risk_master AS
SELECT tranche_risk.date, tranche_id AS trade_id, fund, security_desc, index, series, maturity, orig_attach,
       orig_detach, tranche_risk.notional,
       clean_nav * coalesce(fx, 1.) as serenitas_clean_nav,
       accrued * coalesce(fx, 1.) as serenitas_accrued,
       nav AS cpty_nav,
       duration, delta, gamma, theta, tranche_factor,
       tranche_risk.corr_attach, tranche_risk.corr_detach,
       tranche_risk.upfront, tranche_risk.running,
       index_refprice, index_refspread, index_duration, initial_margin_percentage, ia as cpty_ia, indexfactor
FROM tranche_risk
LEFT JOIN cds ON (tranche_id=id)
LEFT JOIN index_version ON (security_id=redindexcode)
LEFT JOIN (SELECT date, 'EUR'::currency AS currency, eurusd AS fx FROM fx) fx USING (date, currency)
LEFT JOIN external_marks_deriv on cpty_id=identifier and external_marks_deriv.date=tranche_risk.date
ORDER BY date desc, index, series, orig_attach;


CREATE TABLE fcm_im(
       date date NOT NULL,
       account text NOT NULL, -- REFERENCES accounts(cash_account)
       currency currency NOT NULL,
       amount float NOT NULL,
       PRIMARY KEY(date, account, currency)
);

CREATE TABLE fcm_moneyline(
       date date NOT NULL,
       account text NOT NULL,
       currency currency NOT NULL,
       beginning_balance float NOT NULL,
       cds_initial_coupon float NOT NULL,
       cds_reset_to_par float NOT NULL,
       pai float NOT NULL,
       clearing_fees float NOT NULL,
       transaction_fees float NOT NULL,
       net_dep_withdraw float NOT NULL,
       ending_balance float NOT NULL,
       account_value_market float NOT NULL,
       realized_pnl float NOT NULL,
       current_im float NOT NULL,
       current_excess_deficit float NOT NULL,
       PRIMARY KEY (date, account, currency)
);

CREATE TABLE strategy_im(
       date date NOT NULL,
       broker text NOT NULL,
       strategy strategy NOT NULL,
       amount float NOT NULL,
       currency currency NOT NULL,
       fund fund NOT NULL,
       PRIMARY KEY (date, fund, broker, strategy, currency)
)

CREATE TYPE cash_rate AS ENUM('FED_FUND', '1M_LIBOR', '3M_LIBOR', 'SOFR_RATE');

CREATE OR REPLACE VIEW swaption_trades AS
SELECT swaptions.id,
       dealid,
       termination_date AS trade_date,
       fee_payment_date AS settle_date,
       termination_amount AS notional,
       security_desc,
       security_id,
       CASE WHEN termination_cp=cp_code THEN
         'Termination'
       ELSE
         'Assignment'
       END AS trade_type,
       folder,
       portfolio,
       fund,
       termination_cp AS cp_code,
       name,
       option_type,
       expiration_date,
       strike,
       NOT buysell AS buysell,
       -termination_fee AS fee,
       deal_type
FROM terminations RIGHT JOIN swaptions USING (dealid)
LEFT JOIN counterparties ON termination_cp = code
WHERE termination_date IS NOT NULL
UNION ALL (
SELECT id,
       dealid,
       trade_date,
       settle_date,
       notional,
       security_desc,
       security_id,
       'New' AS trade_type,
       folder,
       portfolio,
       fund,
       cp_code,
       name,
       option_type,
       expiration_date,
       strike,
       buysell,
       notional * price / 100 * (2* buysell::integer -1.) * COALESCE(indexfactor / 100, 1.),
       (CASE WHEN swap_type='CD_INDEX_OPTION' THEN 'CreditSwaption' ELSE 'IRSwaption' END)::deal_type
FROM swaptions JOIN counterparties ON cp_code = code
               LEFT JOIN index_version ON security_id = redindexcode) ORDER BY trade_date DESC;

CREATE OR REPLACE VIEW cds_trades AS
SELECT cds.id,
       dealid,
       termination_date AS trade_date,
       termination_amount AS notional,
       security_desc,
       security_id,
       CASE WHEN termination_cp=cp_code THEN
         'Termination'
       ELSE
         'Assignment'
       END AS trade_type,
       folder,
       fund,
       termination_cp AS cp_code,
       name,
       orig_attach,
       orig_detach,
       attach,
       detach,
       CASE WHEN protection = 'Buyer' THEN
         'Seller'::protection
       ELSE
         'Buyer'::protection
       END AS protection,
       termination_fee AS upfront,
       terminations.traded_level
FROM terminations RIGHT JOIN cds USING (dealid)
LEFT JOIN counterparties on termination_cp=code
WHERE termination_date is NOT NULL
UNION ALL (
SELECT id,
       dealid,
       trade_date,
       notional,
       security_desc,
       security_id,
       'New',
       folder,
       fund,
       cp_code,
       name,
       orig_attach,
       orig_detach,
       attach,
       detach,
       protection,
       upfront,
       traded_level
FROM cds JOIN counterparties ON cp_code = code) ORDER BY trade_date DESC, folder;

CREATE TABLE curve_risk(
       date date NOT NULL,
       strategy cds_strat,
       "VaR" float,
       currency currency,
       fund fund,
       PRIMARY KEY (date, strategy, fund))

CREATE OR REPLACE VIEW tranche_pnl AS
WITH temp AS (
   SELECT  date, tranche_id, fund, clean_nav + accrued - lag(clean_nav+accrued, -1, -cds.upfront) over (partition by tranche_id ORDER BY date DESC) AS daily_pnl
   FROM tranche_risk JOIN cds ON tranche_id=id
)
SELECT date, fund, tranche_id, daily_pnl, sum(daily_pnl) OVER (PARTITION BY tranche_id, date_trunc('month', date) ORDER BY date) AS mtd_pnl FROM temp;


create table id_mapping(
       date date not null,
       trade_type text not null,
       serenitas_id int not null,
       globeop_id int not null,
       PRIMARY KEY (date, trade_type, serenitas_id)
);

CREATE TABLE tranche_cashflows(
       date date NOT NULL,
       tranche_id integer NOT NULL,
       principal float,
       accrued float,
       currency currency,
       PRIMARY KEY (date, tranche_id)
);

CREATE TABLE beta_crt(
       date date NOT NULL,
       strategy bond_strat NOT NULL ,
       beta_crt float,
       PRIMARY KEY (date, strategy)
);


CREATE OR REPLACE VIEW bond_settlements AS SELECT bt.id::text AS id,
            bt.settle_date,
            bt.fund::fund,
            bt.cp_code::text,
            'BOND' AS asset_class,
            a.name::text as account,
            'USD'::currency AS currency,
                CASE
                    WHEN bt.buysell THEN - bt.net_amount::numeric(11,2)
                    WHEN NOT bt.buysell THEN bt.net_amount::numeric(11,2)
                    ELSE NULL::numeric(11,2)
                END AS payment_amount
           FROM bond_trades bt LEFT JOIN accounts a ON bt.account=a.code
          WHERE bt.tradeid IS NOT NULL;

CREATE OR REPLACE VIEW tranche_settlements AS SELECT
    ct.id::text,
    ct.settle_date,
    ct.fund::fund,
    ct.cp_code::text,
    'TRANCHE'::text AS asset_class,
    'OTC'::text AS account,
    ct.currency::currency,
    ct.upfront::numeric(11,2) AS payment_amount
  FROM cds_trades ct
  WHERE orig_attach IS NOT NULL;


CREATE OR REPLACE VIEW tranchepayment_settlements AS SELECT tc.tranche_id::TEXT AS id, tc.date AS settle_date,
        cds.fund::fund, cds.cp_code::text, 'TRANCHE_CF' AS asset_class,
        'OTC'::text AS account, tc.currency::currency,
        (COALESCE(tc.principal,0) + COALESCE(tc.accrued,0))::numeric(11,2) AS payment_amount
        FROM tranche_cashflows tc LEFT JOIN cds ON tc.tranche_id=cds.id ;



CREATE OR REPLACE VIEW swaption_settlements AS SELECT st.id::text AS id,
            st.settle_date,
            st.fund::fund,
            st.cp_code::text,
            'SWAPTION' AS asset_class,
            'OTC'::text AS account,
            'USD'::currency AS currency,
            - st.fee::numeric(11,2) AS payment_amount
           FROM swaption_trades st;

CREATE OR REPLACE VIEW trs_settlements AS SELECT tt.id::text,
            tt.settle_date,
            tt.fund::fund,
            tt.cp_code::text,
            'TRS' AS asset_class,
            'OTC'::text AS account,
            'USD'::currency AS currency,
            tt.upfront::numeric(11,2) AS payment_amount
           FROM trs_trades tt;

CREATE OR REPLACE VIEW spot_settlements AS SELECT st.dealid::text AS dealid,
            st.settle_date,
            st.fund::fund,
            st.cp_code::text,
            'SPOT' AS asset_class,
            a.name AS account,
            unnest(ARRAY[st.buy_currency, st.sell_currency])::currency AS currency,
            unnest(ARRAY[st.buy_amount, - st.sell_amount])::numeric(11,2) AS amount
           FROM spots st LEFT JOIN accounts2 a USING (cash_account);

CREATE OR REPLACE VIEW fxswap_settlements AS SELECT ft.dealid::text,
            unnest(ARRAY[ft.near_settle_date, ft.near_settle_date, ft.far_settle_date, ft.far_settle_date]) AS settle_date,
            ft.fund::fund,
            ft.cp_code::text,
            'SPOT' AS asset_class,
            a.name AS account,
            unnest(ARRAY[ft.near_buy_currency, ft.near_sell_currency, ft.far_buy_currency, ft.far_sell_currency])::currency AS currency,
            unnest(ARRAY[ft.near_buy_amount, - ft.near_sell_amount, ft.far_buy_amount, - ft.far_sell_amount])::numeric(11,2) AS amount
           FROM fx_swaps ft LEFT JOIN accounts2 a USING (cash_account);



CREATE OR REPLACE VIEW equityoption_settlements AS SELECT eo.id::text AS id,
            eo.settle_date,
            eo.fund::fund,
            eo.cp_code::text,
            'EQUITYOPTION' AS asset_class,
            'OTC'::text AS account,
            'USD'::currency AS currency,
            - eo.fee::numeric(11,2) AS payment_amount
           FROM equityoption_trades eo;


CREATE OR REPLACE VIEW payment_settlements
AS SELECT t.settle_date,
    t.fund,
    c.name,
    t.cp_code,
    t.asset_class,
    t.account,
    t.currency,
    sum(t.payment_amount)::numeric(11,2) AS payment_amount,
    array_agg(t.id) AS ids
   FROM ( SELECT * FROM bond_settlements
        UNION
         SELECT * FROM tranche_settlements
        UNION
         SELECT * FROM tranchepayment_settlements
        UNION
         SELECT * FROM swaption_settlements
        UNION
         SELECT * FROM spot_settlements
        UNION
         SELECT * FROM fxswap_settlements
         UNION
         SELECT * FROM trs_settlements
         UNION
         SELECT * FROM equityoption_settlements) t
     LEFT JOIN counterparties c on t.cp_code=c.code
  GROUP BY t.settle_date, t.fund, c.name, t.cp_code, t.asset_class, t.currency, t.account
  ORDER BY t.settle_date DESC, t.fund, c.name, t.asset_class, t.currency;


CREATE TABLE equities (
	id serial4 NOT NULL,
	dealid varchar(28) NULL GENERATED ALWAYS AS ((('EQ'::text || id::text))) STORED,
	lastupdate timestamp NULL DEFAULT now(),
	"action" action NOT NULL,
	folder future_strat NOT NULL,
	trade_date date NOT NULL,
	settle_date date NOT NULL,
	buysell bool NOT NULL,
	bbg_ticker varchar(32) NOT NULL,
	quantity float8 NOT NULL,
	price float8 NOT NULL,
	commission float8 NULL,
	security_desc varchar(32) NOT NULL,
	"currency" currency NOT NULL,
	exchange varchar(3) NOT NULL,
	"fund" fund NOT NULL DEFAULT 'SERCGMAST'::fund,
	account_code text NOT NULL DEFAULT 'IB'::text,
	CONSTRAINT equities_dealid_key UNIQUE (dealid),
	CONSTRAINT equities_pkey PRIMARY KEY (id),
	CONSTRAINT equities_account_code_fkey FOREIGN KEY (account_code) REFERENCES accounts(code)
);

CREATE TYPE exercise_type AS ENUM ('European', 'American');

CREATE TYPE equity_option_strat AS ENUM ('VOLRV');

CREATE TABLE equityoptions (
	id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,
	dealid varchar(28) NULL GENERATED ALWAYS AS ((('EQOPT_'::text || id::text))) STORED,
	"fund" "fund" NOT NULL,
	lastupdate timestamp NULL DEFAULT now(),
	"action" "action" NOT NULL,
	"portfolio" "portfolio" NOT NULL,
	folder text NOT NULL,
	cash_account text NOT NULL,
	cp_code text NOT NULL,
	trade_date date NOT NULL,
	settle_date date NOT NULL,
	expiration_date date NOT NULL,
	buysell bool NOT NULL,
	quantity float8 NOT NULL,
	identifier text NOT NULL,
	putcall bool NOT NULL,
	strike float8 NOT NULL,
	exercise_type exercise_type NOT NULL,
	price float8 NOT NULL,
	"currency" "currency" NOT NULL,
	clearing_facility text NULL,
	"settlement_type" "settlement_type" NOT NULL,
	initial_margin float8 NULL,
	cpty_id text NULL,
	figi text NULL,
  globeop_id int4 NULL,
  underlyingshares int NOT NULL,
	CONSTRAINT equity_options2_pkey PRIMARY KEY (id),
	CONSTRAINT equity_options2_cash_account_fkey FOREIGN KEY (cash_account) REFERENCES accounts2(cash_account) ON UPDATE CASCADE,
	CONSTRAINT equity_options2_cp_code_fkey FOREIGN KEY (cp_code) REFERENCES counterparties(code) ON UPDATE CASCADE
);


CREATE OR REPLACE VIEW equityoption_trades AS
SELECT eo.id,
       eo.dealid,
       t.termination_date AS trade_date,
       t.fee_payment_date AS settle_date,
       t.termination_amount AS quantity,
       eo.bbg_ticker,
       eo.figi,
       CASE WHEN t.termination_cp=eo.cp_code THEN
         'Termination'
       ELSE
         'Assignment'
       END AS trade_type,
       eo.folder,
       eo.portfolio,
       eo.fund,
       t.termination_cp AS cp_code,
       cps.name,
       eo.putcall,
       eo.expiration_date,
       eo.strike,
       NOT eo.buysell AS buysell,
       -t.termination_fee AS fee,
       eo.underlyingshares AS underlyingshares
FROM terminations t RIGHT JOIN equityoptions eo USING (dealid)
LEFT JOIN counterparties cps ON termination_cp = code
WHERE termination_date IS NOT NULL
UNION ALL (
SELECT eo.id,
       eo.dealid,
       eo.trade_date,
       eo.settle_date,
       eo.quantity,
       eo.bbg_ticker,
       eo.figi,
       'New' AS trade_type,
       eo.folder,
       eo.portfolio,
       eo.fund,
       eo.cp_code,
       cps.name,
       eo.putcall,
       eo.expiration_date,
       eo.strike,
       eo.buysell,
       eo.quantity * eo.underlyingshares * price * (2* buysell::integer -1.)
       eo.underlyingshares
FROM equityoptions eo JOIN counterparties cps ON cp_code = code) ORDER BY trade_date DESC;

CREATE TABLE bond_tickets (
	bbg_ticket_id text NOT NULL,
	"Match" text NULL,
	"Side" text NULL,
	"Security" text NULL,
	"Quantity" int8 NULL,
	"Price (Dec)" float8 NULL,
	"CP" text NULL,
	"STP Status" text NULL,
	"Trade Dt" date NULL,
	"SetDt" date NULL,
	"Curncy" text NULL,
	"Principal" float8 NULL,
	"Net" float8 NULL,
	"Acc Int" float8 NULL,
	"Block Status" text NULL,
	"Brkr" text NULL,
	"BrkrName" text NULL,
	"BrkrName.1" text NULL,
	"FIGI" text NULL,
	"Cusip" text NULL,
	"Curr Face" text NULL,
  "Mat Dt" date NULL,
  "C/Clear USI/UTI" text null,
  "Client FCM" text null,
	CONSTRAINT bond_tickets_pk PRIMARY KEY (bbg_ticket_id)
);
CREATE INDEX ix_bond_tickets_index ON bond_tickets USING btree (bbg_ticket_id);

CREATE TABLE cds_tickets (
	bbg_ticket_id text NOT NULL,
	"Match" text NULL,
	"Side" text NULL,
	"Security" text NULL,
	"Quantity" int8 NULL,
	"Price (Dec)" float8 NULL,
	"CP" text NULL,
	"STP Status" text NULL,
	"Trade Dt" text NULL,
	"SetDt" text NULL,
	"Curncy" text NULL,
	"Principal" float8 NULL,
	"Net" float8 NULL,
	"Acc Int" float8 NULL,
	"Account" text NOT NULL,
	"Client FCM" text NOT NULL,
	"Block Status" text NULL,
	"Red Code" text NULL,
	"Cusip" text NULL,
	"Brkr" text NULL,
	"Mat Dt" text NULL,
	"Coupon" int8 NULL,
	CONSTRAINT cds_tickets_pk PRIMARY KEY (bbg_ticket_id, "Account", "Client FCM")
);

CREATE TABLE cds_submission (
	id int4 NOT NULL GENERATED ALWAYS AS IDENTITY,
	tradeid int4 NOT NULL,
	"action" action NOT NULL,
	submit_date timestamptz NOT NULL DEFAULT now(),
	"status" status NOT NULL DEFAULT 'Pending'::status,
	CONSTRAINT cds_submission_pkey PRIMARY KEY (id),
	CONSTRAINT cds_submission_allocation_id_fkey FOREIGN KEY (tradeid) REFERENCES cds(id) ON DELETE CASCADE
);


CREATE TABLE mtm_submissions (
	ticketid text NOT NULL,
	executed date NULL,
	dealid text NOT NULL,
	dealtype text NULL,
	cp_code text NULL,
	swaptype text NULL,
	cpty_ref text NULL,
	CONSTRAINT mtm_submissions_pk PRIMARY KEY (ticketid, dealid)
);

CREATE TABLE quantifi_bond_proxy (
	product_name text NOT NULL,
	trade_date date NOT NULL,
	"asset_class" text NOT NULL,
	"fund" "fund" NOT NULL,
	notional float8 NULL,
	terminated bool NULL DEFAULT false,
	CONSTRAINT quantifi_bond_proxy_pk PRIMARY KEY (product_name, trade_date, asset_class, fund)
);


CREATE OR REPLACE FUNCTION list_compressed_quantifi(start_from date)
 RETURNS TABLE(index text, tradeid text, fund fund, clean_folder text, portfolio portfolio, security_id varchar(12), notional double precision, fcm text)
 LANGUAGE plpgsql
AS $function$
begin
	return query
	SELECT LEFT(split_part(security_desc, ' ', 2),2) AS "index", imm.tradeid, a.fund, pfm.clean_folder, pfm.portfolio, a.security_id, a.notional, a.fcm
FROM (
SELECT cds.fund, account_code AS fcm, cds.security_id, max(security_desc) AS security_desc, maturity, folder,
SUM(cds.notional * (CASE WHEN protection='Buyer' THEN 1 ELSE -1 END)) AS notional FROM cds
WHERE swap_type='CD_INDEX' AND trade_date<=start_from AND maturity > start_from
GROUP BY cds.security_id, maturity, cds.folder, cds.fund, account_code) a
LEFT JOIN portfolio_folder_mapping pfm ON replace(a.folder::text, 'SER_', '')=pfm.clean_folder
LEFT JOIN index_maturity_markit imm ON (a.SECURITY_id, a.maturity) = (imm.redindexcode, imm.maturity) WHERE active AND abs(a.notional) >1;
end;
$function$
;

CREATE TABLE fx_tickets (
	bbg_ticket_id text NOT NULL,
	"Message Type" text NULL,
	"Deal Type" text NULL,
	"Side" text NULL,
	"Product" text NULL,
	"Trans Type" text NULL,
	"Revision Version" text NULL,
	"Trade ID" text NULL,
	"Batch ID" text NULL,
	"Trader Deal Code" text NULL,
	"Trader UUID" text NULL,
	"Trader Name" text NULL,
	"Counterparty UUID" text NULL,
	"Counterparty Trader Name" text NULL,
	"Date Of Deal" text NULL,
	"Time Of Deal" text NULL,
	"Trade Date" text NULL,
	"Date Confirmed" text NULL,
	"Time Confirmed" text NULL,
	"Counterparty Deal Code" text NULL,
	"Counterparty Name" text NULL,
	"User Identifier 1" text NULL,
	"User Identifier 2" text NULL,
	"User Identifier 3" text NULL,
	"User Identifier 4" text NULL,
	"Currency 1" text NULL,
	"Currency 2" text NULL,
	"Amount Dealt" text NULL,
	"Dealt Currency" text NULL,
	"Counter Amount" text NULL,
	"Counter Currency" text NULL,
	"Forward Points Near" text NULL,
	"Far Amount Dealt" text NULL,
	"Far Currency Dealt" text NULL,
	"Far Counter Amount" text NULL,
	"Far Counter Currency" text NULL,
	"Forward Points Far" text NULL,
	"Spot Basis Rate" text NULL,
	"Deposit Rate" text NULL,
	"Day Count Type" text NULL,
	"New or Roll" text NULL,
	"Volume Of Interest" text NULL,
	"Exchange Rate Period 1" text NULL,
	"Value Date Period 1 Currency 1" text NULL,
	"Tenor Period 1" text NULL,
	"Fixing Date Period 1" text NULL,
	"Fixing Source Period 1" text NULL,
	"Settle Currency" text NULL,
	"Swap Rate" text NULL,
	"Exchange Rate Period 2" text NULL,
	"Value Date Period 2 Currency 1" text NULL,
	"Tenor Period 2" text NULL,
	"Fixing Date Period 2" text NULL,
	"Fixing Source Period 2" text NULL,
	"Split Tenor Currency 1" text NULL,
	"Split Value Date Currency 1" text NULL,
	"Split Tenor Currency 2" text NULL,
	"Split Value Date Currency 2" text NULL,
	"Comment Text" text NULL,
	"Note Name 1" text NULL,
	"Note Text 1" text NULL,
	"Note Name 2" text NULL,
	"Note Text 2" text NULL,
	"Note Name 3" text NULL,
	"Note Text 3" text NULL,
	"Note Name 4" text NULL,
	"Note Text 4" text NULL,
	"Note Name 5" text NULL,
	"Note Text 5" text NULL,
	"Comp Quote 1" text NULL,
	"Comp Deal Code 1" text NULL,
	"Supplementary Cost 1" text NULL,
	"Comp Quote 2" text NULL,
	"Comp Deal Code 2" text NULL,
	"Supplementary Cost 2" text NULL,
	"Comp Quote 3" text NULL,
	"Comp Deal Code 3" text NULL,
	"Supplementary Cost 3" text NULL,
	"Comp Quote 4" text NULL,
	"Comp Deal Code 4" text NULL,
	"Supplementary Cost 4" text NULL,
	"Comp Quote 5" text NULL,
	"Comp Deal Code 5" text NULL,
	"Supplementary Cost 5" text NULL,
	"Buyer Near Trader UUID" text NULL,
	"Buyer Near Deal Code" text NULL,
	"Seller Near Trader UUID" text NULL,
	"Seller Near Deal Code" text NULL,
	"Buyer Far Trader UUID" text NULL,
	"Buyer Far Deal Code" text NULL,
	"Seller Far Trader UUID" text NULL,
	"Seller Far Deal Code" text NULL,
	"Broker Trader UUID" text NULL,
	"Broker Deal Code" text NULL,
	"Broker Name" text NULL,
	"Portfolio" text NULL,
	"ALOC Account 1" text NULL,
	"ALOC Amount 1" text NULL,
	"ALOC Direction 1" text NULL,
	"ALOC Custodian 1" text NULL,
	"ALOC Prime Broker 1" text NULL,
	"ALOC Account 2" text NULL,
	"ALOC Amount 2" text NULL,
	"ALOC Direction 2" text NULL,
	"ALOC Custodian 2" text NULL,
	"ALOC Prime Broker 2" text NULL,
	"ALOC Account 3" text NULL,
	"ALOC Amount 3" text NULL,
	"ALOC Direction 3" text NULL,
	"ALOC Custodian 3" text NULL,
	"ALOC Prime Broker 3" text NULL,
	"ALOC Account 4" text NULL,
	"ALOC Amount 4" text NULL,
	"ALOC Direction 4" text NULL,
	"ALOC Custodian 4" text NULL,
	"ALOC Prime Broker 4" text NULL,
	"ALOC Account 5" text NULL,
	"ALOC Amount 5" text NULL,
	"ALOC Direction 5" text NULL,
	"ALOC Custodian 5" text NULL,
	"ALOC Prime Broker 5" text NULL,
	"ALOC Account 6" text NULL,
	"ALOC Amount 6" text NULL,
	"ALOC Direction 6" text NULL,
	"ALOC Custodian 6" text NULL,
	"ALOC Prime Broker 6" text NULL,
	"ALOC Account 7" text NULL,
	"ALOC Amount 7" text NULL,
	"ALOC Direction 7" text NULL,
	"ALOC Custodian 7" text NULL,
	"ALOC Prime Broker 7" text NULL,
	"ALOC Account 8" text NULL,
	"ALOC Amount 8" text NULL,
	"ALOC Direction 8" text NULL,
	"ALOC Custodian 8" text NULL,
	"ALOC Prime Broker 8" text NULL,
	"ALOC Account 9" text NULL,
	"ALOC Amount 9" text NULL,
	"ALOC Direction 9" text NULL,
	"ALOC Custodian 9" text NULL,
	"ALOC Prime Broker 9" text NULL,
	"ALOC Account 10" text NULL,
	"ALOC Amount 10" text NULL,
	"ALOC Direction 10" text NULL,
	"ALOC Custodian 10" text NULL,
	"ALOC Prime Broker 10" text NULL,
	"Reference Spot Rate" text NULL,
	"Reference Rate Period 1" text NULL,
	"Reference Rate Period 2" text NULL,
	"Pay Currency" text NULL,
	"Pay SWIFT Code" text NULL,
	"Pay Account Number" text NULL,
	"Pay Bank" text NULL,
	"Pay Branch" text NULL,
	"Pay Beneficiary" text NULL,
	"Pay Special Instructions" text NULL,
	"Receiving Currency" text NULL,
	"Receiving SWIFT Code" text NULL,
	"Receiving Account Number" text NULL,
	"Receiving Bank" text NULL,
	"Receiving Branch" text NULL,
	"Receiving Beneficiary" text NULL,
	"Receiving Special Instructions" text NULL,
	"Spot Rate Mid" text NULL,
	"All-in Rate Near Leg Mid" text NULL,
	"Near Leg Forward Point Mid" text NULL,
	"All-in Rate Far Leg Mid" text NULL,
	"Far Leg Forward Point Mid" text NULL,
	"USI Namespace" text NULL,
	"USI ID" text NULL,
	"USI ID Near" text NULL,
	"USI ID Swap" text NULL,
	"Delivery Date" text NULL,
	"Banknote Rate Type" text NULL,
	"Commission" text NULL,
	"Order Type Name" text NULL,
	"Order Strategy Name" text NULL,
	"Execution Venue MIC" text NULL,
	"Market Segment ID" text NULL,
	"Group ID" text NULL,
	"Group Type" text NULL,
	"Trade Method" text NULL,
	"Execution Method" text NULL,
	"Sub Type" text NULL,
	"Supplementary Sub Type" text NULL,
	"External Reference ID" text NULL,
	"Execution Venue LEI" text NULL,
	"ISIN Near" text NULL,
	"ISIN Far" text NULL,
	"ISIN Swap" text NULL,
	"Execution within Firm Algo ID" text NULL,
	"Execution within Firm GPI" text NULL,
	"Execution within Firm Identifier" text NULL,
	"Investment Decision within Firm Algo ID" text NULL,
	"Investment Decision within Firm GPI" text NULL,
	"Investment Decision within Firm Short Code" text NULL,
	"Trading Capacity" text NULL,
	"Package ID" text NULL,
	"Pre-Trade Transparency Type" text NULL,
	"Pre-Trade Transparency Reason" text NULL,
	"Post-Trade Transparency Type" text NULL,
	"Post-Trade Transparency Reason" text NULL,
	"Commodities Derivative Indicator" text NULL,
	"Securities Financing Transaction" text NULL,
	"Maker Algo ID" text NULL,
	"Ord Reg Timestamp" text NULL,
	"Ord Reg Timestamp Type" text NULL,
	"Trd Reg Timestamp" text NULL,
	"Trd Reg Timestamp Type" text NULL,
	"Trade Reporting Indicator" text NULL,
	"Country of Membership" text NULL,
	CONSTRAINT fx_tickets_pk PRIMARY KEY (bbg_ticket_id)
);


CREATE TABLE irs (
	id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    dealid text NULL GENERATED ALWAYS AS ('IRS_'::text || id::text) STORED,
  "fund" "fund" NOT NULL DEFAULT 'SERCGMAST'::fund,
  "portfolio" "portfolio" NOT NULL,
  folder "strategy" NOT NULL,
  cash_account text NOT NULL REFERENCES accounts2(cash_account) ON UPDATE CASCADE,
  cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
  trade_date date NOT NULL,
	effective_date date NOT NULL,
	maturity_date date NOT NULL,
	payreceive bool NOT NULL,
	fixed_rate float8 NOT NULL,
	fixed_daycount day_count NOT NULL,
	fixed_payment_freq frequency NOT NULL,
  fixed_bdc bus_day_convention NOT NULL,
	notional float8 NOT NULL,
  float_index cash_rate NOT NULL,
	float_daycount day_count NOT NULL,
	float_payment_freq frequency NOT NULL,
  float_bdc bus_day_convention NOT NULL,
  float_arrears bool NOT NULL,
	"currency" "currency" NOT NULL,
	float_fixing_freq frequency NOT NULL,
	pay_interest_calc_method interest_calc_method NOT NULL,
	clearing_facility clearing_cp NOT NULL DEFAULT 'LCH-LTD'::clearing_cp,
	swap_type swap_type NOT NULL,
	cleared_trade_id text NULL,
  action action not null,
  upfront float8 not null,
  settle_date date not null,
  globeop_id int4 not null,
  bbg_ticket_id text null references irs_tickets(bbg_ticket_id) ON UPDATE CASCADE
);

CREATE TYPE "bbg_code_type" AS ENUM (
	'BOND',
	'CDS',
	'FX',
  'IRS');

CREATE TYPE "interest_calc_method" AS ENUM (
	'Compound',
	'Simple');

CREATE TABLE trs (
    id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    dealid text NULL GENERATED ALWAYS AS ('TRS'::text || id::text) STORED,
    "fund" "fund" NOT NULL DEFAULT 'SERCGMAST'::fund,
    "portfolio" "portfolio" NOT NULL,
    folder "cds_strat" NOT NULL,
    cash_account text NOT NULL REFERENCES accounts2(cash_account) ON UPDATE CASCADE,
    cp_code varchar(12) NOT NULL REFERENCES counterparties(code) ON UPDATE CASCADE,
    trade_date date NOT NULL,
    effective_date date NOT NULL,
    maturity_date date NOT NULL,
    settle_date date NOT NULL,
    funding_index cash_rate NOT NULL DEFAULT 'SOFRRATE'::cash_rate,
    buysell bool NOT NULL,
    underlying_security varchar(32) NOT NULL,
    price float8 NOT NULL,
    accrued float8 NOT NULL,
    funding_freq frequency NOT NULL,
    funding_daycount day_count NOT NULL,
    funding_payment_roll_convention bus_day_convention NOT NULL,
    funding_arrears bool NOT NULL,
    asset_freq frequency NOT NULL,
    asset_daycount day_count NOT NULL,
    asset_payment_roll_convention bus_day_convention NOT NULL,
    initial_margin_percentage float8 NOT NULL,
    notional float8 NOT NULL,
    "currency" "currency" NOT NULL DEFAULT 'USD'::currency,
    interest_calc_method interest_calc_method NOT NULL,
    compound_avg_frequency frequency NOT NULL,
    fixing_frequency frequency NOT NULL,
    cpty_id text NULL,
    action action not null,
    globeop_id int null,
);

CREATE TYPE "instrument_type" AS ENUM (
	'IRS',
	'CDS',
  'BNDO',
  'SWPO',
  'TRS');


CREATE TYPE "id_source" AS ENUM (
	'RED', 'USERID');

CREATE TYPE "serenitas_product" AS ENUM(
  'tranche', 'cdx_swaption', 'ir_swaption', 'irs', 'trs'
)

CREATE TABLE citco_tranche (
	id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,
	dealid text NULL GENERATED ALWAYS AS ('CDS_'::text || id::text) STORED,
	instrument_type instrument_type NOT NULL DEFAULT 'CDS'::instrument_type,
	underlying_id_source id_source NOT NULL DEFAULT 'RED'::id_source,
	underlying_security_id text NOT NULL,
	birth_date date NULL,
	death_date date NULL,
	active bool NULL DEFAULT true,
	"attach" int8 NOT NULL,
	"detach" int8 NOT NULL,
	"committed" bool NOT NULL DEFAULT false,
	CONSTRAINT citco_tranche_pkey PRIMARY KEY (id),
	CONSTRAINT citco_tranche_un UNIQUE (underlying_security_id, attach, detach)
);

CREATE FUNCTION instrument_cast(inst instrument_type) RETURNS text
LANGUAGE SQL
IMMUTABLE
RETURN instrument_type::text;

CREATE TABLE citco_swaption (
	id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
	dealid varchar(28) NULL GENERATED ALWAYS AS (instrument_cast(instrument_type) || '_' || id::text) STORED,
	instrument_type instrument_type NOT NULL,
	underlying_id_source id_source NOT NULL,
	underlying_security_id text NOT NULL,
	birth_date date NOT NULL,
	death_date date NOT NULL,
	active bool NOT NULL DEFAULT true,
	strike float8 NOT NULL,
	expiration date NOT NULL,
	callput bool NULL,
	committed bool NOT NULL DEFAULT false,
	UNIQUE (instrument_type, underlying_security_id, strike, expiration, callput)
);

CREATE TABLE citco_irs (
	id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
	dealid text NULL GENERATED ALWAYS AS ('IRS'::text || id::text) STORED,
  instrument_type  "instrument_type" NOT NULL default 'IRS',
	effective_date date NOT NULL,
  death_date date NOT NULL,
  active bool NOT NULL default True,
	payreceive bool NOT NULL,
	fixed_rate float8 NOT NULL,
	fixed_daycount "day_count" NOT NULL,
	fixed_payment_freq "frequency" NOT NULL,
	fixed_bdc "bus_day_convention" NOT NULL,
	notional float8 NOT NULL,
	float_index "cash_rate" NOT NULL,
	float_daycount "day_count" NOT NULL,
	float_payment_freq "frequency" NOT NULL,
	float_bdc "bus_day_convention" NOT NULL,
	float_arrears bool NOT NULL,
	"currency" "currency" NOT NULL,
	float_fixing_freq "frequency" NOT NULL,
	pay_interest_calc_method "interest_calc_method" NOT NULL,
  committed bool NOT NULL default False,
  payreceive bool NOT NULL
);


CREATE TABLE citco_trs (
	id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
	dealid text NULL GENERATED ALWAYS AS ('TRS'::text || id::text) STORED,
  instrument_type  "instrument_type" NOT NULL default 'TRS',
	birth_date date NOT NULL,
  death_date date NOT NULL,
  active bool NOT NULL default True,
	funding_index "cash_rate" NOT NULL DEFAULT 'SOFRRATE'::cash_rate,
	buysell bool NOT NULL,
	underlying_security varchar(32) NOT NULL,
	price numeric(9, 5) NOT NULL,
	accrued float8 NOT NULL,
	funding_freq "frequency" NOT NULL,
	funding_daycount "day_count" NULL,
	funding_payment_roll_convention "bus_day_convention" NOT NULL,
	funding_arrears bool NOT NULL,
	asset_freq "frequency" NOT NULL,
	asset_daycount "day_count" NULL,
	asset_payment_roll_convention "bus_day_convention" NOT NULL,
	initial_margin_percentage float8 NOT NULL,
	notional float8 NOT NULL,
	"currency" "currency" NOT NULL DEFAULT 'USD'::currency,
	"interest_calc_method" "interest_calc_method" NOT NULL,
	compound_avg_frequency "frequency" NOT NULL,
	fixing_frequency "frequency" NOT NULL,
  committed bool NOT NULL default False
);

CREATE TYPE "citco_identifier" AS ENUM (
	'trade', 'instrument', 'failed');

CREATE TABLE citco_submission2(
       id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
       identifier_type citco_identifier not null,
       citco_id text not null,
       serenitas_id text not null,
       submit_date timestamptz,
       process_date timestamptz,
       UNIQUE (identifier_type, submit_date, process_date, citco_id)
);

CREATE table isda_agreement_dates(
  fund fund not null,
  counterparty text REFERENCES counterparties(code),
  agreement_date date not null,
  CONSTRAINT isda_agreement_dates_key UNIQUE (fund, counterparty, agreement_date),
)

CREATE OR REPLACE VIEW tranche_risk_isosel
AS SELECT tranche_risk.date,
    tranche_risk.tranche_id AS trade_id,
    a.admin_id,
    cds.security_desc,
    index_version.index,
    index_version.series,
    cds.maturity,
    cds.orig_attach,
    cds.orig_detach,
    tranche_risk.notional,
    a.admin_notional,
    tranche_risk.clean_nav AS serenitas_clean_nav,
    a.admin_clean_nav,
    tranche_risk.accrued AS serenitas_accrued,
    a.admin_accrued,
    external_marks_deriv.base_nav AS cpty_nav,
    tranche_risk.duration,
    tranche_risk.delta,
    tranche_risk.gamma,
    tranche_risk.theta,
    tranche_risk.theta_amount,
    tranche_risk.tranche_factor,
    tranche_risk.corr_attach,
    tranche_risk.corr_detach,
    tranche_risk.upfront,
    tranche_risk.running,
    tranche_risk.index_refprice,
    tranche_risk.index_refspread,
    tranche_risk.index_duration,
    tranche_risk.hy_equiv,
    cds.initial_margin_percentage,
    tranche_risk.ir_dv01
   FROM tranche_risk
     LEFT JOIN cds ON tranche_risk.tranche_id = cds.id
     FULL JOIN ( SELECT COALESCE(isosel_accrued.init_trader_notes, isosel_accrued.init_fix_id) AS fix_id,
            isosel_accrued.init_order_id AS admin_id,
            isosel_accrued.period_end_date,
            sum(isosel_accrued.total_acc_int) AS admin_accrued,
            sum(isosel_accrued.end_mkt_value) AS admin_clean_nav,
            sum(- isosel_accrued."position") AS admin_notional
           FROM isosel_accrued
          WHERE isosel_accrued.liqd_date IS NULL
          GROUP BY (COALESCE(isosel_accrued.init_trader_notes, isosel_accrued.init_fix_id)), isosel_accrued.init_order_id, isosel_accrued.period_end_date) a ON a.fix_id = concat('SCCDS', tranche_risk.tranche_id) AND a.period_end_date = tranche_risk.date
     LEFT JOIN index_version ON cds.security_id::text = index_version.redindexcode
     LEFT JOIN external_marks_deriv ON cds.cpty_id = external_marks_deriv.identifier AND external_marks_deriv.date = tranche_risk.date
  WHERE cds.fund = 'ISOSEL'::fund
  ORDER BY index_version.index, index_version.series, cds.orig_attach;

CREATE OR REPLACE VIEW tranche_risk_globeop AS
SELECT tranche_risk.date, tranche_id as trade_id, b.globeop_id, security_desc, index, series, maturity, orig_attach,
       orig_detach, tranche_risk.notional,
       admin_notional,
       clean_nav as serenitas_clean_nav,
       admin_clean_nav,
       accrued as serenitas_accrued,
       admin_accrued,
       base_nav AS cpty_nav,
       duration, delta, gamma, theta, theta_amount, tranche_factor,
       tranche_risk.corr_attach, tranche_risk.corr_detach,
       tranche_risk.upfront, tranche_risk.running,
       index_refprice, index_refspread, index_duration, hy_equiv, initial_margin_percentage, cds.fund
FROM tranche_risk
LEFT JOIN LATERAL
(SELECT globeop_id FROM id_mapping WHERE id_mapping.serenitas_id=tranche_id AND date <= tranche_risk.date ORDER by date desc LIMIT 1) b ON true
LEFT JOIN cds ON (tranche_id=id)
FULL JOIN (SELECT invid, periodenddate,
                  sum(endbookunrealincome) AS admin_accrued,
                  sum(endbooknav-endbookunrealincome) AS admin_clean_nav,
                  sum(endqty) AS admin_notional
           FROM valuation_reports GROUP BY invid, periodenddate) a
     ON (NULLIF(substring(invid FROM '\D{3}[0]*(\d*)K00HEEAD'), '')::integer=b.globeop_id AND periodenddate=tranche_risk.date)
LEFT JOIN index_version ON (security_id=redindexcode)
LEFT JOIN external_marks_deriv ON cpty_id=identifier AND external_marks_deriv.date=tranche_risk.date
WHERE fund IN ('SERCGMAST', 'BOWDST')
ORDER BY index, series, orig_attach;


CREATE OR REPLACE VIEW tranche_risk_citco
AS SELECT tranche_risk.date,
    tranche_risk.tranche_id AS trade_id,
    a.admin_id,
    cds.security_desc,
    index_version.index,
    index_version.series,
    cds.maturity,
    cds.orig_attach,
    cds.orig_detach,
    tranche_risk.notional,
    a.admin_notional,
    tranche_risk.clean_nav AS serenitas_clean_nav,
    a.admin_clean_nav,
    tranche_risk.accrued AS serenitas_accrued,
    a.admin_accrued,
    external_marks_deriv.base_nav AS cpty_nav,
    tranche_risk.duration,
    tranche_risk.delta,
    tranche_risk.gamma,
    tranche_risk.theta,
    tranche_risk.theta_amount,
    tranche_risk.tranche_factor,
    tranche_risk.corr_attach,
    tranche_risk.corr_detach,
    tranche_risk.upfront,
    tranche_risk.running,
    tranche_risk.index_refprice,
    tranche_risk.index_refspread,
    tranche_risk.index_duration,
    tranche_risk.hy_equiv,
    cds.initial_margin_percentage,
    tranche_risk.ir_dv01
    cds.fund 
   FROM tranche_risk
     LEFT JOIN cds ON tranche_risk.tranche_id = cds.id
     FULL JOIN ( SELECT COALESCE(isosel_accrued.init_trader_notes, isosel_accrued.init_fix_id) AS fix_id,
            isosel_accrued.init_order_id AS admin_id,
            isosel_accrued.period_end_date,
            sum(isosel_accrued.total_acc_int) AS admin_accrued,
            sum(isosel_accrued.end_mkt_value) AS admin_clean_nav,
            sum(- isosel_accrued."position") AS admin_notional
           FROM isosel_accrued
          WHERE isosel_accrued.liqd_date IS NULL
          GROUP BY (COALESCE(isosel_accrued.init_trader_notes, isosel_accrued.init_fix_id)), isosel_accrued.init_order_id, isosel_accrued.period_end_date) a ON a.fix_id = concat('SCCDS', tranche_risk.tranche_id) AND a.period_end_date = tranche_risk.date
     LEFT JOIN index_version ON cds.security_id::text = index_version.redindexcode
     LEFT JOIN external_marks_deriv ON cds.cpty_id = external_marks_deriv.identifier AND external_marks_deriv.date = tranche_risk.date
  WHERE cds.fund::fund in ('ISOSEL', 'CRSE') 
  ORDER BY index_version.index, index_version.series, cds.orig_attach;

  CREATE TABLE isosel_accrued (
	"status" text NULL,
	tid text NULL,
	tid_fwd_date date NULL,
	fund_abbrev text NULL,
	trader_name text NULL,
	clear_agent text NULL,
	"strategy" text NULL,
	init_exec_broker text NULL,
	liqd_exec_broker text NULL,
	instr_class text NULL,
	instr_type text NULL,
	instrument_description text NULL,
	"l/s" text NULL,
	"position" float8 NULL,
	init_order_id int8 NULL,
	liqd_order_id float8 NULL,
	matching_id int8 NULL,
	init_fix_id text NULL,
	liqd_fix_id text NULL,
	init_date date NULL,
	init_settle_date date NULL,
	liqd_date date NULL,
	liqd_settle_date date NULL,
	init_price float8 NULL,
	liqd_price float8 NULL,
	init_fx float8 NULL,
	liqd_fx float8 NULL,
	"cost_[n]" float8 NULL,
	"avg_cost_[n]" float8 NULL,
	"off-balance_cost_[n]" float8 NULL,
	"off-balance_net_cost_[n]" float8 NULL,
	"cost" float8 NULL,
	avg_cost float8 NULL,
	"off-balance_cost" float8 NULL,
	"off-balance_net_cost" float8 NULL,
	"off-balance_init_net_cost" float8 NULL,
	init_net_cost float8 NULL,
	net_cost float8 NULL,
	"proceeds_[n]" float8 NULL,
	proceeds float8 NULL,
	net_proceeds float8 NULL,
	"init_comms_[n]" float8 NULL,
	"init_mfees_[n]" float8 NULL,
	"init_mtax_[n]" float8 NULL,
	"init_mexp_[n]" float8 NULL,
	"liqd_comms_[n]" float8 NULL,
	"liqd_mfees_[n]" float8 NULL,
	"liqd_mtax_[n]" float8 NULL,
	"liqd_mexp_[n]" float8 NULL,
	init_comms float8 NULL,
	init_mfees float8 NULL,
	init_mtax float8 NULL,
	init_mexp float8 NULL,
	liqd_comms float8 NULL,
	liqd_mfees float8 NULL,
	liqd_mtax float8 NULL,
	liqd_mexp float8 NULL,
	sec_fees float8 NULL,
	start_qty float8 NULL,
	end_qty float8 NULL,
	chg_qty float8 NULL,
	"start_mkt_value_[n]" float8 NULL,
	"start_mkt_value_realized_[n]" float8 NULL,
	"end_mkt_value_[n]" float8 NULL,
	"start_unrealized_[n]" float8 NULL,
	"end_unrealized_[n]" float8 NULL,
	"chg_unreal_[n]" float8 NULL,
	"realized_[n]" float8 NULL,
	"net_realized_[n]" float8 NULL,
	start_mkt_value float8 NULL,
	start_mkt_value_realized float8 NULL,
	end_mkt_value float8 NULL,
	start_unrealized float8 NULL,
	end_unrealized float8 NULL,
	chg_unreal float8 NULL,
	realized float8 NULL,
	net_realized float8 NULL,
	unrealized_fx float8 NULL,
	unrealized_fx_net float8 NULL,
	chg_unreal_fx float8 NULL,
	chg_unreal_fx_net float8 NULL,
	realized_fx float8 NULL,
	realized_fx_net float8 NULL,
	"dividends_[n]" float8 NULL,
	dividends float8 NULL,
	"acq_int_[n]" float8 NULL,
	"start_accrual_[n]" float8 NULL,
	"bond_accrual_[n]" float8 NULL,
	"interest_[n]" float8 NULL,
	"total_int_[n]" float8 NULL,
	acq_int float8 NULL,
	start_accrual float8 NULL,
	bond_accrual float8 NULL,
	interest float8 NULL,
	total_int float8 NULL,
	"p&l" float8 NULL,
	"p&l_[n]" float8 NULL,
	"p&l_total" float8 NULL,
	start_mkt_px float8 NULL,
	end_mkt_px float8 NULL,
	chg_mkt_px float8 NULL,
	instr_ccy text NULL,
	trade_ccy text NULL,
	fund_ccy text NULL,
	price_factor float8 NULL,
	notes text NULL,
	tax_status text NULL,
	days_held float8 NULL,
	account_988 float8 NULL,
	cost_basis text NULL,
	bond_coupon float8 NULL,
	source_ccy text NULL,
	"end_mkt_value_[source_ccy]" float8 NULL,
	fund_ending_notional float8 NULL,
	symbol text NULL,
	exchange text NULL,
	"country" text NULL,
	ticker_cusip text NULL,
	ticker_isin text NULL,
	ticker_sedol text NULL,
	ticker_userid text NULL,
	ticker_u_isin float8 NULL,
	ticker_u_sedol float8 NULL,
	industry float8 NULL,
	u_tid int8 NULL,
	u_name text NULL,
	"posted_init_fees_[n]" float8 NULL,
	posted_init_fees float8 NULL,
	"avg_netpx_[n]" float8 NULL,
	"avg_netliqdpx_[n]" float8 NULL,
	avg_netpx float8 NULL,
	fas_157 text NULL,
	fas_157_moved float8 NULL,
	orig_date date NULL,
	start_date date NULL,
	end_date date NULL,
	lot_commissions float8 NULL,
	lot_sec_fees float8 NULL,
	"fwd_unwind_[n]" float8 NULL,
	fwd_unwind float8 NULL,
	instr_country text NULL,
	"lot_cost_[n]" float8 NULL,
	lot_cost float8 NULL,
	"lot_net_cost_[n]" float8 NULL,
	lot_net_cost float8 NULL,
	"net_proceeds_[n]" float8 NULL,
	zz_int float8 NULL,
	fas157_major_type float8 NULL,
	fas161_trade_hedge float8 NULL,
	fas161_risk float8 NULL,
	lot_init_comms float8 NULL,
	lot_liqd_comms float8 NULL,
	ntv_acq_relief float8 NULL,
	base_acq_relief float8 NULL,
	ntv_end_accrual float8 NULL,
	base_end_accrual float8 NULL,
	last_cpn_date date NULL,
	liqd_orig_date text NULL,
	days_betw_orig_dates float8 NULL,
	"long/short_adjustment" float8 NULL,
	"$p&l_fx" float8 NULL,
	"opt_put/call" text NULL,
	beta float8 NULL,
	option_type_name text NULL,
	instrument_subtype text NULL,
	std_stratery float8 NULL,
	u_mkt_price float8 NULL,
	delta float8 NULL,
	option_strike float8 NULL,
	"total_acc_int_[n]" float8 NULL,
	total_acc_int float8 NULL,
	end_princ_factor float8 NULL,
	end_face_value float8 NULL,
	"acq_int_(fx)" float8 NULL,
	init_ticket_bs text NULL,2
	start_tax_status text NULL,
	active_bond_int float8 NULL,
	end_last_progname text NULL,
	init_corpact_id text NULL,
	liqd_corpact_id text NULL,
	init_client_order_id text NULL,
	liqd_client_order_id text NULL,
	deal_id float8 NULL,
	apost_tax_status text NULL,
	start_apost_tax_status text NULL,
	ticker_bbg text NULL,
	"order-level_attr_name" float8 NULL,
	init_order_attr_value float8 NULL,
	liqd_order_attr_value float8 NULL,
	ticker_pb_code_1 float8 NULL,
	ticker_pb_code_2 float8 NULL,
	init_trader_notes text NULL,
	liqd_trader_notes text NULL,
	u_symbol text NULL,
	ticker_u_cusip float8 NULL,
	bond_class text NULL,
	bond_maturity text NULL,
	trader_group float8 NULL,
	subfund text NULL,
	"row" int8 NOT NULL,
	period_end_date date NOT NULL,
	knowledge_date timestamp NULL,
  ticker_ocs_code text null,
  fund fund not null
	CONSTRAINT isosel_accrued_pk PRIMARY KEY (period_end_date, "row", fund)
);

CREATE TABLE citco_reports (
	subfund text NULL,
	trader text NULL,
	"prime_broker/clearing_broker" text NULL,
	"strategy" text NULL,
	citco_security_id text NULL,
	symbol text NULL,
	cusip text NULL,
	isin text NULL,
	sedol text NULL,
	ric text NULL,
	bloomberg_code text NULL,
	"long/short" text NULL,
	"quantity(start)" int8 NULL,
	"quantity(end)" float8 NULL,
	base_price float8 NULL,
	base_market_value float8 NULL,
	base_average_unit_cost float8 NULL,
	base_total_cost float8 NULL,
	base_commissions float8 NULL,
	base_sec_fees float8 NULL,
	"report_date_base_realized_p&l" int8 NULL,
	"report_date_base_unrealized_p&l" float8 NULL,
	"mtd_base_realized_p&l" int8 NULL,
	"mtd_base_unrealized_p&l" float8 NULL,
	"ytd_base_realized_p&l" int8 NULL,
	"ytd_base_unrealized_p&l" float8 NULL,
	base_ccy text NULL,
	issue_price float8 NULL,
	issue_market_value float8 NULL,
	issue_average_unit_cost float8 NULL,
	issue_total_cost float8 NULL,
	issue_commissions float8 NULL,
	issue_sec_fees float8 NULL,
	"report_date_issue_realized_p&l" int8 NULL,
	"report_date_issue_unrealized_p&l" float8 NULL,
	"mtd_issue_realized_p&l" int8 NULL,
	"mtd_issue_unrealized_p&l" float8 NULL,
	"ytd_issue_realized_p&l" int8 NULL,
	"ytd_issue_unrealized_p&l" float8 NULL,
	issue_ccy text NULL,
	security_description text NULL,
	security_asset_name text NULL,
	security_asset_class text NULL,
	maturity_date date NULL,
	"number_of_ticks(for_futures)" float8 NULL,
	"tick_value(for_futures)" float8 NULL,
	underlying_citco_security_id float8 NULL,
	underlying_symbol text NULL,
	underlying_cusip float8 NULL,
	underlying_isin text NULL,
	underlying_sedol float8 NULL,
	underlying_bloomberg_code text NULL,
	underlying_security_description text NULL,
	underlying_security_asset_name text NULL,
	underlying_security_asset_class text NULL,
	region text NULL,
	exchange text NULL,
	exchange_symbol text NULL,
	country_code text NULL,
	industry float8 NULL,
	industry_sector float8 NULL,
	"dividend_accrued/payable" int8 NULL,
	"dividend_income/loss" int8 NULL,
	"mtd_dividend_income/loss" int8 NULL,
	"ytd_dividend_income/loss" int8 NULL,
	"issue_dividend_accrued/payable" int8 NULL,
	"issue_dividend_income/loss" int8 NULL,
	"issue_mtd_dividend_income/loss" int8 NULL,
	"issue_ytd_dividend_income/loss" int8 NULL,
	issue_trade_acquisition_interest float8 NULL,
	mtd_issue_trade_acquisition_interest float8 NULL,
	ytd_issue_trade_acquisition_interest float8 NULL,
	issue_coupons_received float8 NULL,
	mtd_issue_coupons_received float8 NULL,
	ytd_issue_coupons_received float8 NULL,
	issue_repo_realized_interest float8 NULL,
	mtd_issue_repo_realized_interest float8 NULL,
	ytd_issue_repo_realized_interest float8 NULL,
	issue_bond_accrued_interest float8 NULL,
	issue_start_bond_accrued_interest float8 NULL,
	mtd_issue_start_bond_accrued_interest float8 NULL,
	ytd_issue_start_bond_accrued_interest float8 NULL,
	issue_repo_accrued_interest float8 NULL,
	issue_start_repo_accrued_interest float8 NULL,
	mtd_issue_start_repo_accrued_interest float8 NULL,
	ytd_issue_start_repo_accrued_interest float8 NULL,
	base_trade_acquisition_interest float8 NULL,
	mtd_base_trade_acquisition_interest float8 NULL,
	ytd_base_trade_acquisition_interest float8 NULL,
	base_coupons_received float8 NULL,
	mtd_base_coupons_received float8 NULL,
	ytd_base_coupons_received float8 NULL,
	base_repo_realized_interest float8 NULL,
	mtd_base_repo_realized_interest float8 NULL,
	ytd_base_repo_realized_interest float8 NULL,
	base_bond_accrued_interest float8 NULL,
	base_start_bond_accrued_interest float8 NULL,
	mtd_base_start_bond_accrued_interest float8 NULL,
	ytd_base_start_bond_accrued_interest float8 NULL,
	base_repo_accrued_interest float8 NULL,
	base_start_repo_accrued_interest float8 NULL,
	mtd_base_start_repo_accrued_interest float8 NULL,
	ytd_base_start_repo_accrued_interest float8 NULL,
	total_fund_capital float8 NULL,
	repo_start_quantity float8 NULL,
	mtd_repo_start_quantity float8 NULL,
	ytd_repo_start_quantity float8 NULL,
	repo_end_quantity float8 NULL,
	issue_start_loan_amount float8 NULL,
	mtd_issue_start_loan_amount float8 NULL,
	ytd_issue_start_loan_amount float8 NULL,
	issue_end_loan_amount float8 NULL,
	base_start_loan_amount float8 NULL,
	mtd_base_start_loan_amount float8 NULL,
	ytd_base_start_loan_amount float8 NULL,
	base_end_loan_amount float8 NULL,
	issue_total_repo_interest float8 NULL,
	mtd_issue_total_repo_interest float8 NULL,
	ytd_issue_total_repo_interest float8 NULL,
	issue_total_bond_interest float8 NULL,
	mtd_issue_total_bond_interest float8 NULL,
	ytd_issue_total_bond_interest float8 NULL,
	base_total_repo_interest float8 NULL,
	mtd_base_total_repo_interest float8 NULL,
	ytd_base_total_repo_interest float8 NULL,
	repo_rate float8 NULL,
	base_total_bond_interest float8 NULL,
	mtd_base_total_bond_interest float8 NULL,
	ytd_base_total_bond_interest float8 NULL,
	spot_fx_rate int8 NULL,
	standard_strategy float8 NULL,
	client_instrument_id text NULL,
	issue_start_price float8 NULL,
	issue_mtd_start_price float8 NULL,
	issue_ytd_start_price float8 NULL,
	report_date_base_commissions float8 NULL,
	mtd_base_commissions float8 NULL,
	ytd_base_commissions float8 NULL,
	base_commissions_paid_on_open_positions float8 NULL,
	report_date_issue_commissions float8 NULL,
	mtd_issue_commissions float8 NULL,
	ytd_issue_commissions float8 NULL,
	issue_commissions_paid_on_open_positions float8 NULL,
	trader_group float8 NULL,
	report_date_base_sec_fees float8 NULL,
	mtd_base_sec_fees float8 NULL,
	ytd_base_sec_fees float8 NULL,
	report_date_issue_sec_fees float8 NULL,
	mtd_issue_sec_fees float8 NULL,
	ytd_issue_sec_fees float8 NULL,
	base_deferred_fees_payable float8 NULL,
	base_deferred_mgmt_fees_payable float8 NULL,
	repo float8 NULL,
	"option_type" text NULL,
	"option_put/call_flag" text NULL,
	option_strike_price float8 NULL,
	option_expiration_date float8 NULL,
	contract_size float8 NULL,
	coupon_rate float8 NULL,
	bloomberg_real_time_code text NULL,
	bond_abbrev text NULL,
	underlying_ric text NULL,
	period_end_date date NOT NULL,
	knowledge_date timpestamp NULL,
	option_delta float8 NULL,
	"daily_base_p/l" float8 NULL,
	"monthly_base_p/l" float8 NULL,
	"yearly_base_p/l" float8 NULL,
	"daily_issue_p/l" float8 NULL,
	"monthly_issue_p/l" float8 NULL,
	"yearly_issue_p/l" float8 NULL,
	daily_base_income float8 NULL,
	monthly_base_income float8 NULL,
	yearly_base_income float8 NULL,
	daily_issue_income float8 NULL,
	monthly_issue_income float8 NULL,
	yearly_issue_income float8 NULL,
	adjustment_date float8 NULL,
	"fund" "fund" NOT NULL,
	future_contract_value float8 NULL,
	future_contract_tick_size float8 NULL,
	bond_series_code text NULL,
	coupon_freq text NULL,
	daycount float8 NULL,
	day_count_fraction_repo text NULL,
	feed_system_code float8 NULL,
	factor float8 NULL,
	coupon_start_date float8 NULL,
	coupon_end_date float8 NULL,
	number_of_days_accrued float8 NULL,
	security_identifier float8 NULL,
	previous_period_accrual_unsettled float8 NULL,
	fixing_date float8 NULL,
	issue_date float8 NULL,
	settle_days float8 NULL,
	redeem_price float8 NULL,
	day_convention text NULL,
	instrument_attributes text NULL,
	underlying_currency_code text NULL,
	swap_receiving_leg_rate_index text NULL,
	swap_receiving_leg_coupon float8 NULL,
	swap_receiving_leg_accrual_method text NULL,
	swap_receiving_leg_payment_frequency text NULL,
	swap_pay_leg_rate_index text NULL,
	swap_pay_leg_coupon float8 NULL,
	swap_pay_leg_accrual_method text NULL,
	swap_pay_leg_payment_frequency text NULL,
	bloomberg_id text NULL,
	daily_tax_issue_currency int8 NULL,
	mtd_tax_issue_currency int8 NULL,
	ytd_tax_issue_currency int8 NULL,
	daily_tax_base_currency int8 NULL,
	mtd_tax_base_currency int8 NULL,
	ytd_tax_base_currency int8 NULL,
	odd_first_coupon float8 NULL,
	odd_last_coupon float8 NULL,
	end_ote_issue float8 NULL,
	end_ote_base float8 NULL,
	swap_start_date float8 NULL,
	swap_maturity_date float8 NULL,
	swap_counterparty float8 NULL,
	swap_receiving_leg_currency text NULL,
	swap_receiving_leg_principal float8 NULL,
	swap_receiving_leg_payment_calendar text NULL,
	swap_pay_leg_currency text NULL,
	swap_pay_leg_principal float8 NULL,
	swap_pay_leg_payment_calendar text NULL,
	swap_pay_leg_rate_source text NULL,
	price_factor float8 NULL,
	notional_asset_value int8 NULL,
	country_name text NULL,
	swap_interest int8 NULL,
	effective_coupon_rate float8 NULL,
	moody_bond_rating text NULL,
	"s&p_bond_rating" text NULL,
	risk_country_attribute text NULL,
	underlying_country_code text NULL,
	underlying_country_name text NULL,
	underlying_price float8 NULL,
	underlying_bloomberg_id text NULL,
	underlying_risk_country text NULL,
	issue_miscellaneous_fees float8 NULL,
	issue_miscellaneous_expenses float8 NULL,
	issue_taxes float8 NULL,
	base_miscellaneous_fees float8 NULL,
	base_miscellaneous_expenses float8 NULL,
	base_taxes float8 NULL,
	commodity_swap_start_date float8 NULL,
	commodity_swap_termination_date float8 NULL,
	issue_sec_fees_for_zzinternal_trade float8 NULL,
	base_sec_fees_for_zzinternal_trade float8 NULL,
	beta_1d float8 NULL,
	end_face_value float8 NULL,
	"prime_broker/clearing_broker_long_name" text NULL,
	"end_date_issue_unrealized_p&l" float8 NULL,
	"end_date_base_unrealized_p&l" float8 NULL,
	issue_nav_contribution float8 NULL,
	base_nav_contribution float8 NULL,
	cost_basis_flag text NULL,
	occ_code float8 NULL,
	underlying_occ_code float8 NULL,
	interest_start_date float8 NULL,
	trader_abbrev text NULL,
	deal_id int8 NULL,
	client_deal_id float8 NULL,
	deal_type_id float8 NULL,
	notes float8 NULL,
	pb3 float8 NULL,
	report_date_repo_fx float8 NULL,
	mtd_repo_fx float8 NULL,
	ytd_repo_fx float8 NULL,
	report_date_issue_swap_coupon int8 NULL,
	mtd_issue_swap_coupon int8 NULL,
	ytd_issue_swap_coupon int8 NULL,
	report_date_base_swap_coupon int8 NULL,
	mtd_base_swap_coupon int8 NULL,
	ytd_base_swap_coupon int8 NULL,
	swaption_underlyer_maturity_date float8 NULL,
	base_swap_interest float8 NULL,
	mtd_issue_miscellaneous_fees float8 NULL,
	ytd_issue_miscellaneous_fees float8 NULL,
	mtd_base_miscellaneous_fees float8 NULL,
	ytd_base_miscellaneous_fees float8 NULL,
	mtd_issue_miscellaneous_expenses float8 NULL,
	ytd_issue_miscellaneous_expenses float8 NULL,
	mtd_base_miscellaneous_expenses float8 NULL,
	ytd_base_miscellaneous_expenses float8 NULL,
	future_death_date float8 NULL,
	mtd_issue_taxes float8 NULL,
	ytd_issue_taxes float8 NULL,
	mtd_base_taxes float8 NULL,
	ytd_base_taxes float8 NULL,
	report_date_issue_start_acq_interest float8 NULL,
	mtd_issue_start_acq_interest float8 NULL,
	ytd_issue_start_acq_interest float8 NULL,
	report_date_base_start_acq_interest float8 NULL,
	mtd_base_start_acq_interest float8 NULL,
	ytd_base_start_acq_interest float8 NULL,
	"trading_base_unrealized_p&l" float8 NULL,
	issue_bond_realized_interest float8 NULL,
	mtd_issue_bond_realized_interest float8 NULL,
	ytd_issue_bond_realized_interest float8 NULL,
	issue_bond_unrealized_interest float8 NULL,
	mtd_issue_bond_unrealized_interest float8 NULL,
	ytd_issue_bond_unrealized_interest float8 NULL,
	base_bond_realized_interest float8 NULL,
	mtd_base_bond_realized_interest float8 NULL,
	ytd_base_bond_realized_interest float8 NULL,
	base_bond_unrealized_interest float8 NULL,
	mtd_base_bond_unrealized_interest float8 NULL,
	ytd_base_bond_unrealized_interest float8 NULL,
	report_date_unrealized_repo_fx float8 NULL,
	mtd_unrealized_repo_fx float8 NULL,
	ytd_unrealized_repo_fx float8 NULL,
	report_date_realized_repo_fx float8 NULL,
	mtd_realized_repo_fx float8 NULL,
	ytd_realized_repo_fx float8 NULL,
	red text NULL,
	user_id text NULL,
	fund_name text NULL,
	instrument_start_date float8 NULL,
	exchange_principal text NULL,
	tick_size float8 NULL,
	underlying_tick_size float8 NULL,
	swap_float_leg_coupon float8 NULL,
	swap_reset_rate float8 NULL,
	cds_attachment_points float8 NULL,
	cds_detachment_points float8 NULL,
	cds_credit_event float8 NULL,
	barrier1 float8 NULL,
	barrier2 float8 NULL,
	barrier_option_window_1_start_date float8 NULL,
	barrier_option_window_1_end_date float8 NULL,
	swaption_underlyer_start_date float8 NULL,
	swaption_underlyer_coupon_frequency float8 NULL,
	option_expiration_value_date float8 NULL,
	underlying_red text NULL,
	swap_receive_leg_rate_source text NULL,
	fas_157 text NULL,
	swaption_receiving_leg_rate_source text NULL,
	swaption_receiving_leg_payment_frequency text NULL,
	swaption_receiving_leg_coupon_rate float8 NULL,
	swaption_pay_leg_rate_source text NULL,
	swaption_pay_leg_payment_frequency text NULL,
	swaption_pay_leg_coupon_rate float8 NULL,
	instrument_subtype text NULL,
	close_price float8 NULL,
	underlying_cds_maturity_date float8 NULL,
	underlying2_citco_security_id float8 NULL,
	underlying2_symbol text NULL,
	underlying2_cusip float8 NULL,
	underlying2_isin float8 NULL,
	underlying2_sedol float8 NULL,
	underlying2_bloomberg_code float8 NULL,
	underlying2_ric float8 NULL,
	underlying2_bloomberg_id float8 NULL,
	underlying2_red float8 NULL,
	"gross_dividend_income/loss" float8 NULL,
	"mtd_gross_dividend_income/loss" float8 NULL,
	"ytd_gross_dividend_income/loss" float8 NULL,
	"issue_gross_dividend_income/loss" float8 NULL,
	"issue_gross_mtd_dividend_income/loss" float8 NULL,
	"issue_gross_ytd_dividend_income/loss" float8 NULL,
	"repo_type" text NULL,
	repo_start_date float8 NULL,
	"gic_level_1_(sector)" float8 NULL,
	"gic_level_2_(industry_group)" float8 NULL,
	"gic_level_3_(industries)" float8 NULL,
	"gic_level_4_(sub-industries)" float8 NULL,
	repo_bcusip float8 NULL,
	dividend_explorer_txn_id float8 NULL,
	swap_div_eligibility_date float8 NULL,
	issue_end_loan_amount_td float8 NULL,
	base_end_loan_amount_td float8 NULL,
	trade_ccy text NULL,
	buy_cur_for_fxfwd text NULL,
	sell_cur_for_fxfwd text NULL,
	eod_rolled_nav_balance float8 NULL,
	bloomberg_ticker text NULL,
	start_fx_rate int8 NULL,
	"p&l_(fx)" float8 NULL,
	market_capital float8 NULL,
	gl_account float8 NULL,
	gl_account_name text NULL,
	"p&l_type" text NULL,
	net_cost float8 NULL,
	"net_cost_[n]" float8 NULL,
	issue_client_market_value float8 NULL,
	custom_user_id text NULL,
	pb_bloomberg_ticker float8 NULL,
	"cost_[n]" float8 NULL,
	"cost" float8 NULL,
	bond_accr float8 NULL,
	"bond_accr_[n]" float8 NULL,
	swap_accrued int8 NULL,
	"swap_accrued_[n]" int8 NULL,
	instr_end_fx_rate float8 NULL,
	death_date float8 NULL,
	"tickr/loanx" float8 NULL,
	strike_price float8 NULL,
	global_client_instrument_id text NULL,
	"daily_p&l_(fx)" int8 NULL,
	"mtd_p&l_(fx)" int8 NULL,
	"ytd_p&l_(fx)" int8 NULL,
	mtd_swap_interest int8 NULL,
	ytd_swap_interest int8 NULL,
	repo_start_origin_date float8 NULL,
	repo_end_date float8 NULL,
	"attr/dm_template_name" float8 NULL,
	"attr/pricing_frequency" float8 NULL,
	"attr/fas_161_primary_risk_category" float8 NULL,
	"attr/fas_161_tradinghedging" float8 NULL,
	"attr/analyst" float8 NULL,
	"attr/country_status" float8 NULL,
	"attr/va_co_override" float8 NULL,
	"attr/va_gic_exclude" float8 NULL,
	"attr/va_industry_override" float8 NULL,
	"attr/va_sector_override" float8 NULL,
	"attr/beta" float8 NULL,
	"attr/kcm_instrument" float8 NULL,
	"attr/kcm_symbol" float8 NULL,
	"attr/kcm_issuer" float8 NULL,
	"attr/kcm_investment_type" float8 NULL,
	"attr/kcm_investment_direc" float8 NULL,
	"attr/kcm_risk_country" float8 NULL,
	"attr/kcm_region" float8 NULL,
	"attr/kcm_sr_pm" float8 NULL,
	"attr/kcm_pm" float8 NULL,
	"attr/kcm_sr_analyst" float8 NULL,
	"attr/kcm_analyst" float8 NULL,
	"attr/kcm_1st_trade_date" float8 NULL,
	"attr/kcm_investment_type2" float8 NULL,
	"attr/kcm_descr_by_issuer" float8 NULL,
	"attr/kcm_attribution_tagg" float8 NULL,
	"utckr/bloomberg_real_time_code" text NULL,
	base_start_loan_amount_td float8 NULL,
	issue_start_loan_amount_td float8 NULL,
	rate_start_date float8 NULL,
	rate_set_date float8 NULL,
	bloomberg_global_id text NULL,
	instrument_attribute_name text NULL,
	issue_swap_interest int8 NULL,
	mtd_issue_swap_interest int8 NULL,
	ytd_issue_swap_interest int8 NULL,
	"base_misc_bal_p&l" float8 NULL,
	"mtd_base_misc_bal_p&l" float8 NULL,
	"ytd_base_misc_bal_p&l" float8 NULL,
	"issue_misc_bal_p&l" float8 NULL,
	"mtd_issue_misc_bal_p&l" float8 NULL,
	"ytd_issue_misc_bal_p&l" float8 NULL,
	fund_tid text NULL,
	repo_ccy float8 NULL,
	"tckr/cins" float8 NULL,
	bond_class text NULL,
	revolver text NULL,
	"total_p&l" float8 NULL,
	repo_end_qty_td float8 NULL,
	repo_start_qty_td float8 NULL,
	fund_underlying_tid text NULL,
	"daily_acq_int_(fx)" float8 NULL,
	"mtd_acq_int_(fx)" float8 NULL,
	"ytd_acq_int_(fx)" float8 NULL,
	asc_820_level float8 NULL,
	"attr/kcm_strategy" text NULL,
	end_last_price_source text NULL,
	strategy_group text NULL,
	"row" int8 NOT NULL,
	CONSTRAINT citco_reports_pkey PRIMARY KEY (period_end_date, "row", fund)
);


CREATE TABLE custodian_wires(
       date date NOT NULL,
       fund fund NOT NULL,
       entry_date date,
       value_date date,
       pay_date date,
       currency currency,
       amount float8 NOT NULL,
       wire_details text,
       unique_ref text PRIMARY KEY,
       custodian custodian NOT NULL);



CREATE OR REPLACE VIEW trs_trades AS
SELECT trs.id,
       dealid,
       termination_date AS trade_date,
       termination_amount AS notional,
       underlying_desc,
       underlying_security,
       CASE WHEN termination_cp=cp_code THEN
         'Termination'
       ELSE
         'Assignment'
       END AS trade_type,
       folder,
       fund,
       termination_cp AS cp_code,
       name,
       funding_index,
       CASE WHEN buysell THEN
         False
       ELSE
         True
       END AS buysell,
       termination_fee AS upfront,
       terminations.traded_level as price,
       maturity_date,
       fee_payment_date as settle_date
FROM terminations RIGHT JOIN trs USING (dealid)
LEFT JOIN counterparties on termination_cp=code
WHERE termination_date is NOT NULL
UNION ALL (
SELECT id,
       dealid,
       trade_date,
       notional,
       underlying_desc,
       underlying_security,
       'New',
       folder,
       fund,
       cp_code,
       name,
       funding_index,
       buysell,
       accrued as upfront,
       price,
       maturity_date,
       settle_date
FROM trs JOIN counterparties ON cp_code = code) ORDER BY trade_date DESC, folder;


CREATE TRIGGER cash_account BEFORE
INSERT OR UPDATE OF
   fund,
   cp_code
ON
    trs
FOR EACH ROW
EXECUTE PROCEDURE update_account('ISDA');

CREATE TYPE author AS ENUM ('auto', 'manual');

 CREATE OR REPLACE VIEW forward_trades
AS SELECT a.*, c.name from(SELECT  unnest(ARRAY[fx_swaps.dealid::text, fx_swaps.dealid::text]) AS dealid,
    fx_swaps.trade_date,
    unnest(ARRAY[fx_swaps.near_settle_date, fx_swaps.far_settle_date]) AS settle_date,
    fx_swaps.fund,
    fx_swaps.portfolio,
    fx_swaps.folder,
    fx_swaps.cp_code,
    unnest(ARRAY[fx_swaps.near_buy_currency, fx_swaps.far_buy_currency]) AS buy_currency,
    unnest(ARRAY[fx_swaps.near_sell_currency, fx_swaps.far_sell_currency]) AS sell_currency,
    unnest(ARRAY[fx_swaps.near_buy_amount::numeric(11,2), fx_swaps.far_buy_amount::numeric(11,2)]) AS buy_amount,
    unnest(ARRAY[fx_swaps.near_sell_amount::numeric(11,2), fx_swaps.far_sell_amount::numeric(11,2)]) AS sell_amount,
    unnest(ARRAY[fx_swaps.near_cpty_id, fx_swaps.far_cpty_id]) AS cpty_id,
    unnest(ARRAY[fx_swaps.near_rate, fx_swaps.far_rate]) AS spot_rate,
    fx_swaps.id as id,
    unnest(ARRAY['NEAR', 'FAR']) as fx_type
   FROM fx_swaps
UNION
 SELECT  spots.dealid,
    spots.trade_date,
    spots.settle_date,
    spots.fund,
    spots.portfolio,
    spots.folder,
    spots.cp_code,
    spots.buy_currency,
    spots.sell_currency,
    spots.buy_amount::numeric(11,2),
    spots.sell_amount::numeric(11,2),
    spots.cpty_id,
    spots.spot_rate,
    spots.id as id,
    'SPOT' as fx_type
   FROM spots) a
   LEFT JOIN counterparties c ON cp_code=code ;

CREATE OR REPLACE function list_orphaned_cash(p_date date, p_fund fund)
RETURNS TABLE(fund fund, trade_date date,amount float, portfolio portfolio, cash_account text, currency currency, folder TEXT, custodian text, cp_code varchar(10)) AS $$
BEGIN
  RETURN QUERY
  SELECT a.*, coalesce(pfm.folder::text, a.strat::text), accounts2.custodian, accounts2.cp_code FROM (
  SELECT vr.fund, vr.periodenddate, -sum(vr.endqty) AS amount, vr.port, vr.custacctname AS cash_account, vr.invid::currency AS currency
  FROM valuation_reports vr
  GROUP BY (vr.periodenddate, vr.fund, vr.port, vr.strat, vr.custacctname, vr.invid)
  HAVING periodenddate=p_date AND vr.fund=p_fund AND vr.invid in ('USD', 'EUR') and port NOT IN ('GFS_HELPER_BUSINESS_UNIT', 'CASH') AND sum(vr.endqty) !=0
  ) a
  LEFT JOIN portfolio_folder_mapping pfm ON a.strat::text = pfm.clean_folder::text
  LEFT JOIN accounts2 USING (cash_account)
  WHERE pfm.active;
END
$$ LANGUAGE plpgsql;


CREATE TABLE cash_balances (
	"date" date NOT NULL,
	"fund" "fund" NULL,
	account_name varchar NULL,
	account_number varchar NOT NULL,
	currency_code "currency" NOT NULL,
	balance numeric(11,2) NULL,
	CONSTRAINT cash_balances_pkey PRIMARY KEY (date, account_number, currency_code)
);

CREATE TYPE priced_at_market_discounting_reference_rate_t AS enum('1-month LIBOR','SOFR');
CREATE TYPE priced_at_market_ccf_engine_t AS enum('btm','serenitas');
CREATE TYPE crt_bond_type AS enum('FCF','pre-COVID LCF','post-COVID LCF','pre-SSRA B1','pre-COVID SSRA B1','early post-COVID B1','early post-COVID B2','2021 non-5-year-call B2','2021 non-5-year-call B1','5-year call B1','5-year call B2','pre-COVID OGB and B2','IO', 'MI CRT FCF', 'MI CRT mid-CF', 'MI CRT pre-COVID LCF', 'MI CRT post-COVID LCF', 'MI CRT pre-COVID B1', 'MI CRT post-COVID B1');
IMPORT FOREIGN SCHEMA crt LIMIT TO (priced_at_market, map_cusip, bond_types, beta_estimates) FROM SERVER mysql_server INTO public;

CREATE TABLE bond_csv_upload(
      id int4 NOT NULL GENERATED ALWAYS AS IDENTITY,
      tradeid int NOT NULL,
      identifier text NOT NULL,
      principal numeric(11, 2) NOT NULL,
      interest numeric(11, 2) NOT NULL,
      status status DEFAULT 'Processed',
      CONSTRAINT unique_upload_check UNIQUE (tradeid, cusip, principal, interest)
      );

CREATE OR REPLACE VIEW irs_trades AS
SELECT irs.id,
       dealid,
       termination_date AS trade_date,
       termination_amount AS notional,
       maturity_date,
       float_index,
       CASE WHEN termination_cp=cp_code THEN
         'Termination'
       ELSE
         'Assignment'
       END AS trade_type,
       folder,
       fund,
       termination_cp AS cp_code,
       name,
       fixed_rate,
       CASE WHEN payreceive THEN
         False
       ELSE
         True
       END AS payreceive,
       termination_fee AS upfront,
       fee_payment_date as settle_date,
       swap_type
FROM terminations RIGHT JOIN irs USING (dealid)
LEFT JOIN counterparties on termination_cp=code
WHERE termination_date is NOT NULL
UNION ALL (
SELECT id,
       dealid,
       trade_date,
       notional,
       maturity_date,
       float_index,
       'New',
       folder,
       fund,
       cp_code,
       name,
       fixed_rate,
       payreceive,
       upfront,
       settle_date,
       swap_type
FROM irs JOIN counterparties ON cp_code = code) ORDER BY trade_date DESC, folder;

CREATE OR REPLACE FUNCTION list_iam(p_date date, p_fund fund) RETURNS TABLE (trade_date date, broker text, clean_folder strategy, start_money numeric(11,2), currency currency, fund fund, folder text, portfolio portfolio) AS $$ BEGIN RETURN QUERY
SELECT si.date as trade_date, si.broker, si.strategy as clean_strat, si.amount::NUMERIC(11,2),
si.currency, si.fund, COALESCE(pfm.folder::text, strategy::text) AS folder, pfm.portfolio
FROM (SELECT *, rank() OVER(PARTITION BY si.broker,si.fund ORDER BY date desc)
FROM strategy_im si WHERE si.fund=p_fund AND si.date<=p_date ORDER BY date DESC) si
LEFT JOIN portfolio_folder_mapping pfm ON pfm.clean_folder=si.strategy::TEXT
WHERE RANK=1 and abs(amount) >= .01; END $$ LANGUAGE plpgsql;

CREATE TYPE custodian AS ENUM('BNY', 'UMB', 'NT', "SCOTIA");


CREATE TABLE iams (
	id int4 NOT NULL GENERATED ALWAYS AS IDENTITY,
	dealid varchar(28) NULL GENERATED ALWAYS AS ((('IAM_'::text || id::text))) STORED,
	trade_date date NOT NULL,
	folder strategy NOT NULL,
	broker text NOT NULL,
	maturity date NULL,
	amount numeric NOT NULL,
	currency currency NOT NULL,
	is_offset bool NOT NULL,
	uploaded bool NOT NULL,
	fund fund NOT NULL,
  portfolio portfolio NOT NULL,
	CONSTRAINT iams_pk PRIMARY KEY (trade_date, strategy, broker, currency, is_offset, fund)
);

CREATE TABLE shocks (
	date date NOT NULL,
	risk_type risk_type NOT NULL,
	spread_shock float8 NOT NULL,
	strategy text NOT NULL,
	value numeric(11, 2) NOT NULL,
	fund fund NOT NULL,
	CONSTRAINT shocks_pkey PRIMARY KEY (date, risk_type, spread_shock, strategy, fund)
);

CREATE TABLE jtd_risks (
	"date" date NOT NULL,
	"fund" "fund" NOT NULL,
	company_id int4 NOT NULL,
	"name" text NOT NULL,
	jtd float8 NOT NULL,
	5yr_spread float8 NOT NULL,
	1yr_spread float8 NULL,
	3yr_spread float8 NULL,
	CONSTRAINT jtd_risks_pkey PRIMARY KEY (date, fund, company_id)
);

CREATE TYPE risk_type AS ENUM ('HY_EQUIV', 'PNL');

CREATE TABLE irs_tickets (
	bbg_ticket_id text NOT NULL,
	"match" text NULL,
	side text NULL,
	"security" text NULL,
	quantity float8 NULL,
	price_dec float8 NULL,
	cp float8 NULL,
	stp_status text NULL,
	trade_dt date NULL,
	setdt date NULL,
	curncy text NULL,
	principal float8 NULL,
	net float8 NULL,
	acc_int float8 NULL,
	block_status text NULL,
	brkr text NULL,
	brkrname text NULL,
	figi text NULL,
	cusip text NULL,
	mat_dt date NULL,
	cclear_usiuti text NULL,
	account text NOT NULL,
	client_fcm text NOT NULL,
	effectdt date NULL,
	CONSTRAINT irs_tickets_pk PRIMARY KEY (bbg_ticket_id, account, client_fcm)
);


CREATE OR REPLACE VIEW globeop_forward_valuations AS
SELECT periodenddate, knowledgedate, fund, invccy, invid, port::text, strat::text, sum(endlocalmv) as endlocalmv
FROM valuation_reports vr
GROUP BY periodenddate, knowledgedate, fund, invccy, invid, port, strat
HAVING invid IN ('EURF') ORDER BY periodenddate desc, fund;

CREATE OR REPLACE VIEW citco_forward_valuations
AS SELECT 
    cr.period_end_date AS periodenddate,
    cr.knowledge_date as knowledgedate, 
    cr.fund,
    "substring"(cr.bloomberg_code, 0, 4)::currency AS invccy,
    "substring"(cr.bloomberg_code, 0, 4) || 'F'::text AS invid,
    split_part(cr.strategy, '/'::text, 1) AS port,
    split_part(cr.strategy, '/'::text, 2) AS strat,
    sum(cr."quantity(end)") AS endlocalmv
   FROM citco_reports cr
  GROUP BY cr.period_end_date, cr.knowledge_date, cr.fund, cr.bloomberg_code, cr.strategy
 HAVING cr.bloomberg_code ~~ '%CURNCY'::text
  ORDER BY cr.period_end_date DESC, fund;

CREATE OR REPLACE VIEW globeop_otc_valuations AS SELECT periodenddate, knowledgedate, fund, invccy, custacctname, port::text, strat::text,
       sum(
          CASE
            WHEN endbookmv = 0 OR endlocalmv = 0 THEN 0
            ELSE endbooknav / (endbookmv / endlocalmv)
          END
       ) as endlocalmv
FROM valuation_reports vr
WHERE invid NOT IN ('EUR', 'EURF') AND endbooknav IS NOT NULL
GROUP BY periodenddate, knowledgedate, fund, invccy, custacctname, port, strat
HAVING invccy IN ('EUR', 'USD')
AND custacctname IN (SELECT cash_account FROM accounts2 WHERE account_type = 'Cash' AND active) ORDER BY periodenddate desc, fund;

-- no strategy = cash, we're trying to make sure the otc valuations are calculated, not cash
CREATE OR REPLACE VIEW citco_otc_valuations
AS SELECT cr.period_end_date AS periodenddate,
    cr.knowledge_date as knowledgedate,
    cr.fund,
    cr.trade_ccy::currency AS invccy,
    cr."prime_broker/clearing_broker" AS custacctname,
    split_part(cr.strategy, '/'::text, 1) AS port,
    split_part(cr.strategy, '/'::text, 2) AS strat,
    sum(cr.issue_nav_contribution) AS endlocalmv
   FROM citco_reports cr
  WHERE cr."prime_broker/clearing_broker" ~~ '%_IS'::text AND cr.strategy NOT NULL
  GROUP BY cr.period_end_date, cr.knowledge_date, cr.fund, cr.trade_ccy, cr."prime_broker/clearing_broker", cr.strategy
  ORDER BY cr.period_end_date DESC, cr.fund;

CREATE OR REPLACE VIEW globeop_cash_valuations
AS SELECT 
    vr.periodenddate,
    vr.knowledgedate,
    vr.fund,
    vr.invid,
    vr.invccy,
    vr.port::text,
    vr.strat::text,
    vr.custacctname,
    sum(vr.endqty) AS endlocalmv
   FROM valuation_reports vr
  GROUP BY  vr.periodenddate, vr.knowledgedate, vr.fund, vr.invid, vr.invccy, vr.port, vr.strat, vr.custacctname
 HAVING vr.invid = ANY (ARRAY['EUR'::text, 'USD'::text]) ORDER BY periodenddate DESC, fund;

CREATE OR REPLACE VIEW citco_cash_valuations
AS 
SELECT 
    cr.period_end_date AS periodenddate,
    cr.knowledge_date as knowledgedate,
    cr.fund,
    cr.trade_ccy AS invid,
    cr.trade_ccy::currency AS invccy,
    'CASH'::text AS port,
    'CSH_CASH'::text AS strat,
    cr."prime_broker/clearing_broker" AS custacctname,
    CASE WHEN cr."prime_broker/clearing_broker" = 'BOA_FC'
         THEN (SELECT sum(cr."quantity(end)")+(account_value_market- ending_balance) FROM fcm_moneyline fm WHERE account='6MZ20K79'AND "currency" = 'EUR' AND date=cr.period_end_date)
         ELSE sum(cr."quantity(end)")
    END AS endlocalmv
FROM citco_reports cr
GROUP BY cr.period_end_date, cr.knowledge_date, cr.fund, cr.trade_ccy, cr."prime_broker/clearing_broker", cr.symbol
HAVING cr.symbol = ANY (ARRAY['EUR Cash Balance'::text, 'USD Cash Balance'::text])
ORDER BY period_end_date DESC, fund;

CREATE VIEW eur_fx_valuations AS
SELECT periodenddate, knowledgedate, fund, port, forward_valuations, otc_valuations, cash_valuations
FROM (
  SELECT periodenddate, knowledgedate, fund, port, sum(endlocalmv) AS forward_valuations
  FROM (SELECT * FROM globeop_forward_valuations UNION SELECT * FROM citco_forward_valuations) afv
  WHERE invid = 'EURF'
  GROUP BY periodenddate, knowledgedate, fund, port
) f
FULL OUTER JOIN (
  SELECT periodenddate, knowledgedate, fund, port, sum(endlocalmv) AS otc_valuations
  FROM (SELECT * FROM globeop_otc_valuations UNION SELECT * FROM citco_otc_valuations) aov
  WHERE invccy = 'EUR'
  GROUP BY periodenddate, knowledgedate, fund, port
) otc
USING (periodenddate, knowledgedate, fund, port)
FULL OUTER JOIN (
  SELECT periodenddate, knowledgedate, fund, port, sum(endlocalmv) AS cash_valuations
  FROM (SELECT * FROM globeop_cash_valuations UNION SELECT * FROM citco_cash_valuations) acv
  WHERE invid = 'EUR'
  GROUP BY periodenddate, knowledgedate, fund, port
) c
USING (periodenddate, knowledgedate, fund, port)
ORDER BY periodenddate DESC, knowledgedate, fund;


CREATE OR REPLACE FUNCTION calculate_eur_excess(p_periodenddate DATE)
RETURNS TABLE (
  fund fund,
  knowledgedate timestamp,
  periodenddate date,
  eur_excess numeric(11,2)
) AS $$
BEGIN
  RETURN QUERY
  SELECT
    efv.fund,
    efv.knowledgedate,
    efv.periodenddate,
    SUM(COALESCE(efv.forward_valuations, 0) + COALESCE(efv.otc_valuations, 0) + COALESCE(efv.cash_valuations, 0))::numeric(11,2) AS eur_excess
  FROM
    eur_fx_valuations efv
  WHERE
    efv.periodenddate = p_periodenddate
  GROUP BY
    efv.fund,
    efv.knowledgedate,
    efv.periodenddate
  ORDER BY
    efv.periodenddate DESC,
    efv.fund;
END;
$$ LANGUAGE plpgsql;


CREATE TABLE citco_account_mapping (fund fund, citco_code text, account TEXT references accounts2(cash_account), PRIMARY KEY (fund, citco_code));

CREATE VIEW cds_termination_mapping AS 
SELECT t.id AS termination_id, cds.*
FROM terminations t
LEFT JOIN cds ON t.deal_type = 'CDS' AND t.dealid = cds.dealid WHERE deal_type='CDS';

CREATE VIEW swaption_termination_mapping AS 
SELECT t.id AS termination_id, swaptions.*
FROM terminations t
LEFT JOIN swaptions ON (t.deal_type = 'CreditSwaption' OR t.deal_type = 'IRSwaption') AND t.dealid = swaptions.dealid WHERE deal_type IN ('CreditSwaption', 'IRSwaption');


CREATE VIEW trs_termination_mapping AS 
SELECT t.id AS termination_id, trs.*
FROM terminations t
LEFT JOIN trs ON t.deal_type = 'TRS' AND t.dealid = trs.dealid WHERE deal_type='TRS';

CREATE VIEW termination_collateral_mapping AS 
SELECT * FROM (SELECT fund, folder::text, termination_id FROM cds_termination_mapping
UNION
SELECT fund, folder::text, termination_id FROM swaption_termination_mapping
UNION
SELECT fund, folder::text, termination_id from trs_termination_mapping) a LEFT JOIN 
terminations on a.termination_id = terminations.id;


CREATE OR REPLACE FUNCTION compare_citco_bonds(
	p_date date,
    p_fund fund
) RETURNS TABLE (
    citco_security_id text,
    security_id text,
    serenitas_factor float,
    serenitas_notional float,
    admin_factor float,
    admin_notional float
)
AS $$
BEGIN
    RETURN QUERY
    SELECT b.citco_security_id::text, a.identifier::text AS security_id, a.factor AS serenitas_factor, 
           a.notional AS serenitas_notional, b.factor AS admin_factor, 
           b."quantity(end)" AS admin_notional 
    FROM risk_positions(p_date, NULL, p_fund, True) a 
    LEFT JOIN 
    (
        SELECT cusip, factor, "quantity(end)", cr.citco_security_id 
        FROM citco_reports cr 
        WHERE fund=p_fund AND cusip IS NOT NULL AND period_end_date=p_date
    ) b 
    ON a.identifier=b.cusip;
END;
$$ LANGUAGE PLPGSQL;