-
Notifications
You must be signed in to change notification settings - Fork 129
/
rates.go
749 lines (648 loc) · 26 KB
/
rates.go
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
package models
import (
"encoding/json"
"errors"
"fmt"
"github.com/diadata-org/diadata/internal/pkg/rateDerivatives"
"math"
"sort"
"strconv"
"time"
"github.com/diadata-org/diadata/pkg/utils"
"github.com/go-redis/redis"
)
const (
keyAllRates = "all_rates"
// TimeLayoutRedis = "2006-01-02 15:04:05 +0000 UTC"
)
type InterestRate struct {
Symbol string `json:"Symbol"`
Value float64 `json:"Value"`
PublicationTime time.Time `json:"PublicationTime"`
EffectiveDate time.Time `json:"EffectiveDate"`
Source string `json:"Source"`
}
// MarshalBinary for interest rates
func (e *InterestRate) MarshalBinary() ([]byte, error) {
return json.Marshal(e)
}
// UnmarshalBinary for interest rates
func (e *InterestRate) UnmarshalBinary(data []byte) error {
if err := json.Unmarshal(data, &e); err != nil {
return err
}
return nil
}
type InterestRateMeta struct {
Symbol string
FirstDate time.Time
Decimals int
Issuer string
}
// ---------------------------------------------------------------------------------------
// Setter and getter for interest rates
// ---------------------------------------------------------------------------------------
// getKeyInterestRate returns a string that is used as key for storing an interest
// rate in the Redis database.
// @symbol is the symbol of the interest rate (such as SOFR) set at time @date.
func getKeyInterestRate(symbol string, date time.Time) string {
return "dia_quotation_" + symbol + "_" + date.String()
}
// SetInterestRate writes the interest rate struct ir into the Redis database
// and writes rate type into a set of all available rates (if not done yet).
func (datastore *DB) SetInterestRate(ir *InterestRate) error {
if datastore.redisClient == nil {
return nil
}
// Prepare interest rate quantities for database
key := getKeyInterestRate(ir.Symbol, ir.EffectiveDate)
// Write interest rate quantities into database
log.Debug("setting", key, ir)
err := datastore.redisClient.Set(key, ir, TimeOutRedis).Err()
if err != nil {
log.Printf("Error: %v on SetInterestRate %v\n", err, ir.Symbol)
}
// Write rate type into set of available rates
err = datastore.redisClient.SAdd(keyAllRates, ir.Symbol).Err()
if err != nil {
log.Printf("Error: %v on writing rate %v into set of available rates\n", err, ir.Symbol)
}
return err
}
// GetInterestRate returns the interest rate value for the last time stamp before @date.
// If @date is an empty string it returns the rate at the latest time stamp.
// @symbol is the shorthand symbol for the requested interest rate.
// @date is a string in the format yyyy-mm-dd.
func (datastore *DB) GetInterestRate(symbol, date string) (*InterestRate, error) {
if date == "" {
date = time.Now().Format("2006-01-02")
}
key, _ := datastore.matchKeyInterestRate(symbol, date)
// Run database querie with found key
ir := &InterestRate{}
err := datastore.redisClient.Get(key).Scan(ir)
if err != nil {
if !errors.Is(err, redis.Nil) {
log.Errorf("Error: %v on GetInterestRate %v\n", err, symbol)
}
return ir, err
}
return ir, nil
}
// GetInterestRateRange returns the interest rate values for a range of timestamps.
// @symbol is the shorthand symbol for the requested interest rate.
// @dateInit and @dateFinal are strings in the format yyyy-mm-dd.
func (datastore *DB) GetInterestRateRange(symbol, dateInit, dateFinal string) ([]*InterestRate, error) {
// Collect all possible keys in time range
keys := []string{}
auxDate := dateInit
for dateFinal >= auxDate {
keys = append(keys, "dia_quotation_"+symbol+"_"+auxDate+" 00:00:00 +0000 UTC")
auxDate = utils.GetTomorrow(auxDate, "2006-01-02")
}
// Retrieve corresponding values from database
result := datastore.redisClient.MGet(keys...).Val()
allValues := []*InterestRate{}
for _, val := range result {
if val != nil {
ir := &InterestRate{}
err := json.Unmarshal([]byte(fmt.Sprint(val)), ir)
if err != nil {
log.Error("error parsing json")
return []*InterestRate{}, err
}
allValues = append(allValues, ir)
}
}
// Sort entries with respect to effective date
sort.Slice(allValues, func(i, j int) bool {
return (allValues[i].EffectiveDate).Before(allValues[j].EffectiveDate)
})
return allValues, nil
}
// ---------------------------------------------------------------------------------------
// Getter for rates' metadata
// ---------------------------------------------------------------------------------------
// GetRates returns a (unique) slice of all rates that have been written into the database
func (datastore *DB) GetRates() []string {
// log.Info("Fetching set of available rates")
allRates := datastore.redisClient.SMembers(keyAllRates).Val()
return allRates
}
// GetRatesMeta returns a list of all available rate symbols along with their first
// timestamp in the database.
func (datastore *DB) GetRatesMeta() (RatesMeta []InterestRateMeta, err error) {
allRates := datastore.GetRates()
for _, symbol := range allRates {
// Get first publication date
newdate, err := datastore.GetFirstDate(symbol)
if err != nil {
return []InterestRateMeta{}, err
}
// Get issuing entity
issuer, err := datastore.GetIssuer(symbol)
if err != nil {
return []InterestRateMeta{}, err
}
// Number of decimals
decimals := 0
switch symbol {
case "SONIA":
decimals = 4
case "SOFR":
decimals = 2
case "SAFR":
decimals = 8
case "SOFR30":
decimals = 5
case "SOFR90":
decimals = 5
case "SOFR180":
decimals = 5
case "ESTER":
decimals = 3
default:
decimals = 8
}
// Fill meta type
newEntry := InterestRateMeta{symbol, newdate, decimals, issuer}
RatesMeta = append(RatesMeta, newEntry)
}
return
}
// GetIssuer returns the issuing entity of the rate given by @symbol
func (datastore *DB) GetIssuer(symbol string) (string, error) {
newdate, err := datastore.GetFirstDate(symbol)
if err != nil {
return "", err
}
key := getKeyInterestRate(symbol, newdate)
ir := &InterestRate{}
err = datastore.redisClient.Get(key).Scan(ir)
if err != nil {
return "", err
}
return ir.Source, nil
}
// GetFirstDate returns the oldest date written in the database for the rate with symbol @symbol
func (datastore *DB) GetFirstDate(symbol string) (time.Time, error) {
allSyms := datastore.GetRates()
if !(utils.Contains(&allSyms, symbol)) {
log.Errorf("The symbol %v does not exist in the database.", symbol)
return time.Time{}, errors.New("database error")
}
// Fetch all available keys for @symbol
patt := "dia_quotation_" + symbol + "_*"
// Comment: This could be improved. Should be when the database gets larger.
allKeys := datastore.redisClient.Keys(patt).Val()
oldestKey, _ := utils.MinString(allKeys)
// Scan the struct corresponding to the oldest timestamp and fetch effective date.
ir := &InterestRate{}
err := datastore.redisClient.Get(oldestKey).Scan(ir)
if err != nil {
return time.Time{}, err
}
return ir.EffectiveDate, nil
}
// ---------------------------------------------------------------------------------------
// Risk-free rates methods
// ---------------------------------------------------------------------------------------
// GetCompoundedRate returns the compounded rate for the period @dateInit to @date. It computes the rate for all
// days for which an entry is present in the database. All other days are assumed to be holidays (or weekends).
func (datastore *DB) GetCompoundedRate(symbol string, dateInit, date time.Time, daysPerYear int, rounding int) (*InterestRate, error) {
// Get first publication date for the rate with @symbol in order to check feasibility of dateInit
firstPublication, err := datastore.GetFirstDate(symbol)
if err != nil {
return &InterestRate{}, err
}
if utils.AfterDay(firstPublication, dateInit) {
log.Error("dateInit cannot be earlier than first publication date.")
err = errors.New("dateInit cannot be earlier than first publication date")
return &InterestRate{}, err
}
ratesAPI, err := datastore.GetInterestRateRange(symbol, dateInit.Format("2006-01-02"), date.Format("2006-01-02"))
if err != nil {
return &InterestRate{}, err
}
if len(ratesAPI) == 0 {
err = errors.New("no rate information for this period")
return &InterestRate{}, err
}
// Determine holidays through missing database entries
existDates := []time.Time{}
for _, entry := range ratesAPI {
existDates = append(existDates, (*entry).EffectiveDate)
}
holidays := utils.GetHolidays(existDates, dateInit, date)
// Sort ratesApi (type []*InterestRates) in increasing order according to date
// and remove the data for the final date, as only past values are compounded.
sort.Slice(ratesAPI, func(i, j int) bool {
return (ratesAPI[i].EffectiveDate).Before(ratesAPI[j].EffectiveDate)
})
ratesAPI = ratesAPI[:len(ratesAPI)-1]
// Extract rates' values
rates := []float64{}
for i := range ratesAPI {
rates = append(rates, ratesAPI[i].Value)
}
// Check, whether first day is a holiday or weekend. If so, prepend rate of
// preceding business day (outside the considered time range!).
if utils.ContainsDay(holidays, dateInit) || !utils.CheckWeekDay(dateInit) {
var firstRate *InterestRate
firstRate, err = datastore.GetInterestRate(symbol, dateInit.Format("2006-01-02"))
if err != nil {
return &InterestRate{}, err
}
rates = append([]float64{firstRate.Value}, rates...)
}
// Get compounded rate
compRate, err := ratederivatives.CompoundedRate(rates, dateInit, date, holidays, daysPerYear, rounding)
if err != nil {
return &InterestRate{}, err
}
// Fill InterestRate type for return
ir := &InterestRate{}
ir.Symbol = symbol + "_compounded_by_DIA"
ir.Value = compRate
ir.EffectiveDate = date
ir.Source = ratesAPI[0].Source
return ir, nil
}
// GetCompoundedIndex returns the compounded index over the maximal period of existence of @symbol
func (datastore *DB) GetCompoundedIndex(symbol string, date time.Time, daysPerYear int, rounding int) (*InterestRate, error) {
// Get initial date for the rate with @symbol
dateInit, err := datastore.GetFirstDate(symbol)
if err != nil {
return &InterestRate{}, err
}
return datastore.GetCompoundedRate(symbol, dateInit, date, daysPerYear, rounding)
}
// GetCompoundedIndexRange returns the compounded average of the index @symbol over rolling @calDays calendar days.
func (datastore *DB) GetCompoundedIndexRange(symbol string, dateInit, dateFinal time.Time, daysPerYear int, rounding int) (values []*InterestRate, err error) {
// Get first publication date for the rate with @symbol in order to check feasibility of dateInit
firstPublication, err := datastore.GetFirstDate(symbol)
if err != nil {
return []*InterestRate{}, err
}
if utils.AfterDay(firstPublication, dateInit) {
log.Error("dateStart cannot be earlier than first publication date.")
err = errors.New("dateStart cannot be earlier than first publication date")
return []*InterestRate{}, err
}
// Get rate data from database for the computation of the compounded values
ratesAPI, err := datastore.GetInterestRateRange(symbol, dateInit.Format("2006-01-02"), dateFinal.Format("2006-01-02"))
if err != nil {
return []*InterestRate{}, err
}
if len(ratesAPI) == 0 {
err = errors.New("no rate information for this period")
return []*InterestRate{}, err
}
// Sort ratesApi (type []*InterestRates) in increasing order according to date.
sort.Slice(ratesAPI, func(i, j int) bool {
return (ratesAPI[i].EffectiveDate).Before(ratesAPI[j].EffectiveDate)
})
// Determine holidays through missing database entries
existDates := []time.Time{}
for _, entry := range ratesAPI {
existDates = append(existDates, (*entry).EffectiveDate)
}
holidays := utils.GetHolidays(existDates, firstPublication, dateFinal)
// Consider previous business day if @dateFinal is holiday or weekend
for utils.ContainsDay(holidays, dateFinal) || !utils.CheckWeekDay(dateFinal) {
dateFinal = dateFinal.AddDate(0, 0, -1)
}
// Consider next business day if @dateInit is holiday or weekend
for utils.ContainsDay(holidays, dateInit) || !utils.CheckWeekDay(dateInit) {
dateInit = dateInit.AddDate(0, 0, 1)
}
// Initialize return values
compRate, err := datastore.GetCompoundedRate(symbol, firstPublication, dateInit, daysPerYear, 0)
if err != nil {
return
}
value := compRate.Value
values = append(values, compRate)
// Iterate through all remaining business days
for i := 0; i < len(ratesAPI)-1; i++ {
n, _ := ratederivatives.RateFactor(ratesAPI[i].EffectiveDate, holidays)
factor := 1 + (ratesAPI[i].Value/100)*float64(n)/float64(daysPerYear)
value *= factor
// Fill return struct
compAvg := &InterestRate{}
compAvg.Symbol = symbol + "_compounded_by_DIA"
compAvg.Value = value
compAvg.EffectiveDate = ratesAPI[i+1].EffectiveDate
compAvg.Source = ratesAPI[0].Source
// Append data and increment initial date
values = append(values, compAvg)
}
if rounding != 0 {
for i := range values {
values[i].Value = math.Round(values[i].Value*math.Pow(10, float64(rounding))) / math.Pow(10, float64(rounding))
}
return values, nil
}
return values, nil
}
// GetCompoundedAvg returns the compounded average of the index @symbol over rolling @calDays calendar days.
func (datastore *DB) GetCompoundedAvg(symbol string, date time.Time, calDays, daysPerYear int, rounding int) (*InterestRate, error) {
dateInit := date.AddDate(0, 0, -calDays)
index, err := datastore.GetCompoundedRate(symbol, dateInit, date, daysPerYear, rounding)
if err != nil {
return &InterestRate{}, err
}
// Fill return struct
compAvg := &InterestRate{}
compAvg.Symbol = symbol + strconv.Itoa(calDays) + "_compounded_by_DIA"
compAvg.Value = 100 * (index.Value - 1) * float64(daysPerYear) / float64(calDays)
compAvg.EffectiveDate = date
compAvg.Source = index.Source
return compAvg, nil
}
// --------------------------------------------------------------------------------------------
// Computation of compounded average range as done by FED and BOE, i.e. neglecting higher order
// terms accounting for holidays and weekends
// --------------------------------------------------------------------------------------------
// WeightedRates returns a map which maps a rate to each business day in the time period given by
// @dateInit and @dateFinal.
// Rates are weighted by the rate factor. intRates must be sorted by date in increasing order.
func WeightedRates(intRates []*InterestRate, dateInit, dateFinal time.Time, holidays []time.Time, startIndex int) (map[time.Time]float64, int) {
rateMap := make(map[time.Time]float64)
// Adjust rate if dateInit is not a business day
initialFactor := 0
auxDate := dateInit
for !utils.CheckWeekDay(auxDate) || utils.ContainsDay(holidays, auxDate) {
initialFactor++
auxDate = auxDate.AddDate(0, 0, 1)
}
// Get index for first date inside global range
for utils.AfterDay(dateInit, intRates[startIndex].EffectiveDate) {
startIndex++
}
// Return index as cursor inside of entire range requested in API call
index := startIndex
// If first dateInit is non-business day, get previous rate
if !utils.CheckWeekDay(dateInit) || utils.ContainsDay(holidays, dateInit) {
startIndex = startIndex - 1
rateMap[dateInit] = float64(initialFactor) * intRates[startIndex].Value
startIndex++
}
// Compute compounded rate for period [dateInit, dateFinal]
for utils.AfterDay(dateFinal, intRates[startIndex].EffectiveDate) && startIndex < len(intRates)-1 {
ratefactor, _ := ratederivatives.RateFactor(intRates[startIndex].EffectiveDate, holidays)
rateMap[intRates[startIndex].EffectiveDate] = float64(ratefactor) * intRates[startIndex].Value
startIndex++
}
return rateMap, index
}
// GetCompoundedAvgRange returns the compounded average of the index @symbol over rolling @calDays calendar days.
func (datastore *DB) GetCompoundedAvgRange(symbol string, dateInit, dateFinal time.Time, calDays, daysPerYear int, rounding int) (values []*InterestRate, err error) {
dateStart := dateInit.AddDate(0, 0, -calDays)
// Get first publication date for the rate with @symbol in order to check feasibility of dateInit
firstPublication, err := datastore.GetFirstDate(symbol)
if err != nil {
return []*InterestRate{}, err
}
if utils.AfterDay(firstPublication, dateStart) {
log.Error("dateStart cannot be earlier than first publication date.")
err = errors.New("dateStart cannot be earlier than first publication date")
return []*InterestRate{}, err
}
// Get rate data from database
ratesAPI, err := datastore.GetInterestRateRange(symbol, dateStart.Format("2006-01-02"), dateFinal.Format("2006-01-02"))
if err != nil {
return []*InterestRate{}, err
}
if len(ratesAPI) == 0 {
err = errors.New("no rate information for this period")
return []*InterestRate{}, err
}
// Check, whether first day is a holiday or weekend. If so, prepend rate of
// preceding business day (outside the considered time range!).
// Determine holidays through missing database entries
existDates := []time.Time{}
for _, entry := range ratesAPI {
existDates = append(existDates, (*entry).EffectiveDate)
}
holidays := utils.GetHolidays(existDates, dateStart, dateFinal)
if utils.ContainsDay(holidays, dateStart) || !utils.CheckWeekDay(dateStart) {
firstRate, err := datastore.GetInterestRate(symbol, dateStart.Format("2006-01-02"))
if err != nil {
return []*InterestRate{}, err
}
ratesAPI = append([]*InterestRate{firstRate}, ratesAPI...)
}
// Consider last business day if last given day is holiday or weekend
for utils.ContainsDay(holidays, dateFinal) || !utils.CheckWeekDay(dateFinal) {
dateFinal = dateFinal.AddDate(0, 0, -1)
}
// Sort ratesApi (type []*InterestRates) in increasing order according to date
// and remove the data for the final date, as only past values are compounded.
sort.Slice(ratesAPI, func(i, j int) bool {
return (ratesAPI[i].EffectiveDate).Before(ratesAPI[j].EffectiveDate)
})
ratesAPI = ratesAPI[:len(ratesAPI)-1]
// Iterate through interest periods of length @calDays
cursor := 0
for utils.AfterDay(dateFinal, dateInit) {
// Get starting date of compounding period
dateStart := dateInit.AddDate(0, 0, -calDays)
if utils.ContainsDay(holidays, dateInit) || !utils.CheckWeekDay(dateInit) {
// No rate information on holidays and weekends
dateInit = dateInit.AddDate(0, 0, 1)
} else {
// get a weighted rate for each business day in period of interest
mapRates, index := WeightedRates(ratesAPI, dateStart, dateInit, holidays, cursor)
cursor = index
auxDate := dateStart
ratesPeriod := []float64{}
for utils.AfterDay(dateInit, auxDate) {
val, ok := mapRates[auxDate]
if ok {
ratesPeriod = append(ratesPeriod, val)
auxDate = auxDate.AddDate(0, 0, 1)
} else {
auxDate = auxDate.AddDate(0, 0, 1)
}
}
compRate, err := ratederivatives.CompoundedRateSimple(ratesPeriod, dateStart, dateInit, daysPerYear, 0)
if err != nil || utils.ContainsDay(holidays, dateInit) {
dateInit = dateInit.AddDate(0, 0, 1)
} else {
// Fill return struct
compAvg := &InterestRate{}
compAvg.Symbol = symbol + strconv.Itoa(calDays) + "_compounded_by_DIA"
compAvg.Value = 100 * (compRate - 1) * float64(daysPerYear) / float64(calDays)
compAvg.EffectiveDate = dateInit
compAvg.Source = ratesAPI[0].Source
// Append data and increment initial date
values = append(values, compAvg)
dateInit = dateInit.AddDate(0, 0, 1)
}
}
}
if rounding != 0 {
for i := range values {
values[i].Value = math.Round(values[i].Value*math.Pow(10, float64(rounding))) / math.Pow(10, float64(rounding))
}
return values, nil
}
return values, nil
}
// ---------------------------------------------------------------------------------------------
// Computation of compounded averages in conservative way, i.e. including higher order terms
// ---------------------------------------------------------------------------------------------
// StraightRates returns a map which maps a rate to each day in the time period. This includes (artificial)
// rate values for non-business days. intRates must be sorted by date in increasing order.
func StraightRates(intRates []*InterestRate) map[time.Time]float64 {
finalDay := intRates[len(intRates)-1].EffectiveDate
count := 0
day := intRates[count].EffectiveDate
rateMap := make(map[time.Time]float64)
rateMap[day] = intRates[count].Value
day = day.AddDate(0, 0, 1)
count++
for utils.AfterDay(finalDay, day) {
if utils.SameDays(day, intRates[count].EffectiveDate) {
// For business day assign rate and increment day
rateMap[day] = intRates[count].Value
day = day.AddDate(0, 0, 1)
count++
} else {
// holiday or weekend gets the previous rate
rateMap[day] = intRates[count-1].Value
day = day.AddDate(0, 0, 1)
}
}
return rateMap
}
// GetCompoundedAvgDIARange returns the compounded average DIA index of @symbol over rolling @calDays calendar days.
func (datastore *DB) GetCompoundedAvgDIARange(symbol string, dateInit, dateFinal time.Time, calDays, daysPerYear int, rounding int) (values []*InterestRate, err error) {
dateStart := dateInit.AddDate(0, 0, -calDays)
// Get first publication date for the rate with @symbol in order to check feasibility of dateInit
firstPublication, err := datastore.GetFirstDate(symbol)
if err != nil {
return []*InterestRate{}, err
}
if utils.AfterDay(firstPublication, dateStart) {
log.Error("dateStart cannot be earlier than first publication date.")
err = errors.New("dateStart cannot be earlier than first publication date")
return []*InterestRate{}, err
}
// Get rate data from database
ratesAPI, err := datastore.GetInterestRateRange(symbol, dateStart.Format("2006-01-02"), dateFinal.Format("2006-01-02"))
if err != nil {
return []*InterestRate{}, err
}
if len(ratesAPI) == 0 {
err = errors.New("no rate information for this period")
return []*InterestRate{}, err
}
// Check, whether first day is a holiday or weekend. If so, prepend rate of
// preceding business day (outside the considered time range!).
// Determine holidays through missing database entries
existDates := []time.Time{}
for _, entry := range ratesAPI {
existDates = append(existDates, (*entry).EffectiveDate)
}
holidays := utils.GetHolidays(existDates, dateStart, dateFinal)
if utils.ContainsDay(holidays, dateStart) || !utils.CheckWeekDay(dateStart) {
firstRate, err := datastore.GetInterestRate(symbol, dateStart.Format("2006-01-02"))
if err != nil {
return []*InterestRate{}, err
}
ratesAPI = append([]*InterestRate{firstRate}, ratesAPI...)
}
// Consider last business day if last given day is holiday or weekend
for utils.ContainsDay(holidays, dateFinal) || !utils.CheckWeekDay(dateFinal) {
dateFinal = dateFinal.AddDate(0, 0, -1)
}
// Sort ratesApi (type []*InterestRates) in increasing order according to date
// and remove the data for the final date, as only past values are compounded.
sort.Slice(ratesAPI, func(i, j int) bool {
return (ratesAPI[i].EffectiveDate).Before(ratesAPI[j].EffectiveDate)
})
ratesAPI = ratesAPI[:len(ratesAPI)-1]
// get a rate for each calendar day in period of interest
mapRates := StraightRates(ratesAPI)
// Iterate through interest period
count := 0
for utils.AfterDay(dateFinal, dateInit) {
// Get compounded rate
dateStart := dateInit.AddDate(0, 0, -calDays)
auxDate := dateStart
ratesPeriod := []float64{}
for i := count; i < count+calDays; i++ {
ratesPeriod = append(ratesPeriod, mapRates[auxDate])
auxDate = auxDate.AddDate(0, 0, 1)
}
compRate, err := ratederivatives.CompoundedRateSimple(ratesPeriod, dateStart, dateInit, daysPerYear, 0)
if err != nil {
dateInit = dateInit.AddDate(0, 0, 1)
} else {
// Fill return struct
compAvg := &InterestRate{}
compAvg.Symbol = symbol + strconv.Itoa(calDays) + "_compounded_by_DIA"
compAvg.Value = 100 * (compRate - 1) * float64(daysPerYear) / float64(calDays)
compAvg.EffectiveDate = dateInit
compAvg.Source = ratesAPI[0].Source
// Append data and increment initial date
values = append(values, compAvg)
dateInit = dateInit.AddDate(0, 0, 1)
count++
}
}
if rounding != 0 {
for i := range values {
values[i].Value = math.Round(values[i].Value*math.Pow(10, float64(rounding))) / math.Pow(10, float64(rounding))
}
return values, nil
}
return values, nil
}
// ---------------------------------------------------------------------------------------
// Auxiliary functions
// ---------------------------------------------------------------------------------------
// ExistInterestRate returns true if a database entry with given date stamp exists,
// and false otherwise.
// @date should be a substring of a string formatted as "yyyy-mm-dd hh:mm:ss".
func (datastore *DB) ExistInterestRate(symbol, date string) bool {
pattern := "*" + symbol + "_" + date + "*"
strSlice := datastore.redisClient.Keys(pattern).Val()
return len(strSlice) != 0
}
// matchKeyInterestRate returns the key in the database db with the youngest timestamp
// younger than the date @date, given as substring of a string formatted as "yyyy-mm-dd hh:mm:ss".
func (datastore *DB) matchKeyInterestRate(symbol, date string) (string, error) {
exDate, err := datastore.findLastDay(symbol, date)
if err != nil {
return "", err
}
// Determine all database entries with given date
pattern := "*" + symbol + "_" + exDate + "*"
strSlice := datastore.redisClient.Keys(pattern).Val()
var strSliceFormatted []string
layout := "2006-01-02 15:04:05"
for _, key := range strSlice {
date, _ := time.Parse(layout, key)
strSliceFormatted = append(strSliceFormatted, date.String())
}
_, index := utils.MaxString(strSliceFormatted)
return strSlice[index], nil
}
// findLastDay returns the youngest date before @date that has an entry in the database.
// @date should be a substring of a string formatted as "yyyy-mm-dd hh:mm:ss"
func (datastore *DB) findLastDay(symbol, date string) (string, error) {
maxDays := 30 // Remark: This could be a function parameter as well...
for count := 0; count < maxDays; count++ {
if datastore.ExistInterestRate(symbol, date) {
return date, nil
}
// If date has no entry, look for one the day before
date = utils.GetYesterday(date, "2006-01-02")
}
// If no entry found in the last @maxDays days return error
err := errors.New("No database entry found in the last " + strconv.FormatInt(int64(maxDays), 10) + "days.")
return "", err
}