aboutsummaryrefslogtreecommitdiffstats
path: root/sql/serenitas.c
blob: 034af647964bcd4fc4b92446818e24baee57e48b (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
#include "postgres.h"
#include "fmgr.h"
#include "executor/spi.h"
#include "lz4.h"
#include "utils/date.h"
#include "utils/builtins.h"
#include "utils/numeric.h"
#include "utils/rel.h"

#include "isda/bastypes.h"
#include "isda/dateconv.h"
#include "isda/busday.h"
#include "isda/ldate.h"
#include "isda/cdsone.h"
#include "isda/cerror.h"
#include <stdbool.h>

PG_MODULE_MAGIC;

static inline TDate next_business_day(TDate date, long method, const char* cal) {
    TDate r;
    if (JpmcdsBusinessDay(date, method, cal, &r) != SUCCESS) {
        return -1;
    } else {
        return r;
    }
}

TDate _previous_twentieth(TDate d, bool roll, const char* cal) {
    TMonthDayYear mdy;
    if (JpmcdsDateToMDY(d, &mdy) != SUCCESS) {
        return -1;
    }
    if (mdy.day < 20) {
        if(mdy.month == 1) {
            mdy.month = 12;
            mdy.year -= 1;
        } else {
            mdy.month -= 1;
        }
    }
    mdy.day = 20;
    int mod = mdy.month % 3;
    if (mod != 0) {
        mdy.month -= mod;
        if (mdy.month <= 0) {
            mdy.month += 12;
            mdy.year -= 1;
        }
    }
    TDate r;
    if (JpmcdsMDYToDate(&mdy, &r) != SUCCESS) {
        return -1;
    }
    if (roll) {
        return next_business_day(r, JPMCDS_BAD_DAY_FOLLOW, cal);
    } else {
        return r;
    }
}

// postgresql represents dates as number of days since 2000-01-01
// TDate are integers since 1601-01-01
static inline TDate TDate_from_DateADT(DateADT d) {
    return d + 145731;
}

static inline const char* cal_from_currency(const char* curr) {
    static const char default_cal[] = "NONE";
    static const char us_cal[] = "/usr/share/cds/NYM";
    static const char jp_cal[] = "/usr/share/cds/TYO";
    if (strcmp(curr, "USD") == 0) {
        return us_cal;
    } else if (strcmp(curr, "JPY") == 0) {
        return jp_cal;
    } else {
        return default_cal;
    }
}

static inline const int16 curvetype_from_currency(const char* curr) {
    if (strcmp(curr, "USD") == 0) {
        return 531;
    } else if (strcmp(curr, "EUR") == 0) {
        return 530;
    } else if (strcmp(curr, "JPY") == 0) {
        return 532;
    } else {
        elog(ERROR, "unknown currency");
    }
}


PG_FUNCTION_INFO_V1(cds_accrued);

Datum cds_accrued(PG_FUNCTION_ARGS) {
    DateADT d = PG_GETARG_DATEADT(0);
    float8 coupon = PG_GETARG_FLOAT8(1);
    bool include_cashflow = PG_GETARG_BOOL(2);
    char* currency = text_to_cstring(PG_GETARG_TEXT_PP(3));
    const char* cal = cal_from_currency(currency);
    TDate date = TDate_from_DateADT(d) + 1;
    TDate date1 = next_business_day(date, JPMCDS_BAD_DAY_PREVIOUS, cal);
    if (date1 == -1) {
        pfree(currency);
        elog(ERROR, "Please set up the US calendar in /usr/share/cds/NYM");
    }

    TDate date_prev = _previous_twentieth(date1, true, cal);

    if ((date_prev == date) && include_cashflow) {
        date_prev = _previous_twentieth(date - 1, true, cal);
    }
    pfree(currency);
    PG_RETURN_FLOAT8((date - date_prev) / 360. * coupon);
}

static inline void get_TCurve(const char* buf, uint32_t length, TCurve* curve) {
    if (LZ4_decompress_safe(buf, (char*)curve, length, 512) < 0) {
        elog(ERROR, "error during decompression");
    }
}

double calc(TDate today, TDate start_date, TDate end_date, double recovery, double fixed_rate, const char* calendar, const TCurve* yc, double val, bool calc_upfront) {
    TDate cash_settle_date;
    JpmcdsDateFromBusDaysOffset(today, 3, calendar, &cash_settle_date);
    TDate step_in_date = today + 1;
    TStubMethod stub_type = {0, 0}; //f/s
    TDateInterval ivl = {.prd = 3, .prd_typ='M', .flag=0}; // 3 months
    double result;
    int success;
    if (calc_upfront) {
        success = JpmcdsCdsoneUpfrontCharge(today,
                                            cash_settle_date,
                                            start_date, // benchmark_start_date
                                            step_in_date,
                                            start_date,
                                            end_date,
                                            fixed_rate,
                                            true, // pay accrued on default
                                            &ivl,
                                            &stub_type,
                                            JPMCDS_ACT_360,
                                            JPMCDS_BAD_DAY_FOLLOW,
                                            calendar,
                                            yc,
                                            val,
                                            recovery,
                                            false, // pay accrued at start
                                            &result);
    } else {
        success = JpmcdsCdsoneSpread(today,
                                     cash_settle_date,
                                     start_date, // benchmark_start_date
                                     step_in_date,
                                     start_date,
                                     end_date,
                                     fixed_rate,
                                     true, // pay accrued on default
                                     &ivl,
                                     &stub_type,
                                     JPMCDS_ACT_360,
                                     JPMCDS_BAD_DAY_FOLLOW,
                                     calendar,
                                     yc,
                                     val,
                                     recovery,
                                     false, // pay accrued at start
                                     &result);
    }
    if (success == 0)
        return result;
    else
        elog(ERROR, "something went wrong");
}


PG_FUNCTION_INFO_V1(upfront_from_level);

Datum upfront_from_level(PG_FUNCTION_ARGS) {
    if (SPI_connect() == SPI_ERROR_CONNECT) {
        elog(ERROR, "something wrong happened");
    }
    const text* redindexcode = PG_GETARG_TEXT_PP(0);
    DateADT maturity = PG_GETARG_DATEADT(1);
    float8 traded_level = PG_GETARG_FLOAT8(2);
    DateADT trade_date = PG_GETARG_DATEADT(3);
    char* currency = text_to_cstring(PG_GETARG_TEXT_PP(4));
    char* sql_query = "SELECT index::text, coupon, issue_date, indexfactor/100, cumulativeloss "
        "FROM index_desc "
        "WHERE redindexcode=$1 AND maturity=$2";
    uint64 proc;
    int nargs = 2;
    Oid argtypes[2] = {TEXTOID, DATEOID};
    char nulls[2] = "  ";
    Datum values[2];
    int ret;
    values[0] = PointerGetDatum(redindexcode);
    values[1] = DateADTGetDatum(maturity);

    ret = SPI_execute_with_args(sql_query, nargs, argtypes, values, nulls, true, 1);
    proc = SPI_processed;
    int coupon;
    char *index;
    TDate issue_date;
    double factor, cumulativeloss;
    if (ret == SPI_OK_SELECT && SPI_tuptable != NULL) {
        SPITupleTable *tuptable = SPI_tuptable;
        TupleDesc tupdesc = tuptable->tupdesc;
        bool isnull;
        HeapTuple tuple = tuptable->vals[0];
        index = text_to_cstring(DatumGetTextPP(SPI_getbinval(tuple, tupdesc, 1, &isnull)));
        coupon = DatumGetInt32(SPI_getbinval(tuple, tupdesc, 2, &isnull));
        issue_date = TDate_from_DateADT(DatumGetDateADT(SPI_getbinval(tuple, tupdesc, 3, &isnull)));
        factor = DatumGetFloat8(SPI_getbinval(tuple, tupdesc, 4, &isnull));
        cumulativeloss = DatumGetFloat8(SPI_getbinval(tuple, tupdesc, 5, &isnull));
        elog(INFO, "%s %d %d %f %f", index, coupon, issue_date, factor, cumulativeloss);
    } else {
        elog(ERROR, "something wrong happened");
    }
    SPI_freetuptable(SPI_tuptable);
    int16 curve_type = curvetype_from_currency(currency);
    sql_query = "SELECT curve FROM rate_curves WHERE effective_date=$1 AND curve_type=$2";
    argtypes[0] = DATEOID;
    argtypes[1] = INT2OID;
    values[0] = DateADTGetDatum(trade_date);
    values[1] = Int16GetDatum(curve_type);
    ret = SPI_execute_with_args(sql_query, nargs, argtypes, values, nulls, true, 1);
    proc = SPI_processed;
    bytea* buf;
    Datum tmp;
    TCurve* curve;
    if (ret == SPI_OK_SELECT && SPI_tuptable != NULL) {
        SPITupleTable *tuptable = SPI_tuptable;
        TupleDesc tupdesc = tuptable->tupdesc;
        bool isnull;
        HeapTuple tuple = tuptable->vals[0];
        tmp = SPI_getbinval(tuple, tupdesc, 1, &isnull);
        if (isnull) {
            elog(ERROR, "no curve for that date");
        } else {
            buf = DatumGetByteaPP(tmp);
            uint32 data_length = VARSIZE_ANY_EXHDR(buf);
            const char *raw_data = VARDATA_ANY(buf);
            curve = (TCurve*)palloc(512);
            get_TCurve(raw_data, data_length, curve);
        }
    } else {
        elog(ERROR, "no curve for that date");
    }
    pfree(currency);
    pfree(curve);
    SPI_finish();
    double recovery = 0.4;
    double upfront;
    upfront = calc(TDate_from_DateADT(trade_date), issue_date, TDate_from_DateADT(maturity), recovery, coupon / 10000.0, cal_from_currency(currency), curve, traded_level, true);
    PG_RETURN_FLOAT8(upfront);
}


PG_FUNCTION_INFO_V1(update_attach);

Datum
update_attach(PG_FUNCTION_ARGS)
{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    Trigger    *trigger;        /* to get trigger name */
    char       *relname;        /* triggered relation name */
    Relation    rel;            /* triggered relation */
    HeapTuple   rettuple = NULL;
    TupleDesc   tupdesc;        /* tuple description */
    bool        isnull;
    if (!CALLED_AS_TRIGGER(fcinfo))
        /* internal error */
        elog(ERROR, "not fired by trigger manager");
    if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
        /* internal error */
        elog(ERROR, "must be fired for row");
    if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
        /* internal error */
        elog(ERROR, "must be fired before event");

    if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
        rettuple = trigdata->tg_trigtuple;
    else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        rettuple = trigdata->tg_newtuple;
    else
        /* internal error */
        elog(ERROR, "cannot process DELETE events");

    rel = trigdata->tg_relation;

    if (rettuple)
        relname = SPI_getrelname(rel);

    trigger = trigdata->tg_trigger;
    tupdesc = rel->rd_att;
    /* int attname = SPI_fnumer(tupdesc, "traded_level"); */
    /* Oid traded_level = DatumGetObjectId(SPI_getbinval(rettuple, tupdesc, SPI_fnumber(tupdesc, "traded_level"), &isnull)); */
    int16 orig_attach, orig_detach;
    bool attach_is_null, detach_is_null;
    orig_attach = DatumGetInt16(SPI_getbinval(rettuple, tupdesc, SPI_fnumber(tupdesc, "orig_attach"), &attach_is_null));
    orig_detach = DatumGetInt16(SPI_getbinval(rettuple, tupdesc, SPI_fnumber(tupdesc, "orig_detach"), &detach_is_null));

    if (attach_is_null && detach_is_null)
        return PointerGetDatum(rettuple);

    char* sql_query = "SELECT indexfactor, cumulativeloss "
        "FROM index_factors "
        "WHERE redindexcode=$1";
    int nargs = 1;
    Oid argtypes[1] = {TEXTOID};
    char nulls[1] = " ";
    Datum values[1];
    int ret;
    values[0] = SPI_getbinval(rettuple, tupdesc, SPI_fnumber(tupdesc, "security_id"), &isnull);
    if (isnull) {
        elog(ERROR, "no security id");
    }
    if (SPI_connect() == SPI_ERROR_CONNECT) {
        elog(ERROR, "something wrong happened");
    }
    ret = SPI_execute_with_args(sql_query, nargs, argtypes, values, nulls, true, 1);
    double factor, cumloss;
    if (SPI_processed != 1) {
        return PointerGetDatum(rettuple);
    }
    if (ret == SPI_OK_SELECT && SPI_tuptable != NULL) {
        SPITupleTable *tuptable = SPI_tuptable;
        TupleDesc tupdesc = tuptable->tupdesc;
        bool isnull;
        HeapTuple tuple = tuptable->vals[0];
        factor = DatumGetFloat8(SPI_getbinval(tuple, tupdesc, 1, &isnull));
        cumloss = DatumGetFloat8(SPI_getbinval(tuple, tupdesc, 2, &isnull));
        elog(INFO, "%f %f", factor, cumloss);
    } else {
        elog(ERROR, "SPI query didn't work");
    }
    SPI_finish();
    double detach, attach;
    detach = detach_is_null ? 1.0 : factor * Min(Max((orig_detach - cumloss) / factor, 0.0), 1.0);
    attach = attach_is_null ? 0.0 : factor * Min(Max((orig_attach - cumloss) / factor, 0.0), 1.0);

    int chnattrs = 2;
    int chattrs[2];
    Datum newvals[2];
    bool newnulls[2] = {false, false};
    chattrs[0] = SPI_fnumber(tupdesc, "attach");
    chattrs[1] = SPI_fnumber(tupdesc, "detach");
    newvals[0] = Float8GetDatum(attach);
    newvals[1] = Float8GetDatum(detach);

    rettuple = heap_modify_tuple_by_cols(rettuple, tupdesc,
                                         chnattrs, chattrs,
                                         newvals, newnulls);
    return PointerGetDatum(rettuple);
}