-
Notifications
You must be signed in to change notification settings - Fork 25
/
db-queries.rkt
1357 lines (1333 loc) · 40 KB
/
db-queries.rkt
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
#lang racket/base
(require db
gregor
racket/string
interactive-brokers-api/base-structs
interactive-brokers-api/response-messages
"logging.rkt"
"params.rkt"
"structs.rkt")
(provide get-1-month-rate
get-condor-analysis
get-date-ohlc
get-date-vol-history
get-dividend-estimates
get-earnings-dates
get-next-earnings-date
get-options
get-position-history
get-position-analysis
get-price-analysis
get-rank-analysis
get-security-name
get-vol-analysis
insert-commission-report
insert-condor-analysis
insert-contract
insert-execution
insert-price-analysis
insert-order
insert-order-note)
(define dbc (postgresql-connect #:server (db-host) #:user (db-user) #:database (db-name) #:password (db-pass)))
(define (get-date-ohlc ticker-symbol start-date end-date)
(let ([price-query (query-rows dbc "
select
date::text,
open,
high,
low,
close
from
polygon.split_adjusted_ohlc(
$1,
case
when $2::text::date > (select max(date) from polygon.ohlc) then (select max(date) from polygon.ohlc)
else $2::text::date
end,
$3::text::date,
false);
"
ticker-symbol
start-date
end-date)])
(map (λ (row) (dohlc (->posix (iso8601->date (vector-ref row 0)))
(vector-ref row 1) (vector-ref row 2) (vector-ref row 3) (vector-ref row 4)))
price-query)))
(define (get-date-vol-history ticker-symbol start-date end-date)
(let ([vol-history-query (query-rows dbc "
select
date::text,
iv_current
from
oic.volatility_history
where
act_symbol = $1 and
date >= $2::text::date and
date <= $3::text::date and
iv_current is not null;
"
ticker-symbol
start-date
end-date)])
(map (λ (row) (dv (->posix (iso8601->date (vector-ref row 0))) (vector-ref row 1)))
vol-history-query)))
(define (get-earnings-dates ticker-symbol start-date end-date)
(map (λ (el) (->posix (iso8601->date el)))
(query-list dbc "
select
date::text
from
zacks.earnings_calendar
where
act_symbol = $1 and
date >= $2::text::date and
date <= $3::text::date
order by
date;
"
ticker-symbol
start-date
end-date)))
;; Get market/sector/industry/stock breakdown for ETF components
(define (get-price-analysis market sector start-date end-date)
(let ([msis-query (query-rows dbc "
with start_close as (
select
c.act_symbol,
c.close / coalesce(split_ratio, 1) as close
from
polygon.ohlc c
left join
(select
act_symbol,
mul(to_factor / for_factor) as split_ratio
from
polygon.split
where
ex_date >= $3::text::date and
ex_date <= $4::text::date
group by
act_symbol) s
on
c.act_symbol = s.act_symbol
where
c.date = (select min(date) from polygon.ohlc where date >= $3::text::date)
), end_close as (
select
act_symbol,
close
from
polygon.ohlc
where
date = (select max(date) from polygon.ohlc where date <= $4::text::date )
)
select
market.market_symbol as market,
market.sector_symbol as sector,
trunc((((sector_end_close.close - sector_start_close.close) / sector_start_close.close) -
((market_end_close.close - market_start_close.close) / market_start_close.close)) * 100, 2) as sector_vs_market,
coalesce(industry.etf_symbol, '') as industry,
market.component_symbol,
trunc((((stock_end_close.close - stock_start_close.close) / stock_start_close.close) -
((sector_end_close.close - sector_start_close.close) / sector_start_close.close)) * 100, 2) as stock_vs_sector,
coalesce(to_char(div.ex_date + interval '1 year', 'YY-MM-DD'), '') as anticipated_dividend_ex_date,
coalesce(to_char(ec.date, 'YY-MM-DD'), '') as earnings_date,
coalesce(trunc(option_spread.spread * 100, 2)::text, '') as option_spread,
coalesce(replace(rank.rank::text, 'Strong', 'Str'), '') as rank,
case
when w.act_symbol is not null then true
else false
end as is_weekly
from
(select
etf_symbol as market_symbol,
spdr.to_sector_etf(sector) as sector_symbol,
component_symbol as component_symbol,
date
from
spdr.etf_holding
where
etf_symbol = any(string_to_array($1, ',')) and
date = (select max(date) from spdr.etf_holding where date <= $4::text::date)) as market
left outer join
spdr.etf_holding industry
on
market.component_symbol = industry.component_symbol and
market.date = industry.date and
industry.sub_industry is not null
join
start_close as market_start_close
on
market.market_symbol = market_start_close.act_symbol
join
end_close as market_end_close
on
market.market_symbol = market_end_close.act_symbol
join
start_close as sector_start_close
on
market.sector_symbol = sector_start_close.act_symbol
join
end_close as sector_end_close
on
market.sector_symbol = sector_end_close.act_symbol
join
start_close as stock_start_close
on
market.component_symbol = stock_start_close.act_symbol
join
end_close as stock_end_close
on
market.component_symbol = stock_end_close.act_symbol
left outer join
yahoo.dividend div
on
market.component_symbol = div.act_symbol and
div.ex_date > $4::text::date - interval '1 year' and
div.ex_date <= $4::text::date - interval '1 year' + interval '2 months'
left outer join
zacks.earnings_calendar ec
on
market.component_symbol = ec.act_symbol and
ec.date >= $4::text::date and
ec.date <= $4::text::date + interval '1 month'
left outer join
(select
act_symbol,
avg((ask - bid) / ask) as spread
from
oic.option_chain
where
date = (select max(date) from oic.option_chain where date <= $4::text::date ) and
expiration > $4::text::date and
expiration <= $4::text::date + interval '3 months' and
bid > 0.0 and
ask > 0.0 and
((delta >= 0.2 and delta <= 0.8) or
(delta <= -0.2 and delta >= -0.8))
group by
act_symbol) option_spread
on
market.component_symbol = option_spread.act_symbol
left outer join
zacks.rank_score rank
on
market.component_symbol = rank.act_symbol and
rank.date > (select max(date) - interval '3 days' from zacks.rank_score)
left outer join
oic.weekly w
on
market.component_symbol = w.act_symbol and
w.last_seen = (select max(last_seen) from oic.weekly where last_seen <= $4::text::date)
where
case
when $2::text != '' then market.sector_symbol = $2::text
else true
end
order by
((stock_end_close.close - stock_start_close.close) / stock_start_close.close) desc;
"
market
sector
start-date
end-date)])
(map (λ (row) (price-analysis (vector-ref row 0) (vector-ref row 1) (vector-ref row 2) (vector-ref row 3)
(vector-ref row 4) (vector-ref row 5) (vector-ref row 6) (vector-ref row 7)
(vector-ref row 8) (vector-ref row 9) (vector-ref row 10)))
msis-query)))
(define (get-rank-analysis market date)
(map (λ (row) (rank-analysis (vector-ref row 0) (vector-ref row 1) (vector-ref row 2) (vector-ref row 3)
(vector-ref row 4) (vector-ref row 5) (vector-ref row 6) (vector-ref row 7)
(vector-ref row 8) (vector-ref row 9) (vector-ref row 10) (vector-ref row 11)
(vector-ref row 12) (vector-ref row 13)))
(query-rows dbc "
with etf_rank as (
select
etf_symbol,
sum(eh.weight * zacks.to_integer_rank(r.rank)) / sum(eh.weight) as \"rank\"
from
spdr.etf_holding eh
join
zacks.rank_score r
on
eh.component_symbol = r.act_symbol and
r.date = (select max(date) from zacks.rank_score where date <= $2::text::date)
where
eh.date = (select max(date) from spdr.etf_holding where date <= $2::text::date)
group by
etf_symbol
order by
\"rank\")
select
market.etf_symbol as market_symbol,
trunc(market_rank.rank, 2) as market_rank,
spdr.to_sector_etf(market.sector) as sector_symbol,
trunc(sector_rank.rank, 2) as sector_rank,
coalesce(industry.etf_symbol, '') as industry_symbol,
coalesce(trunc(industry_rank.rank, 2), 0.00) as industry_rank,
market.component_symbol,
zacks.to_integer_rank(component_rank.rank) as component_rank,
best_rank as component_best_rank,
trunc(component_avg_rank.rank, 2) as component_avg_rank,
worst_rank as component_worst_rank,
coalesce(to_char(ec.date, 'YY-MM-DD'), '') as earnings_date,
coalesce(trunc(option_spread.spread * 100, 2)::text, '') as option_spread,
case
when w.act_symbol is not null then true
else false
end as is_weekly
from
spdr.etf_holding market
join
etf_rank market_rank
on
market.etf_symbol = market_rank.etf_symbol
join
etf_rank sector_rank
on
spdr.to_sector_etf(market.sector) = sector_rank.etf_symbol
left outer join
spdr.etf_holding industry
on
market.component_symbol = industry.component_symbol and
market.date = industry.date and
industry.sub_industry is not null
left outer join
etf_rank industry_rank
on
industry.etf_symbol = industry_rank.etf_symbol
join
zacks.rank_score component_rank
on
market.component_symbol = component_rank.act_symbol and
component_rank.date = (select max(date) from zacks.rank_score where date <= $2::text::date)
join
(select
act_symbol,
min(zacks.to_integer_rank(rank)) as best_rank,
avg(zacks.to_integer_rank(rank)) as \"rank\",
max(zacks.to_integer_rank(rank)) as worst_rank
from
zacks.rank_score
where
date between ($2::text::date - interval '5 weeks') and
($2::text::date - interval '1 week')
group by
act_symbol) as component_avg_rank
on
market.component_symbol = component_avg_rank.act_symbol
left outer join
zacks.earnings_calendar ec
on
market.component_symbol = ec.act_symbol and
ec.date >= $2::text::date and
ec.date <= $2::text::date + interval '1 month'
left outer join
(select
act_symbol,
avg((ask - bid) / ask) as spread
from
oic.option_chain
where
date = (select max(date) from oic.option_chain where date <= $2::text::date ) and
expiration > $2::text::date and
expiration <= $2::text::date + interval '3 months' and
bid > 0.0 and
ask > 0.0 and
((delta >= 0.2 and delta <= 0.8) or
(delta <= -0.2 and delta >= -0.8))
group by
act_symbol) option_spread
on
market.component_symbol = option_spread.act_symbol
left outer join
oic.weekly w
on
market.component_symbol = w.act_symbol and
w.last_seen = (select max(last_seen) from oic.weekly where last_seen <= $2::text::date)
where
market.etf_symbol = any(string_to_array($1, ',')) and
market.date = (select max(date) from spdr.etf_holding where date <= $2::text::date) and
component_rank.rank in ('Strong Buy', 'Buy', 'Sell', 'Strong Sell')
order by
component_rank.rank, zacks.to_integer_rank(component_rank.rank) - component_avg_rank.rank, market.component_symbol;
"
market
date)))
(define (get-vol-analysis market date)
(map (λ (row) (vol-analysis (vector-ref row 0) (vector-ref row 1) (vector-ref row 2) (vector-ref row 3)
(vector-ref row 4) (vector-ref row 5) (vector-ref row 6) (vector-ref row 7)
(vector-ref row 8) (vector-ref row 9) (vector-ref row 10) (vector-ref row 11)
(vector-ref row 12) (vector-ref row 13) (vector-ref row 14)))
(query-rows dbc "
with hist_vol as (
select
vh.act_symbol,
min(vh.iv_current) as iv_year_low,
max(vh.iv_current) as iv_year_high
from
oic.volatility_history vh
where
vh.date <= $2::text::date and
vh.date > $2::text::date - '1 year'::interval
group by
vh.act_symbol
)
select
market.etf_symbol,
coalesce(trunc(market_vol.iv_current * 100, 2), 0.00) as market_iv,
case when market_vol.iv_year_low is null or market_vol.iv_year_high is null
then coalesce(trunc((market_vol.iv_current - market_hist_vol.iv_year_low) / (market_hist_vol.iv_year_high - market_hist_vol.iv_year_low) * 100, 2), 0.00)
else coalesce(trunc((market_vol.iv_current - market_vol.iv_year_low) / (market_vol.iv_year_high - market_vol.iv_year_low) * 100, 2), 0.00)
end as market_iv_rank,
spdr.to_sector_etf(market.sector),
coalesce(trunc(sector_vol.iv_current * 100, 2), 0.00) as sector_iv,
case when sector_vol.iv_year_low is null or sector_vol.iv_year_high is null
then coalesce(trunc((sector_vol.iv_current - sector_hist_vol.iv_year_low) / (sector_hist_vol.iv_year_high - sector_hist_vol.iv_year_low) * 100, 2), 0.00)
else coalesce(trunc((sector_vol.iv_current - sector_vol.iv_year_low) / (sector_vol.iv_year_high - sector_vol.iv_year_low) * 100, 2), 0.00)
end as sector_iv_rank,
coalesce(industry.etf_symbol, ''),
coalesce(trunc(industry_vol.iv_current * 100, 2), 0.00) as industry_iv,
case when industry_vol.iv_year_low is null or industry_vol.iv_year_high is null
then coalesce(trunc((industry_vol.iv_current - industry_hist_vol.iv_year_low) / (industry_hist_vol.iv_year_high - industry_hist_vol.iv_year_low) * 100, 2), 0.00)
else coalesce(trunc((industry_vol.iv_current - industry_vol.iv_year_low) / (industry_vol.iv_year_high - industry_vol.iv_year_low) * 100, 2), 0.00)
end as industry_iv_rank,
market.component_symbol,
coalesce(trunc(component_vol.iv_current * 100, 2), 0.00) as component_iv,
case when component_vol.iv_year_low is null or component_vol.iv_year_high is null
then coalesce(trunc((component_vol.iv_current - component_hist_vol.iv_year_low) / (component_hist_vol.iv_year_high - component_hist_vol.iv_year_low) * 100, 2), 0.00)
else coalesce(trunc((component_vol.iv_current - component_vol.iv_year_low) / (component_vol.iv_year_high - component_vol.iv_year_low) * 100, 2), 0.00)
end as component_iv_rank,
coalesce(to_char(ec.date, 'YY-MM-DD'), '') as earnings_date,
coalesce(trunc(option_spread.spread * 100, 2)::text, '') as option_spread,
case
when w.act_symbol is not null then true
else false
end as is_weekly
from
spdr.etf_holding market
left outer join
oic.volatility_history market_vol
on
market.etf_symbol = market_vol.act_symbol and
market_vol.date = (select max(date) from oic.volatility_history where date <= $2::text::date)
left outer join
hist_vol market_hist_vol
on
market.etf_symbol = market_hist_vol.act_symbol
left outer join
oic.volatility_history sector_vol
on
spdr.to_sector_etf(market.sector) = sector_vol.act_symbol and
sector_vol.date = (select max(date) from oic.volatility_history where date <= $2::text::date)
left outer join
hist_vol sector_hist_vol
on
spdr.to_sector_etf(market.sector) = sector_hist_vol.act_symbol
left outer join
spdr.etf_holding industry
on
market.component_symbol = industry.component_symbol and
market.date = industry.date and
industry.sub_industry is not null
left outer join
oic.volatility_history industry_vol
on
industry.etf_symbol = industry_vol.act_symbol and
industry_vol.date = (select max(date) from oic.volatility_history where date <= $2::text::date)
left outer join
hist_vol industry_hist_vol
on
industry.etf_symbol = industry_hist_vol.act_symbol
join
oic.volatility_history component_vol
on
market.component_symbol = component_vol.act_symbol and
component_vol.date = (select max(date) from oic.volatility_history where date <= $2::text::date)
join
hist_vol component_hist_vol
on
market.component_symbol = component_hist_vol.act_symbol
left outer join
zacks.earnings_calendar ec
on
market.component_symbol = ec.act_symbol and
ec.date >= $2::text::date and
ec.date <= $2::text::date + interval '1 month'
left outer join
(select
act_symbol,
avg((ask - bid) / ask) as spread
from
oic.option_chain
where
date = (select max(date) from oic.option_chain where date <= $2::text::date ) and
expiration > $2::text::date and
expiration <= $2::text::date + interval '3 months' and
bid > 0.0 and
ask > 0.0 and
((delta >= 0.2 and delta <= 0.8) or
(delta <= -0.2 and delta >= -0.8))
group by
act_symbol) option_spread
on
market.component_symbol = option_spread.act_symbol
left outer join
oic.weekly w
on
market.component_symbol = w.act_symbol and
w.last_seen = (select max(last_seen) from oic.weekly where last_seen <= $2::text::date)
where
market.etf_symbol = any(string_to_array($1, ',')) and
market.date = (select max(date) from spdr.etf_holding where date <= $2::text::date)
order by
component_iv_rank desc;
"
market
date)))
(define (get-condor-analysis market date)
(map (λ (row) (condor-analysis (vector-ref row 0) "" "" (vector-ref row 1) "" "" (vector-ref row 2) "" ""
(vector-ref row 3) "" "" (vector-ref row 4) (vector-ref row 5) (vector-ref row 6)))
(query-rows dbc "
select
market.etf_symbol as market,
coalesce(spdr.to_sector_etf(market.sector), '') as sector,
coalesce(industry.etf_symbol, '') as industry,
market.component_symbol as stock,
coalesce(to_char(ec.date, 'YY-MM-DD'), '') as earnings_date,
coalesce(trunc(option_spread.spread * 100, 2)::text, '') as option_spread,
case
when w.act_symbol is not null then true
else false
end as is_weekly
from
spdr.etf_holding market
left outer join
spdr.etf_holding industry
on
market.component_symbol = industry.component_symbol and
market.date = industry.date and
industry.sub_industry is not null
left outer join
zacks.earnings_calendar ec
on
market.component_symbol = ec.act_symbol and
ec.date >= $2::text::date and
ec.date <= $2::text::date + interval '1 month'
left outer join
(select
act_symbol,
avg((ask - bid) / ask) as spread
from
oic.option_chain
where
date = (select max(date) from oic.option_chain where date <= $2::text::date ) and
expiration > $2::text::date and
expiration <= $2::text::date + interval '3 months' and
bid > 0.0 and
ask > 0.0 and
((delta >= 0.2 and delta <= 0.8) or
(delta <= -0.2 and delta >= -0.8))
group by
act_symbol) option_spread
on
market.component_symbol = option_spread.act_symbol
left outer join
oic.weekly w
on
market.component_symbol = w.act_symbol and
w.last_seen = (select max(last_seen) from oic.weekly where last_seen <= $2::text::date)
where
market.etf_symbol = any(string_to_array($1, ',')) and
market.date = (select max(date) from spdr.etf_holding where date <= $2::text::date);
"
market
date)))
(define (get-position-analysis date)
(map (λ (row) (position-analysis (vector-ref row 0) (vector-ref row 1) (vector-ref row 2) (vector-ref row 3)
(vector-ref row 4) (vector-ref row 5) (vector-ref row 6) (vector-ref row 7)
(vector-ref row 8) (vector-ref row 9) (vector-ref row 10) (vector-ref row 11)))
(query-rows dbc "
with earnings_end_date as (
select
act_symbol,
case when \"when\" = 'Before market open'
then case when date_part('dow', date) = 1
then (date - interval '3 days')::date
else (date - interval '1 days')::date
end
else date
end as end_date
from
zacks.earnings_calendar
where
date >= $1::text::date
), expiry_end_date as (
select
o.account,
o.order_id,
min(c.expiry) as expiry
from
ibkr.order o
join
ibkr.order_leg ol
on
o.account = ol.account and
o.order_id = ol.order_id
join
ibkr.contract c
on
ol.contract_id = c.contract_id
where
c.expiry >= $1::text::date
group by
o.account,
o.order_id
)
select
coalesce(spdr.to_sector_etf(eh.sector), '') as etf_symbol,
c.symbol,
to_char(c.expiry, 'YY-MM-DD') as expiry,
c.strike,
c.right::text,
e.account,
e.signed_shares,
coalesce(trunc(n.underlying_stop_price, 2), 0.00),
coalesce(trunc(ch.close, 2), 0.00),
coalesce(trunc(n.underlying_target_price, 2), 0.00),
coalesce(to_char(case when ed.end_date is not null and ed.end_date < n.end_date
then case when eed.expiry is not null and eed.expiry < ed.end_date
then eed.expiry else ed.end_date end
else case when eed.expiry is not null and eed.expiry < n.end_date
then eed.expiry else n.end_date end
end, 'YY-MM-DD'), '') as end_date,
coalesce(n.order_strategy::text, '') as order_strategy
from
(select
max(order_id) as order_id,
contract_id,
account,
sum(
case execution.side
when 'BOT'::text then execution.shares
when 'SLD'::text then execution.shares * '-1'::integer::numeric
else NULL::numeric
end) as signed_shares
from
ibkr.execution
group by
contract_id, account) e
join
ibkr.contract c
on
e.contract_id = c.contract_id
left outer join
ibkr.order_note n
on
e.account = n.account and
e.order_id = n.order_id
left outer join
(select distinct
component_symbol,
sector
from
spdr.etf_holding
where
date = (select max(date) from spdr.etf_holding where date <= $1::text::date) and
sector is not null) eh
on
c.symbol = eh.component_symbol
left outer join
earnings_end_date ed
on
c.symbol = ed.act_symbol
left outer join
polygon.ohlc ch
on
c.symbol = ch.act_symbol and
ch.date = (select max(date) from polygon.ohlc where date <= $1::text::date)
left outer join
expiry_end_date eed
on
e.account = eed.account and
e.order_id = eed.order_id
where
c.expiry >= $1::text::date and
signed_shares != 0
order by
etf_symbol,
symbol,
expiry,
strike,
\"right\";
"
date)))
(define (get-position-history date)
(query-value dbc "
select
'Bulls: ' ||
sum(
case n.order_strategy
when 'LONG CALL' then 1
when 'BULL CALL VERTICAL SPREAD' then 1
when 'BULL PUT VERTICAL SPREAD' then 1
when 'CALL RATIO SPREAD' then 1
when 'CALL HORIZONTAL SPREAD' then 1
when 'CALL DIAGONAL SPREAD' then 1
else 0
end
) || ' Roos: ' ||
sum(
case n.order_strategy
when 'LONG STRADDLE' then 1
when 'LONG STRANGLE' then 1
when 'CALL BUTTERFLY' then 1
when 'PUT BUTTERFLY' then 1
when 'CALL CONDOR' then 1
when 'PUT CONDOR' then 1
else 0
end
) || ' Bears: ' ||
sum(
case n.order_strategy
when 'LONG PUT' then 1
when 'BEAR CALL VERTICAL SPREAD' then 1
when 'BEAR PUT VERTICAL SPREAD' then 1
when 'PUT RATIO SPREAD' then 1
when 'PUT HORIZONTAL SPREAD' then 1
when 'PUT DIAGONAL SPREAD' then 1
else 0
end
) as summary
from
(select distinct
order_id
from
ibkr.\"position\" p
where
p.entry_timestamp >= $1::text::date - '1 month'::interval) oids
join
ibkr.order_note n
on
n.order_id = oids.order_id;
"
date))
(define (get-security-name act-symbol)
(query-value dbc "
select
security_name
from
nasdaq.symbol
where
act_symbol = $1;
"
act-symbol))
(define (get-options act-symbol date)
(map (λ (row) (option (vector-ref row 0)
(vector-ref row 1)
(vector-ref row 2)
(vector-ref row 3)
(vector-ref row 4)
(vector-ref row 5)
(vector-ref row 6)
(vector-ref row 7)
(vector-ref row 8)
(vector-ref row 9)
(vector-ref row 10)
(vector-ref row 11)
(vector-ref row 12)
(vector-ref row 13)
(vector-ref row 14)))
(query-rows dbc "
select
act_symbol,
to_char(expiration, 'YY-MM-DD'),
expiration - $2::text::date as dte,
strike,
call_put::text,
to_char(date, 'YY-MM-DD'),
bid,
(bid + ask) / 2 as mid,
ask,
vol,
delta,
gamma,
theta,
vega,
rho
from
oic.option_chain
where
act_symbol = $1 and
expiration > $2::text::date and
date =
(select
max(date)
from
oic.option_chain
where
act_symbol = $1 and
date <= $2::text::date)
order by
expiration, strike, call_put;
"
act-symbol
date)))
(define (get-1-month-rate date)
(query-value dbc "
select
\"1_month\" / 100
from
ust.yield_curve
where
date = (select max(date) from ust.yield_curve where date < $1::text::date)
"
date))
(define (get-dividend-estimates symbol start-date end-date)
(query-rows dbc "
select
(previous.ex_date + interval '1 year')::date - $2::text::date,
latest.amount
from
yahoo.dividend latest
join
yahoo.dividend previous
on
previous.act_symbol = latest.act_symbol
where
latest.act_symbol = $1 and
latest.ex_date = (select max(ex_date) from yahoo.dividend where act_symbol = $1) and
previous.ex_date between $2::text::date - interval '1 year' and $3::text::date - interval '1 year';
"
symbol
(date->iso8601 start-date)
(date->iso8601 end-date)))
(define (get-next-earnings-date symbol start-date end-date)
(iso8601->date (query-value dbc "
select
coalesce(ec.date::text, ed.end_date)
from
(select
$1 as symbol,
$3::text as end_date) ed
left outer join
zacks.earnings_calendar ec
on
ec.act_symbol = $1 and
ec.date >= $2::text::date and
ec.date <= $3::text::date;
"
symbol
(date->iso8601 start-date)
(date->iso8601 end-date))))
(define (insert-commission-report commission-report)
(log-message file-log 'info (format "insert-commission-report ~v" commission-report))
(with-handlers ([exn:fail? (λ (error)
(displayln "Could not insert commission report into DB")
(displayln commission-report)
(displayln error))])
(query-exec dbc "
insert into ibkr.commission_report (
execution_id,
commission,
currency,
realized_pnl,
yield,
yield_redemption_date
) values (
$1,
$2,
$3,
$4,
$5,
$6
) on conflict (execution_id) do nothing;
"
(commission-report-rsp-execution-id commission-report)
(commission-report-rsp-commission commission-report)
(commission-report-rsp-currency commission-report)
(if (commission-report-rsp-realized-pnl commission-report)
(commission-report-rsp-realized-pnl commission-report)
sql-null)
(if (commission-report-rsp-yield commission-report)
(commission-report-rsp-yield commission-report)
sql-null)
(if (commission-report-rsp-yield-redemption-date commission-report)
(commission-report-rsp-yield-redemption-date commission-report)
sql-null))))
(define (insert-execution execution)
(log-message file-log 'info (format "insert-execution ~v" execution))
(query-exec dbc "
insert into ibkr.execution (
order_id,
contract_id,
execution_id,
\"timestamp\",
account,
executing_exchange,
side,
shares,
price,
perm_id,
client_id,
liquidation,
cumulative_quantity,
average_price,
order_reference,
model_code
) values (
$1,
$2,
$3,
$4::text::timestamptz,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16
) on conflict (execution_id) do nothing;
"
(execution-rsp-order-id execution)
(execution-rsp-contract-id execution)
(execution-rsp-execution-id execution)
(~t (execution-rsp-timestamp execution) "yyyy-MM-dd'T'HH:mm:ss")
(execution-rsp-account execution)
(execution-rsp-executing-exchange execution)
(execution-rsp-side execution)
(execution-rsp-shares execution)
(execution-rsp-price execution)
(execution-rsp-perm-id execution)
(execution-rsp-client-id execution)
(execution-rsp-liquidation execution)
(execution-rsp-cumulative-quantity execution)
(execution-rsp-average-price execution)
(execution-rsp-order-reference execution)
(execution-rsp-model-code execution)))
(define (insert-condor-analysis date
condor-analysis
market-rating
market-risk-reward
sector-rating
sector-risk-reward
industry-rating
industry-risk-reward
stock-rating
stock-risk-reward)
(query-exec dbc "
insert into renegade.condor_analysis (
date,
market_act_symbol,
market_rating,
market_risk_reward,
sector_act_symbol,
sector_rating,
sector_risk_reward,
industry_act_symbol,
industry_rating,
industry_risk_reward,
stock_act_symbol,
stock_rating,
stock_risk_reward,
earnings_date,
option_spread
) values (
$1::text::date,
$2,
case
when $3::numeric = 0 then null
else round($3::numeric, 2)
end,
case
when $4::numeric = 0 then null
else round($4::numeric, 2)
end,
$5,
case
when $6::numeric = 0 then null
else round($6::numeric, 2)
end,
case
when $7::numeric = 0 then null
else round($7::numeric, 2)
end,
$8,
case
when $9::numeric = 0 then null
else round($9::numeric, 2)
end,
case
when $10::numeric = 0 then null
else round($10::numeric, 2)
end,
$11,
case
when $12::numeric = 0 then null
else round($12::numeric, 2)
end,
case
when $13::numeric = 0 then null
else round($13::numeric, 2)
end,
case
when $14::text = '' then null
else to_date($14::text, 'YY-MM-DD')