generated from JuliaPluto/static-export-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyFuncs.jl
5467 lines (5021 loc) · 211 KB
/
myFuncs.jl
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
#using Revise, CSV, DataFrames, Dates, Distributions, Format, Grep, HypertextLiteral, Ipopt, JuMP, LinearAlgebra, Loess, NaNStatistics, Optim, Plots, PrettyTables, Random, XLSX
# holiday calendars from https://www.sifma.org/resources/general/us-holiday-archive/
################ Date and calendar functions
us_trading_holidays_2015 = [
Date(2015, 1, 1),
Date(2015, 1, 19),
Date(2015, 4, 3),
Date(2015, 5, 25),
Date(2015, 7, 3),
Date(2015, 9, 7),
Date(2015, 10, 12),
Date(2015, 11, 11),
Date(2015, 11, 26),
Date(2015, 12, 25),
]
us_trading_holidays_2016 = [
Date(2016, 1, 1),
Date(2016, 1, 18),
Date(2016, 3, 25),
Date(2016, 5, 30),
Date(2016, 7, 4),
Date(2016, 9, 5),
Date(2016, 10, 10),
Date(2016, 11, 11),
Date(2016, 11, 24),
Date(2016, 12, 26),
]
us_trading_holidays_2017 = [
Date(2017, 1, 2),
Date(2017, 1, 16),
Date(2017, 2, 20),
Date(2017, 4, 14),
Date(2017, 5, 29),
Date(2017, 7, 4),
Date(2017, 9, 4),
Date(2017, 10, 9),
Date(2017, 11, 23),
Date(2017, 12, 25),
]
us_trading_holidays_2018 = [
Date(2018, 1, 1),
Date(2018, 1, 15),
Date(2018, 2, 19),
Date(2018, 3, 30),
Date(2018, 5, 28),
Date(2018, 7, 4),
Date(2018, 9, 3),
Date(2018, 10, 8),
Date(2018, 11, 12),
Date(2018, 11, 22),
Date(2018, 12, 25),
]
us_trading_holidays_2019 = [
Date(2019, 1, 1),
Date(2019, 1, 21),
Date(2019, 2, 18),
Date(2019, 4, 19),
Date(2019, 5, 27),
Date(2019, 7, 4),
Date(2019, 9, 2),
Date(2019, 10, 14),
Date(2019, 11, 11),
Date(2019, 11, 28),
Date(2019, 12, 25),
]
us_trading_holidays_2020 = [
Date(2020, 1, 1),
Date(2020, 1, 20),
Date(2020, 2, 17),
Date(2020, 4, 10),
Date(2020, 5, 25),
Date(2020, 7, 3),
Date(2020, 9, 7),
Date(2020, 10, 12),
Date(2020, 11, 11),
Date(2020, 11, 26),
Date(2020, 12, 25),
]
us_trading_holidays_2021 = [
Date(2021, 1, 1),
Date(2021, 1, 18),
Date(2021, 2, 15),
Date(2021, 4, 2),
Date(2021, 5, 31),
Date(2021, 7, 5),
Date(2021, 9, 6),
Date(2021, 10, 11),
Date(2021, 11, 11),
Date(2021, 11, 25),
Date(2021, 12, 24),
]
us_trading_holidays_2022 = [
Date(2022, 1, 17),
Date(2022, 2, 21),
Date(2022, 4, 15),
Date(2022, 5, 30),
Date(2022, 6, 20),
Date(2022, 7, 4),
Date(2022, 9, 5),
Date(2022, 11, 24),
Date(2022, 12, 26),
]
us_trading_holidays_2023 = [
Date(2023, 1, 2),
Date(2023, 1, 16),
Date(2023, 2, 20),
Date(2023, 4, 7),
Date(2023, 5, 29),
Date(2023, 6, 19),
Date(2023, 7, 4),
Date(2023, 9, 4),
Date(2023, 11, 23),
Date(2023, 12, 25),
]
us_trading_holidays_2024 = [
Date(2024, 1, 1),
Date(2024, 1, 15),
Date(2024, 2, 19),
Date(2024, 3, 29),
Date(2024, 5, 27),
Date(2024, 6, 19),
Date(2024, 7, 4),
Date(2024, 9, 2),
Date(2024, 11, 28),
Date(2024, 12, 25),
]
us_trading_holidays_2025 = [
Date(2025, 1, 1),
#Date(2025, 1, 9), #this is a trading holiday to honor jimmy carter, but it's a good settlement day - and i don't distinguish trading from settlement holidays
Date(2025, 1, 20),
Date(2025, 2, 17),
Date(2025, 4, 18),
Date(2025, 5, 26),
Date(2025, 6, 19),
Date(2025, 7, 4),
Date(2025, 9, 1),
Date(2025, 11, 27),
Date(2025, 12, 25),
]
us_trading_holidays_2026 = [
Date(2026, 1, 1),
Date(2026, 1, 19),
Date(2026, 2, 16),
Date(2026, 4, 3),
Date(2026, 5, 25),
Date(2026, 6, 19),
Date(2026, 7, 3),
Date(2026, 9, 7),
Date(2026, 11, 26),
Date(2026, 12, 25),
]
us_trading_holidays = vcat(
us_trading_holidays_2015,
us_trading_holidays_2016,
us_trading_holidays_2017,
us_trading_holidays_2018,
us_trading_holidays_2019,
us_trading_holidays_2020,
us_trading_holidays_2021,
us_trading_holidays_2022,
us_trading_holidays_2023,
us_trading_holidays_2024,
us_trading_holidays_2025,
us_trading_holidays_2026
)
fed_end_of_meeting_dates = [
Date(2015,1,28)
Date(2015,3,18)
Date(2015,4,29)
Date(2015,6,17)
Date(2015,7,29)
Date(2015,9,17)
Date(2015,10,28)
Date(2015,12,16)
Date(2016, 1, 27)
Date(2016, 3, 16)
Date(2016, 4, 27)
Date(2016, 6, 15)
Date(2016, 7, 27)
Date(2016, 9, 21)
Date(2016, 11, 2)
Date(2016, 12, 14)
Date(2017, 2, 1)
Date(2017, 3, 15)
Date(2017, 5, 3)
Date(2017, 6, 14)
Date(2017, 7, 26)
Date(2017, 9, 20)
Date(2017, 11, 1)
Date(2017, 12, 13)
Date(2018, 1, 31)
Date(2018, 3, 21)
Date(2018, 5, 2)
Date(2018, 6, 13)
Date(2018, 8, 1)
Date(2018, 9, 26)
Date(2018, 11, 8)
Date(2018, 12, 19)
Date(2020, 1, 29)
Date(2020, 3, 3)
Date(2020, 3, 15)
Date(2020, 4, 29)
Date(2020, 6, 10)
Date(2020, 7, 29)
Date(2020, 9, 16)
Date(2020, 11, 5)
Date(2020, 12, 16)
Date(2016, 1, 27)
Date(2016, 3, 17)
Date(2016, 4, 28)
Date(2016, 6, 16)
Date(2016, 7, 28)
Date(2016, 9, 22)
Date(2016, 11, 3)
Date(2016, 12, 15)
Date(2022, 1, 26)
Date(2022, 3, 16)
Date(2022, 5, 4)
Date(2022, 6, 15)
Date(2022, 7, 27)
Date(2022, 9, 21)
Date(2022, 11, 2)
Date(2022, 12, 14)
Date(2023, 2, 1)
Date(2023, 3, 22)
Date(2023, 5, 3)
Date(2023, 6, 14)
Date(2023, 7, 26)
Date(2023, 9, 20)
Date(2023, 11, 1)
Date(2023, 12, 13)
Date(2024, 1, 31)
Date(2024, 3, 20)
Date(2024, 5, 1)
Date(2024, 6, 12)
Date(2024, 7, 31)
Date(2024, 9, 18)
Date(2024, 11, 7)
Date(2024, 12, 18)
Date(2025, 1, 29)
Date(2025, 3, 19)
Date(2025, 5, 7)
Date(2025, 6, 18)
Date(2025, 7, 30)
Date(2025, 9, 17)
Date(2025, 10, 29)
Date(2025, 12, 10)
Date(2026, 1, 28)
Date(2026, 3, 18)
Date(2026, 4, 29)
Date(2026, 6, 17)
Date(2026, 7, 29)
Date(2026, 9, 16)
Date(2026, 10, 28)
Date(2026, 12, 9)
]
function bd(d, holidays=us_trading_holidays, nonBdDir=1)
while true
not_biz_day = in(d, holidays) | (dayofweek(d) > 5)
if not_biz_day
d = d + Day(nonBdDir)
else
break
end
end
d
end
function workday(d, n, holidays=us_trading_holidays)
if n > 0
nonBdDir = 1
else
nonBdDir = -1
end
d = bd(d, holidays, nonBdDir)
for i = 1:abs(n)
d = bd(d + Day(nonBdDir), holidays, nonBdDir)
end
d
end
function bizDayAdjustedThirdFriday(d) #i.e. option expiry of month containing date d
#rolls back to Thurs if Fri is a holiday
d = floor(d, Month) # returns 1st day of month
#dayofweek fn returns 1,2,...,7 for Monday, Tuesday,...,Sunday
x = dayofweek(d)
if x > 5
x = 12 - x
elseif x <= 5
x = 5 - x
end
x = x + 14
return workday(d + Day(x), 0)
end
################ Fitting and utility functions
function ls_fit(x, y, xhat, order)
# does least squares fit of y on x and returns
# (xhat, yhat = f(xhat), tuple of coeffs) where f(x) comes from the
# least squares fit of y on x
iter = Iterators.flatten((0, 1:order))
X = zeros(length(x), length(collect(iter)))
for (indx, value) in Iterators.enumerate(iter)
X[:, indx] = x .^ value
end
#B = y
ls_coeffs = try
X \ y
catch e
[NaN, NaN]
end
yhat = zeros(length(xhat))
for (indx, value) in Iterators.enumerate(iter)
yhat = yhat .+ ls_coeffs[indx] .* xhat .^ value
end
return (xhat, yhat, ls_coeffs)
end
function ls_geomean(x, y) #as per the Tofallis paper
X = hcat(ones(length(x)), x)
Y = hcat(ones(length(y)), y)
(b1, m1) = X\y #coeffs of regressing y on x, y = m1 * x + b + noise
(bint, mint) = Y\x #coeffs of regressing x on y, i.e. x = mint * y + bint + noise <--> y = (1/mint) * x + (-bind/mint) + noise
(b2, m2) = (-bint/mint, 1/mint)
m = sqrt(m1 * m2)
b = sum(y - m * x) / length(x)
ξ = y .- (m*x .+ b)
return(b, m, ξ)
end
function ls_fit2(x, y, xhat, order)
#uses only even powers of x plus linear to fit
# does least squares fit of y on x and returns
# (xhat, yhat = f(xhat)) where f(x) comes from the
# least squares fit of y on x
if isodd(order)
order = order - 1
end
pows = sort(vcat(1, collect(0:2:order)))
A = zeros(length(x), length(pows))
for i in eachindex(pows)
A[:, i] = x .^ pows[i]
end
B = y
ls_coeffs = A \ B
yhat = zeros(length(xhat))
for i in eachindex(pows)
yhat = yhat .+ ls_coeffs[i] .* xhat .^ pows[i]
end
return (xhat, yhat, ls_coeffs)
end
################ Yield Curve functions
function updateRatesHist()
if Sys.isapple()
path = "/Users/alex/Library/CloudStorage/Dropbox/Code/Julia/data/on_rate_hists/"
elseif Sys.islinux()
path = "/home/alex/Dropbox/Code/Julia/data/on_rate_hists/"
end
# assumes Search.xlsx has been created from https://www.newyorkfed.org/markets/reference-rates/obfr
newData = DataFrame(XLSX.readtable(path * "Search.xlsx", "Results"))[:, 1:3]
fnam1 = path * "sofr_obfr_ff_hist.csv"
if filesize(fnam1) > 0
existingData = DataFrame(CSV.File(fnam1))[:, 1:3]
allData = unique(vcat(newData, existingData))
else
allData = newData
end
CSV.write(fnam1, allData)
fnam2 = path * "rateHist.csv"
rateHist = copy(allData)
#rateHist = DataFrame(CSV.File(fnam1))
#rateHist = rateHist[:, 1:3]
rename!(rateHist, [:date, :variable, :value])
rateHist = unique(rateHist)
rateHist = unstack(rateHist)
rateHist.date = Date.(rateHist.date, dateformat"m/d/y")
rateHist = sort(rateHist, order(:date, rev=false))
rename!(rateHist, [:date, :ff, :obfr, :sofr])
# now create total return series which we'll need for futures inside their accrual periods
rateHist.sofrTotRet = coalesce.(rateHist.sofr,0) .+ NaN
rateHist.obfrTotRet = coalesce.(rateHist.obfr,0) .+ NaN
sofrStartIndx = findfirst(coalesce.(rateHist.sofr,-3) .> 0)
obfrStartIndx = findfirst(coalesce.(rateHist.obfr, -3) .> 0)
rateHist.sofrTotRet[sofrStartIndx] = 1
rateHist.obfrTotRet[obfrStartIndx] = 1
for r = 2:nrow(rateHist)
if r > sofrStartIndx && !ismissing(rateHist.sofr[r])
if !ismissing(rateHist.sofr[r-1])
rateHist.sofrTotRet[r] = rateHist.sofrTotRet[r-1] * (1.0 + rateHist.sofr[r-1] / 100 * (rateHist.date[r] - rateHist.date[r-1]).value / 360)
else #the correctness of this relies upon the fact that there aren't 2 sequential missing values
rateHist.sofrTotRet[r] = rateHist.sofrTotRet[r-2] * (1.0 + rateHist.sofr[r-2] / 100 * (rateHist.date[r] - rateHist.date[r-2]).value / 360)
end
end
if r > obfrStartIndx && !ismissing(rateHist.obfr[r])
if !ismissing(rateHist.obfr[r-1])
rateHist.obfrTotRet[r] = rateHist.obfrTotRet[r-1] * (1.0 + rateHist.obfr[r-1] / 100 * (rateHist.date[r] - rateHist.date[r-1]).value / 360)
else #the correctness of this relies upon the fact that there aren't 2 sequential missing values
rateHist.obfrTotRet[r] = rateHist.obfrTotRet[r-2] * (1.0 + rateHist.obfr[r-2] / 100 * (rateHist.date[r] - rateHist.date[r-2]).value / 360)
end
end
end
CSV.write(fnam2, rateHist)
end
function updateFutsHist(eliminateZeroVolumeDays=false)
if Sys.isapple()
path = "/Users/alex/Library/CloudStorage/Dropbox/Code/Julia/data/"
elseif Sys.islinux()
path = "/home/alex/Dropbox/Code/Julia/data/"
end
monthCodes = DataFrame(code=["F", "G", "H", "J", "K", "M", "N", "Q", "U", "V", "X", "Z"], month=January:December)
function thirdwednesday(d::Date)
d = floor(d, Month) # returns 1st day of month
#dayofweek fn returns 1,2,...,7 for Monday, Tuesday,...,Sunday
x = dayofweek(d)
if 3 - x < 0
x = 10 - x
else
x = 3 - x
end
x = x + 14
return d + Day(x)
end
# firstDay will only work for futures after the year 2000
function firstDay(ticker::String)
# if 3rd Wednesday or 1st of month is non-biz day then returns prev biz day
month = monthCodes.month[findall(monthCodes.code .== uppercase(string(ticker[3])))[1]]
#year = Year(today()).value - Year(today()).value % 10 + parse(Int64, ticker[5]) # only worked for futs in the 2020s!
year = 2000 + 10 * parse(Int64, ticker[4]) + parse(Int64, ticker[5])
if ticker[1:2] == "sq"
startDate = thirdwednesday(Date(year, month, 1))
elseif ticker[1:2] ∈ ["sl", "zq"]
startDate = Date(year, month, 1)
end
return startDate
end
# lasttDay will only work for futures after the year 2000
function lastDay(ticker::String)
month = monthCodes.month[findall(monthCodes.code .== uppercase(string(ticker[3])))[1]]
#year = Year(today()).value - Year(today()).value % 10 + parse(Int64, ticker[5]) # only worked for futs in the 2020s!
year = 2000 + 10 * parse(Int64, ticker[4]) + parse(Int64, ticker[5])
if ticker[1:2] == "sq"
if month < 10
endDate = thirdwednesday(Date(year, month + 3, 1)) - Day(1)
else
endDate = thirdwednesday(Date(year + 1, month - 9, 1)) - Day(1)
end
elseif ticker[1:2] ∈ ["sl", "zq"]
d = Date(year, month, 1)
endDate = lastdayofmonth(d)
end
return endDate
end
filepath = path * "futsHist.csv"
global futsHist = DataFrame(date=String[], last=Float64[], volume=Int64[], openInt=Int64[], bct=String[])#, firstRateDate=Date[], lastRateDate=Date[])
for dirName ∈ path .* ["sofr_3m_futs/", "sofr_1m_futs/", "ff_futs/"]
fnams = grep("_daily_historical-data", readdir(dirName))
for fnam ∈ fnams
bct = fnam[1:5]
tmp = DataFrame(CSV.File(dirName * fnam, silencewarnings=true))
tmp = tmp[1:nrow(tmp)-1, :]
tmp.bct = string.(1:nrow(tmp))
tmp.bct .= bct
tmp = tmp[:, [1, 5, 8, 9, 10]]
rename!(tmp, [:date, :last, :volume, :openInt, :bct])
futsHist = vcat(futsHist, tmp)
end
end
function convert_to_dates(date_strings::AbstractVector)
# First ensure we have Vector{String}
str_vector = Vector{String}(date_strings)
dates = similar(str_vector, Date)
for (i, ds) in enumerate(str_vector)
if occursin("/", ds)
# Handle mm/dd/yyyy format
dates[i] = Date(ds, dateformat"mm/dd/yyyy")
else
# Handle yyyy-mm-dd format
dates[i] = Date(ds, dateformat"yyyy-mm-dd")
end
end
return dates
end
futsHist.date .= convert_to_dates(futsHist.date)
sort!(futsHist,:date)
futsHist.last = Float64.(futsHist.last)
futsHist.volume = Int64.(futsHist.volume)
futsHist.openInt = Int64.(futsHist.openInt)
futsHist.firstRateDate = copy(futsHist.date)
futsHist.lastRateDate = copy(futsHist.date)
for r = 1:nrow(futsHist)
futsHist.firstRateDate[r] = firstDay(futsHist.bct[r])
futsHist.lastRateDate[r] = lastDay(futsHist.bct[r])
end
if eliminateZeroVolumeDays
futsHist = futsHist[futsHist.volume .>0, :]
end
# because we're going to interleave 1m and 3m sofr futs, let's give them a common date range
indx_sq = findall(contains.(futsHist.bct, "sq") .== 1)
indx_sl = findall(contains.(futsHist.bct, "sl") .== 1)
min_date_sq = minimum(futsHist.date[indx_sq])
max_date_sq = maximum(futsHist.date[indx_sq])
min_date_sl = minimum(futsHist.date[indx_sl])
max_date_sl = maximum(futsHist.date[indx_sl])
min_date = max(min_date_sq, min_date_sl)
max_date = min(max_date_sq, max_date_sl)
rows2delete1 = findall(contains.(futsHist.bct, "sq") .== 1 .&& futsHist.date .< min_date)
rows2delete2 = findall(contains.(futsHist.bct, "sq") .== 1 .&& futsHist.date .> max_date)
rows2delete3 = findall(contains.(futsHist.bct, "sl") .== 1 .&& futsHist.date .< min_date)
rows2delete4 = findall(contains.(futsHist.bct, "sl") .== 1 .&& futsHist.date .> max_date)
delete!(futsHist, sort(unique(union(rows2delete1, rows2delete2, rows2delete3, rows2delete4))))
sort!(futsHist, [:date, :lastRateDate])
#if false
## change this part so it's not dependent on EST
lastFullTradingDay = bd(today(), us_trading_holidays, -1)
c1 = Hour(now()).value >= 10
c2 = Hour(now()).value == 9 && Minute(now()).value > 30
c3 = Hour(now()).value <= 15
if (c1 || c2) && c3
intraDayFlag = true
else
intraDayFlag = false
end
#futsHist = DataFrame(CSV.File(path * "futsHist.csv"))
if lastFullTradingDay < today() || intraDayFlag
futsHist = futsHist[futsHist.date.<today(), :]
end
futsHist = futsHist[futsHist.date .<= today(), :] # to remove post close data
CSV.write(filepath, futsHist)
#end
end
function curveStripperFromFuts(baseRate, d, dEnd=d + Year(2), futs=missing, d_lastRateSet=missing, r_lastRateSet=missing, r_currRateSet=missing; eliminateZeroVolumeDays=true)
#=
to convexity adjust the futures prices we should raise the price / lower the
implied rate by sig^2 T1 T2 / 2 where the futures interval starts at T1 and
ends at T2 (sig is vol for the forward rate and has units time^-3/2 because dr ~ sig * dz).
The sign is obvious from the negative convexity implied from margining: rates go up, fut pxs go down -> borrow money at higher rate to keep up w/ variation margining rates go down, fut pxs go up -> take money out of margin account and invest at lower rates. this means that by being long the future you're effectively locking in a lower rate than 100 - futpx, hence we reduce the implied rate by the convexity adjustment.
the more rates jiggle the more costly this effect also note [rate]= 1/time =
N.B. for SOFR futures that average a series of daily fixings from T1 to T2 we can
approximate things well with sig^2 * Tbar^2 /2 where Tbar = (T1+T2)/2 and sig refers to imp vol for 1day rates at expiry Tbar
r_repo =#
begin
if Sys.isapple()
path = "/Users/alex/Library/CloudStorage/Dropbox/Code/Julia/data/"
elseif Sys.islinux()
path = "/home/alex/Dropbox/Code/Julia/data/"
end
end
#=
we will choose lastRateSet and d_lastRateSet to reference d rather than workday(d,-1). this is because the rate set only changes on fed dates (to a close approximation) and on a fed date they've announced the rate that's going to print the next day, so we already know it and it's baked into the futures closing prices on d
=#
if ismissing(d_lastRateSet) || ismissing(r_lastRateSet)
rateHist = DataFrame(CSV.File(path * "/on_rate_hists/rateHist.csv"))
missingIndx = findall(ismissing.(rateHist[:, lowercase(baseRate)]))
if length(missingIndx) > 0
deleteat!(rateHist, missingIndx)
end
indx_earlier = findall(rateHist.date .< d)
indx_missing = findall(ismissing.(rateHist[:, lowercase(baseRate)]))
indx_earlier = setdiff(indx_earlier, indx_missing)
i_lastRateSet = maximum(indx_earlier)
d_lastRateSet = rateHist.date[i_lastRateSet]
r_lastRateSet = rateHist[i_lastRateSet, lowercase(baseRate)]
end
if ismissing(r_currRateSet)
indx = findall(rateHist.date .>= d)
if length(indx) > 0
r_currRateSet = rateHist[minimum(indx), lowercase(baseRate)]
else
r_currRateSet = r_lastRateSet
end
end
if ismissing(futs)
futsHist = DataFrame(CSV.File(path * "futsHist.csv"))
syms = futsHist.bct
if lowercase(baseRate) == "sofr"
indx1 = findall(contains.(syms, "sq") .== 1)
indx2 = findall(contains.(syms, "sl") .== 1)
indx = sort(unique(vcat(indx1, indx2)))
elseif lowercase(baseRate) == "ff"
indx = findall(contains.(syms, "zq") .== 1)
end
futsHist = futsHist[indx, :]
futs = futsHist[findall(futsHist.date .== d), :]# .&& futsHist.volume .> 100), :] # .&& futsHist.openInt .> 100), :]
if eliminateZeroVolumeDays
futs = futs[futs.volume .> 0, :]
end
futs = futs[futs.lastRateDate .> d .&& futs.firstRateDate .<= dEnd, :]
sort!(futs, [:date, :lastRateDate])
#= we'll build the curve from the first 5 1m sofr futs and then 3m sofr futures on the HMUZ cycle that end after the 5th 1m future ends
*** CME methodology for term SOFR construction is described here:
https://www.cmegroup.com/market-data/files/cme-term-sofr-reference-rates-benchmark-methodology.pdf which is, in turn, based on SSRN-id3352598.pdf
=#
if lowercase(baseRate) == "sofr"
delete!(futs, findall(contains.(futs.bct, "sq") .== 1 .&& Dates.monthname.(futs.lastRateDate) .∉ Ref(["March", "June", "September", "December"])))
end
end
if lowercase(baseRate) == "sofr"
indx1m = findall(contains.(futs.bct, "sl") .== 1)
indx1m = indx1m[1:5]
indx3m = findall(contains.(futs.bct, "sq") .== 1 .&& futs.lastRateDate .> futs.lastRateDate[indx1m[end]])
futs = futs[sort(vcat(indx1m, indx3m)), :]
end
futs.lockedInTRorSum = futs.last .+ NaN
for r = 1:nrow(futs)
if futs.firstRateDate[r] < d
if futs.bct[r][1:2] == "sq"
# dates ends on last biz day prior to d
dates = sort(unique(bd.(futs.firstRateDate[r]:Day(1):d-Day(1), Ref(us_trading_holidays), Ref(-1))))
nd = length(dates)
prevRateSettings = DataFrame(date=dates, rate=zeros(nd) .+ NaN)
for i = 1:nd
if i == 1
j = maximum(findall(rateHist.date .<= dates[1]))
else
j = findall(rateHist.date .== dates[i])
end
if length(j) > 0
prevRateSettings.rate[i] = rateHist[j[1], lowercase(baseRate)]
else # this else clause shouldn't normally be activated since we're looping over biz days only
prevRateSettings.rate[i] = prevRateSettings[i-1, 2]
end
end
futs.lockedInTRorSum[r] = 1
for i = 1:nd-1
futs.lockedInTRorSum[r] = futs.lockedInTRorSum[r] * (1 + 0.01 * prevRateSettings.rate[i] * (dates[i+1] - dates[i]).value / 360)
end
futs.lockedInTRorSum[r] = futs.lockedInTRorSum[r] * (1 + 0.01 * prevRateSettings.rate[end] * (d - dates[end]).value / 360)
else # sl and zq
dates = futs.firstRateDate[r]:Day(1):d-Day(1)
nd = length(dates)
prevRateSettings = DataFrame(date=dates, rate=zeros(nd) .+ NaN)
for i = 1:nd
if i == 1
j = maximum(findall(rateHist.date .<= dates[1]))
else
j = findall(rateHist.date .== dates[i])
end
if length(j) > 0
prevRateSettings.rate[i] = rateHist[j[1], lowercase(baseRate)]
else
prevRateSettings.rate[i] = prevRateSettings[i-1, 2]
end
end
futs.lockedInTRorSum[r] = sum(prevRateSettings.rate)
end
end
end
fedDates = workday.(fed_end_of_meeting_dates, 1)
fedDates = sort(fedDates[fedDates.>=d.&&fedDates.<=futs.lastRateDate[end]])
# let's create the intervals within which the o/n rate will be piecewise const
intervals = DataFrame(startDate=fedDates[1:end-1], endDate=vcat(fedDates[2:end] .- Day(1)))
indx = findall(futs.lastRateDate .> fedDates[end])
if length(indx) > 0
for i ∈ indx
intervals = vcat(intervals, DataFrame(startDate=intervals.endDate[end] + Day(1), endDate=futs.lastRateDate[i]))
end
end
nVars = nrow(intervals)
#=
we define 'x' to be the set of piecewise constant o/n rates that we will solve
for, and we initilize x to be the average futures rate - just to have something easy and not entirely crazy
=#
xInit = ones(nVars) * (100 - sum(futs.last) / nrow(futs))
function makeRates(x, rinfo=intervals, ron=r_currRateSet, valDate=d; bizDaysOnly=false)
rinfo.rate = x
if valDate < rinfo.startDate[1]
rinfo = vcat(DataFrame(startDate=valDate, endDate=rinfo.startDate[1] - Day(1), rate=ron), rinfo)
end
allDates = valDate:Day(1):rinfo.endDate[end]
if bizDaysOnly
allDates = sort(unique(bd.(allDates)))
end
nd = length(allDates)
obj = DataFrame(date=allDates, rate=zeros(nd) .+ NaN)
for i = 1:nrow(rinfo)
indx = findall(allDates .>= rinfo.startDate[i] .&& allDates .<= rinfo.endDate[i])
obj.rate[indx] .= rinfo.rate[i]
end
obj
end
function calcFutPx(x, symbol, rinfo, futs, r_curr)
r = findall(string.(futs.bct) .== symbol)[1]
d = futs.date[1]
d1 = futs.firstRateDate[r]
d2 = futs.lastRateDate[r]
rinfo.rate = x
if d < rinfo.startDate[1]
rinfo = vcat(DataFrame(startDate=d, endDate=rinfo.startDate[1] - Day(1), rate=r_curr), rinfo)
end
lastRow = minimum(findall(d2 .<= rinfo.endDate))
firstRow = maximum(findall(d1 .>= rinfo.startDate), init=1)
if symbol[1:2] == "sq"
if futs.firstRateDate[r] < d
tr = futs.lockedInTRorSum[r]
else
tr = 1
end
for r = firstRow:lastRow
tr = tr * (1 + 0.01 * rinfo.rate[r] / 360)^(1 + (min(d2, rinfo.endDate[r]) - max(d1, rinfo.startDate[r])).value)
end
tr = tr * (1 + 0.01 * rinfo.rate[lastRow] / 360)^((workday(d2, 1) - d2).value - 1)
rfut = 100 * (tr - 1) * 360 / (workday(d2, 1) - d1).value
futpx = 100 - rfut
return futpx
elseif symbol[1:2] ∈ ["sl", "zq"]
if futs.firstRateDate[r] < d
mysum = futs.lockedInTRorSum[r]
else
mysum = 0
end
# we rely on the fact that only monthly contracts use the average rate to settle
# therefore, 1) futs.lastDate is the end-of-month and we can just use the "day" function
# 2) there are at most 2 rows of rinfo that apply
for r = firstRow:lastRow
mysum = mysum + rinfo.rate[r] * (1 + (min(d2, rinfo.endDate[r]) - max(d1, rinfo.startDate[r])).value)
end
avgrate = mysum / day(d2)
futpx = 100 - avgrate
end
return futpx
end
function fmin(x, futs, rinfo, lambda)
futs = futs[futs.lastRateDate.<=rinfo.endDate[end], :]
nf = nrow(futs)
v1 = futs.last
v2 = zeros(nf) .+ NaN
for i = 1:nf
v2[i] = calcFutPx(x, string(futs.bct[i]), rinfo, futs, r_currRateSet)
end
1 / nrow(futs) * sum((v1 - v2) .^ 2) + lambda * sum(diff(x) .^ 2)
#1 / nrow(futs) * sum((v1 - v2) .^ 2) + lambda * sum(diff(x[1:nrow(rinfo)]) .^ 2)
end
lambda = 0.001
res = Optim.optimize(x -> fmin(x, futs, intervals, lambda), xInit, BFGS())#, Optim.Options(x_tol=.005))
x = Optim.minimizer(res)
# ycinfo will have rates for all dates but dfs only for biz days
#makeRates(x, rinfo = intervals, ron=r_currRateSet, valDate=d; bizDaysOnly=false)
ycinfo = makeRates(x, bizDaysOnly=false)
ycinfo2 = makeRates(x, bizDaysOnly=true)
ycinfo2.df = ones(nrow(ycinfo2))
ycinfo2.df[2:end] = 1 ./ cumprod(1 .+ 0.01 * ycinfo2.rate[1:end-1] .* Dates.value.(diff(ycinfo2.date)) / 360)
ycinfo.df = zeros(nrow(ycinfo)) .+ NaN
for r = 1:nrow(ycinfo2)
#println(ycinfo2.date[r])
i = findall(ycinfo.date .== ycinfo2.date[r])[1]
ycinfo.df[i] = ycinfo2.df[r]
end
futs.theoLast = futs.last .+ NaN
for r = 1:nrow(futs)
futs.theoLast[r] = calcFutPx(x, futs.bct[r], intervals, futs, r_currRateSet)
end
futs.bpsError = round.(100 * (futs.theoLast - futs.last), digits=1)
futs = futs[!, [:date, :bct, :last, :theoLast, :bpsError, :volume, :openInt, :firstRateDate, :lastRateDate, :lockedInTRorSum]]
intervals.rate = x
if d < intervals.startDate[1]
intervals = vcat(DataFrame(startDate=d, endDate=intervals.startDate[1] - Day(1), rate=r_currRateSet), intervals)
end
#return ycinfo, futs[!, 1:ncol(futs)-1], intervals
return ycinfo, futs, intervals
end
function impliedFutPx(symbol, yc)
(ycinfo, futs, intervals) = yc
r = findall(string.(futs.bct) .== symbol)[1]
d = futs.date[1]
firstRateDate = futs.firstRateDate[r]
lastRateDate = futs.lastRateDate[r]
if lowercase(symbol)[1:2] == "sq"
accrualEndDate = min(ycinfo.date[end], workday(lastRateDate, 1))
r2 = findall(ycinfo.date .== accrualEndDate)[1]
if firstRateDate < d
r1 = 1
tr = futs.lockedInTRorSum[r]
else
r1 = findall(ycinfo.date .== bd(firstRateDate))[1]
tr = 1
end
tr = tr * ycinfo.df[r1] / ycinfo.df[r2]
rfut = 100 * (tr - 1) * 360 / (ycinfo.date[r2] - firstRateDate).value
futpx = 100 - rfut
elseif lowercase(symbol)[1:2] ∈ ["sl", "zq"]
if firstRateDate < d
mysum = futs.lockedInTRorSum[r]
else
mysum = 0
end
indx = findall(ycinfo.date .>= firstRateDate .&& ycinfo.date .<= lastRateDate)
mysum = mysum + sum(ycinfo.rate[indx])
avgrate = mysum / day(futs.lastRateDate[r])
futpx = 100 - avgrate
end
return futpx
end
function df(dt, info)
dt = bd(dt)
(ycinfo, futs, intervals) = info
return ycinfo.df[findall(ycinfo.date .== dt)[1]]
end
function fwd_rate(startDate, endDate, info)
startDate = bd(startDate)
endDate = bd(endDate)
df_start = df(startDate, info)
df_end = df(endDate, info)
fwd = 100 * (df_start / df_end - 1) * 360 / (endDate - startDate).value
return fwd
end
function Rmm2Rcc(rmm, t)
# t in days, rates are in pct
if t == 0
return (0)
elseif rmm <= -36000 / t
return ("rmm is too negative - drives value negative over t days")
else
rcc = 100 * 365 / t * log(1 + 0.01 * rmm * t / 360)
return (rcc)
end
end
function Rcc2Rmm(rcc, t)
# t in days, rates are in pct
if t == 0
return (0)
else
rmm = 100 * 360 / t * (exp(0.01 * rcc * t / 365) - 1)
return (rmm)
end
end
################ European option pricing functions
function BS(optType, S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt)
# note that divamt, dt_exdiv and dt_divpmt need to be array even if there's only one element
premium_settlement = 1
if dt_trade < Date(2024,5,28)
stock_settlement = exercise_settlement = 2
else
stock_settlement = exercise_settlement = 1
end
dt_option_settle = workday(dt_trade, premium_settlement)
dt_stock_settle = workday(dt_trade, stock_settlement)
dt_exp_settle = workday(dt_expiry, exercise_settlement)
days = (dt_expiry - dt_trade).value
t = days / 365
r_csa = log(1 + 0.01 * r_csa_mm_pct * days / 360) / t
r_repo = log(1 + 0.01 * r_repo_mm_pct * days / 360) / t
σ = vol_pct / 100
Z_csa = exp(-r_csa * (dt_exp_settle - dt_option_settle).value / 365)
Z_repo = exp(-r_repo * (dt_exp_settle - dt_stock_settle).value / 365)
divPV = 0
for i = 1:length(divamt)
divPV = divPV + divamt[i] * exp(-r_csa * (dt_divpmt[i] - dt_trade).value / 365)
end
S0 = S - divPV
σ = σ * S / S0
d1 = (log(S0 / K) + (r_repo + σ^2 / 2) * t) / (σ * √t)
#d1 = (log(S0 / K) + (r_csa + σ^2 / 2) * t) / (σ * √t)
d2 = d1 - σ * √t
dist = Normal()
if lowercase(optType)[1] == 'c'
V = Z_csa * (S0 / Z_repo * cdf(dist, d1) - K * cdf(dist, d2))
#=
Δ =
Γ =
Θ =
vega =
=#
elseif lowercase(optType)[1] == 'p'
V = Z_csa * (K * cdf(dist, -d2) - S0 / Z_repo * cdf(dist, -d1))
#=
Δ =
Γ =
Θ =
vega =
=#
end
return V
#return (V, Δ, Γ, Θ, vega)
end
function implied_vol_BS(optPrice, optType, S, K, r_csa_mm_pct, r_repo_mm_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt)
obj(x) = (BS(optType, S, K, r_csa_mm_pct, r_repo_mm_pct, x, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt) - optPrice)^2
res = Optim.optimize(obj, 0, 1000)
vol = Optim.minimizer(res)
vol
end
function conversion_BS(S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt)
callPrice = BS("c", S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt)
putPrice = BS("p", S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt)
conversion = putPrice - callPrice + S - K
return (conversion)
end
function conversion_euro(treeType, S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt, stepsPerDay)
if lowercase(treeType) == "crr"
fn = crr_euro
elseif lowercase(treeType) == "lr"
fn = lr_euro
elseif lowercase(treeType) == "trinomial"
fn = trinomial_euro
end
callPrice = fn("c", S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt, stepsPerDay)[1]
putPrice = fn("p", S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt, stepsPerDay)[1]
conversion = putPrice - callPrice + S - K
return (conversion)
end
function implied_repo_from_conversion_BS(convPrice, S, K, r_csa_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt)
if dt_trade < Date(2024, 5, 28)
stock_settlement = exercise_settlement = 2
else
stock_settlement = exercise_settlement = 1
end
dt_stock_settle = workday(dt_trade, stock_settlement)
dt_exp_settle = workday(dt_expiry, exercise_settlement)
t_stock_settle_to_exp_settle = (dt_exp_settle - dt_stock_settle).value
#= the BS function creates the requisite continuos compounding repo rate as follows:
days = (dt_expiry - dt_trade).value
t = days / 365
r_repo = log(1 + 0.01 * r_repo_mm_pct * days / 360) / t
we want the argument of log to remain positive so we require
1 + .01 * r_repo_mm_pct * days / 360 > 0
r_repo_mm_pct > -360 * 100 / days
=#
max_allowable_repo_pct = r_csa_mm_pct + 100
min_allowable_repo_pct = 1 - 36000 / t_stock_settle_to_exp_settle
obj(x) = (conversion_BS(S, K, r_csa_mm_pct, x, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt) - convPrice)^2
res = Optim.optimize(obj, min_allowable_repo_pct, max_allowable_repo_pct)
if Optim.converged(res)
return Optim.minimizer(res)
else
return NaN
end
end
function crr_euro(optType, S, K, r_csa_mm_pct, r_repo_mm_pct, vol_pct, dt_trade, dt_expiry, divamt, dt_exdiv, dt_divpmt, stepsPerDay)