nsepython 2.94__py3-none-any.whl → 2.97__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nsepython/__init__.py +3 -3
- nsepython/rahu.py +965 -953
- {nsepython-2.94.dist-info → nsepython-2.97.dist-info}/METADATA +129 -117
- nsepython-2.97.dist-info/RECORD +7 -0
- {nsepython-2.94.dist-info → nsepython-2.97.dist-info}/WHEEL +1 -1
- {nsepython-2.94.dist-info → nsepython-2.97.dist-info/licenses}/LICENSE +674 -674
- nsepython-2.94.dist-info/RECORD +0 -7
- {nsepython-2.94.dist-info → nsepython-2.97.dist-info}/top_level.txt +0 -0
nsepython/rahu.py
CHANGED
|
@@ -1,954 +1,966 @@
|
|
|
1
|
-
import os,sys
|
|
2
|
-
# os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
|
3
|
-
# sys.path.insert(1, os.path.join(sys.path[0], '..'))
|
|
4
|
-
|
|
5
|
-
import requests
|
|
6
|
-
import pandas as pd
|
|
7
|
-
import json
|
|
8
|
-
import random
|
|
9
|
-
import datetime,time
|
|
10
|
-
import logging
|
|
11
|
-
import re
|
|
12
|
-
import urllib.parse
|
|
13
|
-
|
|
14
|
-
mode ='local'
|
|
15
|
-
|
|
16
|
-
if
|
|
17
|
-
def nsefetch(payload):
|
|
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
|
-
return
|
|
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
|
-
oi_row['CALLS_OI']
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
oi_row['
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
oi_row['PUTS_OI']
|
|
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
|
-
def
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
for
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
return
|
|
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
|
-
for
|
|
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
|
-
meta
|
|
301
|
-
if(optionType=="Fut"):
|
|
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
|
-
def
|
|
462
|
-
payload = nsefetch('https://
|
|
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
|
-
def
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
if(mode=="
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
if(
|
|
525
|
-
return payload
|
|
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
|
-
logging.info("
|
|
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
|
-
logging.info(
|
|
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
|
-
logging.info("
|
|
704
|
-
logging.info("
|
|
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
|
-
payload
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
payload=pd.
|
|
788
|
-
return payload
|
|
789
|
-
|
|
790
|
-
def
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
payload
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
end_date = datetime.datetime.now().strftime("%d-%
|
|
815
|
-
end_date = str(end_date)
|
|
816
|
-
|
|
817
|
-
start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%
|
|
818
|
-
start_date = str(start_date)
|
|
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
|
-
return
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
def
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
return
|
|
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
|
-
if
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
payload
|
|
1
|
+
import os,sys
|
|
2
|
+
# os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
|
3
|
+
# sys.path.insert(1, os.path.join(sys.path[0], '..'))
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import json
|
|
8
|
+
import random
|
|
9
|
+
import datetime,time
|
|
10
|
+
import logging
|
|
11
|
+
import re
|
|
12
|
+
import urllib.parse
|
|
13
|
+
|
|
14
|
+
mode ='local'
|
|
15
|
+
|
|
16
|
+
if mode == "vpn":
|
|
17
|
+
def nsefetch(payload: str):
|
|
18
|
+
def encode(url: str) -> str:
|
|
19
|
+
if "%26" in url or "%20" in url:
|
|
20
|
+
return url
|
|
21
|
+
return urllib.parse.quote(url, safe=":/?&=")
|
|
22
|
+
|
|
23
|
+
def refresh_cookies():
|
|
24
|
+
os.popen(f'curl -c cookies.txt "https://www.nseindia.com" {curl_headers}').read()
|
|
25
|
+
os.popen(f'curl -b cookies.txt -c cookies.txt "https://www.nseindia.com/option-chain" {curl_headers}').read()
|
|
26
|
+
|
|
27
|
+
if not os.path.exists("cookies.txt"):
|
|
28
|
+
refresh_cookies()
|
|
29
|
+
|
|
30
|
+
encoded_url = encode(payload)
|
|
31
|
+
cmd = f'curl -b cookies.txt "{encoded_url}" {curl_headers}'
|
|
32
|
+
raw = os.popen(cmd).read()
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
return json.loads(raw)
|
|
36
|
+
except ValueError:
|
|
37
|
+
refresh_cookies()
|
|
38
|
+
raw = os.popen(cmd).read()
|
|
39
|
+
try:
|
|
40
|
+
return json.loads(raw)
|
|
41
|
+
except ValueError:
|
|
42
|
+
return {}
|
|
43
|
+
|
|
44
|
+
if(mode=='local'):
|
|
45
|
+
def nsefetch(payload):
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
s = requests.Session()
|
|
49
|
+
s.get("https://www.nseindia.com", headers=headers, timeout=10)
|
|
50
|
+
s.get("https://www.nseindia.com/option-chain", headers=headers, timeout=10)
|
|
51
|
+
output = s.get(payload, headers=headers, timeout=10).json()
|
|
52
|
+
except ValueError:
|
|
53
|
+
output = {}
|
|
54
|
+
return output
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# headers = {
|
|
58
|
+
# 'Connection': 'keep-alive',
|
|
59
|
+
# 'Cache-Control': 'max-age=0',
|
|
60
|
+
# 'DNT': '1',
|
|
61
|
+
# 'Upgrade-Insecure-Requests': '1',
|
|
62
|
+
# 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
|
|
63
|
+
# 'Sec-Fetch-User': '?1',
|
|
64
|
+
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
|
|
65
|
+
# 'Sec-Fetch-Site': 'none',
|
|
66
|
+
# 'Sec-Fetch-Mode': 'navigate',
|
|
67
|
+
# 'Accept-Encoding': 'gzip, deflate, br',
|
|
68
|
+
# 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
|
|
69
|
+
# }
|
|
70
|
+
|
|
71
|
+
#Rahul_Mittal's entry
|
|
72
|
+
headers = {
|
|
73
|
+
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
|
|
74
|
+
"accept-language": "en-US,en;q=0.9,en-IN;q=0.8,en-GB;q=0.7",
|
|
75
|
+
"cache-control": "max-age=0",
|
|
76
|
+
"priority": "u=0, i",
|
|
77
|
+
"sec-ch-ua": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
|
|
78
|
+
"sec-ch-ua-mobile": "?0",
|
|
79
|
+
"sec-ch-ua-platform": '"Windows"',
|
|
80
|
+
"sec-fetch-dest": "document",
|
|
81
|
+
"sec-fetch-mode": "navigate",
|
|
82
|
+
"sec-fetch-site": "none",
|
|
83
|
+
"sec-fetch-user": "?1",
|
|
84
|
+
"upgrade-insecure-requests": "1",
|
|
85
|
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
#Curl headers
|
|
91
|
+
curl_headers = ''' -H "authority: beta.nseindia.com" -H "cache-control: max-age=0" -H "dnt: 1" -H "upgrade-insecure-requests: 1" -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36" -H "sec-fetch-user: ?1" -H "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" -H "sec-fetch-site: none" -H "sec-fetch-mode: navigate" -H "accept-encoding: gzip, deflate, br" -H "accept-language: en-US,en;q=0.9,hi;q=0.8" --compressed'''
|
|
92
|
+
|
|
93
|
+
run_time=datetime.datetime.now()
|
|
94
|
+
|
|
95
|
+
#Constants
|
|
96
|
+
indices = ['NIFTY','FINNIFTY','BANKNIFTY']
|
|
97
|
+
|
|
98
|
+
def running_status():
|
|
99
|
+
start_now=datetime.datetime.now().replace(hour=9, minute=15, second=0, microsecond=0)
|
|
100
|
+
end_now=datetime.datetime.now().replace(hour=15, minute=30, second=0, microsecond=0)
|
|
101
|
+
return start_now<datetime.datetime.now()<end_now
|
|
102
|
+
|
|
103
|
+
#Getting FNO Symboles
|
|
104
|
+
def fnolist():
|
|
105
|
+
# df = pd.read_csv("https://www1.nseindia.com/content/fo/fo_mktlots.csv")
|
|
106
|
+
# return [x.strip(' ') for x in df.drop(df.index[3]).iloc[:,1].to_list()]
|
|
107
|
+
|
|
108
|
+
positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
109
|
+
|
|
110
|
+
nselist=['NIFTY','NIFTYIT','BANKNIFTY']
|
|
111
|
+
|
|
112
|
+
i=0
|
|
113
|
+
for x in range(i, len(positions['data'])):
|
|
114
|
+
nselist=nselist+[positions['data'][x]['symbol']]
|
|
115
|
+
|
|
116
|
+
return nselist
|
|
117
|
+
|
|
118
|
+
def nsesymbolpurify(symbol):
|
|
119
|
+
symbol = symbol.replace('&','%26') #URL Parse for Stocks Like M&M Finance
|
|
120
|
+
return symbol
|
|
121
|
+
|
|
122
|
+
def nse_optionchain_scrapper(symbol):
|
|
123
|
+
symbol = nsesymbolpurify(symbol)
|
|
124
|
+
if any(x in symbol for x in indices):
|
|
125
|
+
payload = nsefetch('https://www.nseindia.com/api/option-chain-indices?symbol='+symbol)
|
|
126
|
+
else:
|
|
127
|
+
payload = nsefetch('https://www.nseindia.com/api/option-chain-equities?symbol='+symbol)
|
|
128
|
+
return payload
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def oi_chain_builder(symbol,expiry="latest",oi_mode="full"):
|
|
132
|
+
|
|
133
|
+
payload = nse_optionchain_scrapper(symbol)
|
|
134
|
+
|
|
135
|
+
if(oi_mode=='compact'):
|
|
136
|
+
col_names = ['CALLS_OI','CALLS_Chng in OI','CALLS_Volume','CALLS_IV','CALLS_LTP','CALLS_Net Chng','Strike Price','PUTS_OI','PUTS_Chng in OI','PUTS_Volume','PUTS_IV','PUTS_LTP','PUTS_Net Chng']
|
|
137
|
+
if(oi_mode=='full'):
|
|
138
|
+
col_names = ['CALLS_Chart','CALLS_OI','CALLS_Chng in OI','CALLS_Volume','CALLS_IV','CALLS_LTP','CALLS_Net Chng','CALLS_Bid Qty','CALLS_Bid Price','CALLS_Ask Price','CALLS_Ask Qty','Strike Price','PUTS_Bid Qty','PUTS_Bid Price','PUTS_Ask Price','PUTS_Ask Qty','PUTS_Net Chng','PUTS_LTP','PUTS_IV','PUTS_Volume','PUTS_Chng in OI','PUTS_OI','PUTS_Chart']
|
|
139
|
+
oi_data = pd.DataFrame(columns = col_names)
|
|
140
|
+
|
|
141
|
+
#oi_row = {'CALLS_OI':0, 'CALLS_Chng in OI':0, 'CALLS_Volume':0, 'CALLS_IV':0, 'CALLS_LTP':0, 'CALLS_Net Chng':0, 'Strike Price':0, 'PUTS_OI':0, 'PUTS_Chng in OI':0, 'PUTS_Volume':0, 'PUTS_IV':0, 'PUTS_LTP':0, 'PUTS_Net Chng':0}
|
|
142
|
+
oi_row = {'CALLS_OI':0, 'CALLS_Chng in OI':0, 'CALLS_Volume':0, 'CALLS_IV':0, 'CALLS_LTP':0, 'CALLS_Net Chng':0, 'CALLS_Bid Qty':0,'CALLS_Bid Price':0,'CALLS_Ask Price':0,'CALLS_Ask Qty':0,'Strike Price':0, 'PUTS_OI':0, 'PUTS_Chng in OI':0, 'PUTS_Volume':0, 'PUTS_IV':0, 'PUTS_LTP':0, 'PUTS_Net Chng':0,'PUTS_Bid Qty':0,'PUTS_Bid Price':0,'PUTS_Ask Price':0,'PUTS_Ask Qty':0}
|
|
143
|
+
if(expiry=="latest"):
|
|
144
|
+
expiry = payload['records']['expiryDates'][0]
|
|
145
|
+
m=0
|
|
146
|
+
for m in range(len(payload['records']['data'])):
|
|
147
|
+
if(payload['records']['data'][m]['expiryDate']==expiry):
|
|
148
|
+
if(1>0):
|
|
149
|
+
try:
|
|
150
|
+
oi_row['CALLS_OI']=payload['records']['data'][m]['CE']['openInterest']
|
|
151
|
+
oi_row['CALLS_Chng in OI']=payload['records']['data'][m]['CE']['changeinOpenInterest']
|
|
152
|
+
oi_row['CALLS_Volume']=payload['records']['data'][m]['CE']['totalTradedVolume']
|
|
153
|
+
oi_row['CALLS_IV']=payload['records']['data'][m]['CE']['impliedVolatility']
|
|
154
|
+
oi_row['CALLS_LTP']=payload['records']['data'][m]['CE']['lastPrice']
|
|
155
|
+
oi_row['CALLS_Net Chng']=payload['records']['data'][m]['CE']['change']
|
|
156
|
+
if(oi_mode=='full'):
|
|
157
|
+
oi_row['CALLS_Bid Qty']=payload['records']['data'][m]['CE']['bidQty']
|
|
158
|
+
oi_row['CALLS_Bid Price']=payload['records']['data'][m]['CE']['bidprice']
|
|
159
|
+
oi_row['CALLS_Ask Price']=payload['records']['data'][m]['CE']['askPrice']
|
|
160
|
+
oi_row['CALLS_Ask Qty']=payload['records']['data'][m]['CE']['askQty']
|
|
161
|
+
except KeyError:
|
|
162
|
+
oi_row['CALLS_OI'], oi_row['CALLS_Chng in OI'], oi_row['CALLS_Volume'], oi_row['CALLS_IV'], oi_row['CALLS_LTP'],oi_row['CALLS_Net Chng']=0,0,0,0,0,0
|
|
163
|
+
if(oi_mode=='full'):
|
|
164
|
+
oi_row['CALLS_Bid Qty'],oi_row['CALLS_Bid Price'],oi_row['CALLS_Ask Price'],oi_row['CALLS_Ask Qty']=0,0,0,0
|
|
165
|
+
pass
|
|
166
|
+
|
|
167
|
+
oi_row['Strike Price']=payload['records']['data'][m]['strikePrice']
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
oi_row['PUTS_OI']=payload['records']['data'][m]['PE']['openInterest']
|
|
171
|
+
oi_row['PUTS_Chng in OI']=payload['records']['data'][m]['PE']['changeinOpenInterest']
|
|
172
|
+
oi_row['PUTS_Volume']=payload['records']['data'][m]['PE']['totalTradedVolume']
|
|
173
|
+
oi_row['PUTS_IV']=payload['records']['data'][m]['PE']['impliedVolatility']
|
|
174
|
+
oi_row['PUTS_LTP']=payload['records']['data'][m]['PE']['lastPrice']
|
|
175
|
+
oi_row['PUTS_Net Chng']=payload['records']['data'][m]['PE']['change']
|
|
176
|
+
if(oi_mode=='full'):
|
|
177
|
+
oi_row['PUTS_Bid Qty']=payload['records']['data'][m]['PE']['bidQty']
|
|
178
|
+
oi_row['PUTS_Bid Price']=payload['records']['data'][m]['PE']['bidprice']
|
|
179
|
+
oi_row['PUTS_Ask Price']=payload['records']['data'][m]['PE']['askPrice']
|
|
180
|
+
oi_row['PUTS_Ask Qty']=payload['records']['data'][m]['PE']['askQty']
|
|
181
|
+
except KeyError:
|
|
182
|
+
oi_row['PUTS_OI'], oi_row['PUTS_Chng in OI'], oi_row['PUTS_Volume'], oi_row['PUTS_IV'], oi_row['PUTS_LTP'],oi_row['PUTS_Net Chng']=0,0,0,0,0,0
|
|
183
|
+
if(oi_mode=='full'):
|
|
184
|
+
oi_row['PUTS_Bid Qty'],oi_row['PUTS_Bid Price'],oi_row['PUTS_Ask Price'],oi_row['PUTS_Ask Qty']=0,0,0,0
|
|
185
|
+
else:
|
|
186
|
+
logging.info(m)
|
|
187
|
+
|
|
188
|
+
if(oi_mode=='full'):
|
|
189
|
+
oi_row['CALLS_Chart'],oi_row['PUTS_Chart']=0,0
|
|
190
|
+
#oi_data = oi_data.append(oi_row, ignore_index=True)
|
|
191
|
+
#oi_data = pd.concat([oi_data, oi_row], ignore_index=True)
|
|
192
|
+
oi_data = pd.concat([oi_data, pd.DataFrame([oi_row])], ignore_index=True)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
oi_data['time_stamp']=payload['records']['timestamp']
|
|
197
|
+
return oi_data,float(payload['records']['underlyingValue']),payload['records']['timestamp']
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def nse_quote(symbol,section=""):
|
|
201
|
+
#https://forum.unofficed.com/t/nsetools-get-quote-is-not-fetching-delivery-data-and-delivery-can-you-include-this-as-part-of-feature-request/1115/4
|
|
202
|
+
symbol = nsesymbolpurify(symbol)
|
|
203
|
+
|
|
204
|
+
if(section==""):
|
|
205
|
+
if any(x in symbol for x in fnolist()):
|
|
206
|
+
payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
|
|
207
|
+
else:
|
|
208
|
+
payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
|
|
209
|
+
return payload
|
|
210
|
+
|
|
211
|
+
if(section!=""):
|
|
212
|
+
payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol+'§ion='+section)
|
|
213
|
+
return payload
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def nse_expirydetails(payload,i=0): #Can make problem. Use nse_expirydetails_by_symbol()
|
|
217
|
+
|
|
218
|
+
expiry_dates = payload['records']['expiryDates']
|
|
219
|
+
expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
|
|
220
|
+
expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
|
|
221
|
+
currentExpiry=expiry_dates[i]
|
|
222
|
+
currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date() # converting json datetime to alice datetime
|
|
223
|
+
date_today = run_time.strftime('%Y-%m-%d') # required to remove hh:mm:ss
|
|
224
|
+
date_today = datetime.datetime.strptime(date_today,'%Y-%m-%d').date()
|
|
225
|
+
dte = (currentExpiry - date_today).days
|
|
226
|
+
return currentExpiry,dte
|
|
227
|
+
|
|
228
|
+
def pcr(payload,inp='0'):
|
|
229
|
+
ce_oi = 0
|
|
230
|
+
pe_oi = 0
|
|
231
|
+
for i in payload['records']['data']:
|
|
232
|
+
if i['expiryDate'] == payload['records']['expiryDates'][inp]:
|
|
233
|
+
try:
|
|
234
|
+
ce_oi += i['CE']['openInterest']
|
|
235
|
+
pe_oi += i['PE']['openInterest']
|
|
236
|
+
except KeyError:
|
|
237
|
+
pass
|
|
238
|
+
return pe_oi / ce_oi
|
|
239
|
+
|
|
240
|
+
#forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
|
|
241
|
+
#Refer https://forum.unofficed.com/t/changed-the-nse-quote-ltp-function/1276
|
|
242
|
+
def nse_quote_ltp(symbol,expiryDate="latest",optionType="-",strikePrice=0):
|
|
243
|
+
payload = nse_quote(symbol)
|
|
244
|
+
|
|
245
|
+
meta = "Options"
|
|
246
|
+
if(optionType=="Fut"): meta = "Futures"
|
|
247
|
+
if(optionType=="PE"):optionType="Put"
|
|
248
|
+
if(optionType=="CE"):optionType="Call"
|
|
249
|
+
|
|
250
|
+
if(expiryDate=="latest") or (expiryDate=="next"):
|
|
251
|
+
|
|
252
|
+
if(meta=="Futures"):
|
|
253
|
+
selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
|
|
254
|
+
if(meta=="Options"):
|
|
255
|
+
selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)
|
|
256
|
+
|
|
257
|
+
expiry_dates=payload["expiryDatesByInstrument"][selected_key]
|
|
258
|
+
expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
|
|
259
|
+
expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
|
|
260
|
+
if(expiryDate=="latest"): expiryDate=expiry_dates[0]
|
|
261
|
+
if(expiryDate=="next"): expiryDate=expiry_dates[1]
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
if(optionType!="-"):
|
|
265
|
+
for i in payload['stocks']:
|
|
266
|
+
if meta in i['metadata']['instrumentType']:
|
|
267
|
+
#print(i['metadata'])
|
|
268
|
+
if(optionType=="Fut"):
|
|
269
|
+
if(i['metadata']['expiryDate']==expiryDate):
|
|
270
|
+
lastPrice = i['metadata']['lastPrice']
|
|
271
|
+
|
|
272
|
+
if((optionType=="Put")or(optionType=="Call")):
|
|
273
|
+
if (i['metadata']["expiryDate"]==expiryDate):
|
|
274
|
+
if (i['metadata']["optionType"]==optionType):
|
|
275
|
+
if (i['metadata']["strikePrice"]==strikePrice):
|
|
276
|
+
#print(i['metadata'])
|
|
277
|
+
lastPrice = i['metadata']['lastPrice']
|
|
278
|
+
|
|
279
|
+
if(optionType=="-"):
|
|
280
|
+
lastPrice = payload['underlyingValue']
|
|
281
|
+
|
|
282
|
+
return lastPrice
|
|
283
|
+
|
|
284
|
+
# print(nse_quote_ltp("RELIANCE"))
|
|
285
|
+
# print(nse_quote_ltp("RELIANCE","latest","Fut"))
|
|
286
|
+
# print(nse_quote_ltp("RELIANCE","next","Fut"))
|
|
287
|
+
# print(nse_quote_ltp("BANKNIFTY","latest","PE",32000))
|
|
288
|
+
# print(nse_quote_ltp("BANKNIFTY","next","PE",32000))
|
|
289
|
+
# print(nse_quote_ltp("BANKNIFTY","10-Jun-2021","PE",32000))
|
|
290
|
+
# print(nse_quote_ltp("BANKNIFTY","17-Jun-2021","PE",32000))
|
|
291
|
+
# print(nse_quote_ltp("RELIANCE","latest","PE",2300))
|
|
292
|
+
# print(nse_quote_ltp("RELIANCE","next","PE",2300))
|
|
293
|
+
|
|
294
|
+
def nse_quote_meta(symbol,expiryDate="latest",optionType="-",strikePrice=0):
|
|
295
|
+
payload = nse_quote(symbol)
|
|
296
|
+
#https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists
|
|
297
|
+
#https://stackoverflow.com/questions/19199984/sort-a-list-in-python
|
|
298
|
+
|
|
299
|
+
#BankNIFTY and NIFTY has weekly options. Using this Jugaad which has primary base of assumption that Reliance will not step out of FNO.
|
|
300
|
+
#forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
|
|
301
|
+
if((symbol in indices) and (optionType=="Fut")):
|
|
302
|
+
dates = expiry_list("RELIANCE","list")
|
|
303
|
+
if(expiryDate=="latest"): expiryDate=dates[0]
|
|
304
|
+
if(expiryDate=="next"): expiryDate=dates[1]
|
|
305
|
+
|
|
306
|
+
if(expiryDate=="latest") or (expiryDate=="next"):
|
|
307
|
+
dates=list(set((payload["expiryDates"])))
|
|
308
|
+
dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
|
|
309
|
+
if(expiryDate=="latest"): expiryDate=dates[0]
|
|
310
|
+
if(expiryDate=="next"): expiryDate=dates[1]
|
|
311
|
+
|
|
312
|
+
meta = "Options"
|
|
313
|
+
if(optionType=="Fut"): meta = "Futures"
|
|
314
|
+
if(optionType=="PE"):optionType="Put"
|
|
315
|
+
if(optionType=="CE"):optionType="Call"
|
|
316
|
+
|
|
317
|
+
if(optionType!="-"):
|
|
318
|
+
for i in payload['stocks']:
|
|
319
|
+
if meta in i['metadata']['instrumentType']:
|
|
320
|
+
#print(i['metadata'])
|
|
321
|
+
if(optionType=="Fut"):
|
|
322
|
+
if(i['metadata']['expiryDate']==expiryDate):
|
|
323
|
+
metadata = i['metadata']
|
|
324
|
+
|
|
325
|
+
if((optionType=="Put")or(optionType=="Call")):
|
|
326
|
+
if (i['metadata']["expiryDate"]==expiryDate):
|
|
327
|
+
if (i['metadata']["optionType"]==optionType):
|
|
328
|
+
if (i['metadata']["strikePrice"]==strikePrice):
|
|
329
|
+
#print(i['metadata'])
|
|
330
|
+
metadata = i['metadata']
|
|
331
|
+
|
|
332
|
+
if(optionType=="-"):
|
|
333
|
+
metadata = i['metadata']
|
|
334
|
+
|
|
335
|
+
return metadata
|
|
336
|
+
|
|
337
|
+
def nse_optionchain_ltp(payload,strikePrice,optionType,inp=0,intent=""):
|
|
338
|
+
expiry_dates = payload['records']['expiryDates']
|
|
339
|
+
expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
|
|
340
|
+
expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
|
|
341
|
+
expiryDate=expiry_dates[inp]
|
|
342
|
+
for x in range(len(payload['records']['data'])):
|
|
343
|
+
if((payload['records']['data'][x]['strikePrice']==strikePrice) & (payload['records']['data'][x]['expiryDate']==expiryDate)):
|
|
344
|
+
if(intent==""): return payload['records']['data'][x][optionType]['lastPrice']
|
|
345
|
+
if(intent=="sell"): return payload['records']['data'][x][optionType]['bidprice']
|
|
346
|
+
if(intent=="buy"): return payload['records']['data'][x][optionType]['askPrice']
|
|
347
|
+
|
|
348
|
+
def nse_eq(symbol):
|
|
349
|
+
symbol = nsesymbolpurify(symbol)
|
|
350
|
+
try:
|
|
351
|
+
payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
|
|
352
|
+
try:
|
|
353
|
+
if(payload['error']=={}):
|
|
354
|
+
print("Please use nse_fno() function to reduce latency.")
|
|
355
|
+
payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
|
|
356
|
+
except:
|
|
357
|
+
pass
|
|
358
|
+
except KeyError:
|
|
359
|
+
print("Getting Error While Fetching.")
|
|
360
|
+
return payload
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def nse_fno(symbol):
|
|
364
|
+
symbol = nsesymbolpurify(symbol)
|
|
365
|
+
try:
|
|
366
|
+
payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
|
|
367
|
+
try:
|
|
368
|
+
if(payload['error']=={}):
|
|
369
|
+
print("Please use nse_eq() function to reduce latency.")
|
|
370
|
+
payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
|
|
371
|
+
except KeyError:
|
|
372
|
+
pass
|
|
373
|
+
except KeyError:
|
|
374
|
+
print("Getting Error While Fetching.")
|
|
375
|
+
return payload
|
|
376
|
+
|
|
377
|
+
def quote_equity(symbol):
|
|
378
|
+
return nse_eq(symbol)
|
|
379
|
+
|
|
380
|
+
def quote_derivative(symbol):
|
|
381
|
+
return nse_fno(symbol)
|
|
382
|
+
|
|
383
|
+
def option_chain(symbol):
|
|
384
|
+
return nse_optionchain_scrapper(symbol)
|
|
385
|
+
|
|
386
|
+
def nse_holidays(type="trading"):
|
|
387
|
+
if(type=="clearing"):
|
|
388
|
+
payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=clearing')
|
|
389
|
+
if(type=="trading"):
|
|
390
|
+
payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=trading')
|
|
391
|
+
return payload
|
|
392
|
+
|
|
393
|
+
def holiday_master(type="trading"):
|
|
394
|
+
return nse_holidays(type)
|
|
395
|
+
|
|
396
|
+
def nse_results(index="equities",period="Quarterly"):
|
|
397
|
+
if(index=="equities") or (index=="debt") or (index=="sme"):
|
|
398
|
+
if(period=="Quarterly") or (period=="Annual")or (period=="Half-Yearly")or (period=="Others"):
|
|
399
|
+
payload = nsefetch('https://www.nseindia.com/api/corporates-financial-results?index='+index+'&period='+period)
|
|
400
|
+
return pd.json_normalize(payload)
|
|
401
|
+
else:
|
|
402
|
+
print("Give Correct Period Input")
|
|
403
|
+
else:
|
|
404
|
+
print("Give Correct Index Input")
|
|
405
|
+
|
|
406
|
+
def nse_events():
|
|
407
|
+
output = nsefetch('https://www.nseindia.com/api/event-calendar')
|
|
408
|
+
return pd.json_normalize(output)
|
|
409
|
+
|
|
410
|
+
def nse_past_results(symbol):
|
|
411
|
+
symbol = nsesymbolpurify(symbol)
|
|
412
|
+
return nsefetch('https://www.nseindia.com/api/results-comparision?symbol='+symbol)
|
|
413
|
+
|
|
414
|
+
def expiry_list(symbol,type="list"):
|
|
415
|
+
logging.info("Getting Expiry List of: "+ symbol)
|
|
416
|
+
|
|
417
|
+
if(type!="list"):
|
|
418
|
+
payload = nse_optionchain_scrapper(symbol)
|
|
419
|
+
payload = pd.DataFrame({'Date':payload['records']['expiryDates']})
|
|
420
|
+
return payload
|
|
421
|
+
|
|
422
|
+
if(type=="list"):
|
|
423
|
+
payload = nse_quote(symbol)
|
|
424
|
+
dates=list(set((payload["expiryDates"])))
|
|
425
|
+
dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
|
|
426
|
+
return dates
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def nse_custom_function_secfno(symbol,attribute="lastPrice"):
|
|
430
|
+
positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
431
|
+
endp = len(positions['data'])
|
|
432
|
+
for x in range(0, endp):
|
|
433
|
+
if(positions['data'][x]['symbol']==symbol.upper()):
|
|
434
|
+
return positions['data'][x][attribute]
|
|
435
|
+
|
|
436
|
+
def nse_blockdeal():
|
|
437
|
+
payload = nsefetch('https://nseindia.com/api/block-deal')
|
|
438
|
+
return payload
|
|
439
|
+
|
|
440
|
+
def nse_marketStatus():
|
|
441
|
+
payload = nsefetch('https://nseindia.com/api/marketStatus')
|
|
442
|
+
return payload
|
|
443
|
+
|
|
444
|
+
def nse_circular(mode="latest"):
|
|
445
|
+
if(mode=="latest"):
|
|
446
|
+
payload = nsefetch('https://nseindia.com/api/latest-circular')
|
|
447
|
+
else:
|
|
448
|
+
payload = nsefetch('https://www.nseindia.com/api/circulars')
|
|
449
|
+
return payload
|
|
450
|
+
|
|
451
|
+
def nse_fiidii(mode="pandas"):
|
|
452
|
+
try:
|
|
453
|
+
if(mode=="pandas"):
|
|
454
|
+
return pd.DataFrame(nsefetch('https://www.nseindia.com/api/fiidiiTradeReact'))
|
|
455
|
+
else:
|
|
456
|
+
return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
|
|
457
|
+
except:
|
|
458
|
+
logger.info("Pandas is not working for some reason.")
|
|
459
|
+
return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
|
|
460
|
+
|
|
461
|
+
def nsetools_get_quote(symbol):
|
|
462
|
+
payload = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
463
|
+
for m in range(len(payload['data'])):
|
|
464
|
+
if(payload['data'][m]['symbol']==symbol.upper()):
|
|
465
|
+
return payload['data'][m]
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def nse_index():
|
|
469
|
+
payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
|
|
470
|
+
payload = pd.DataFrame(payload["data"])
|
|
471
|
+
return payload
|
|
472
|
+
|
|
473
|
+
def nse_get_index_list():
|
|
474
|
+
payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
|
|
475
|
+
payload = pd.DataFrame(payload["data"])
|
|
476
|
+
return payload["indexName"].tolist()
|
|
477
|
+
|
|
478
|
+
def nse_get_index_quote(index):
|
|
479
|
+
payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
|
|
480
|
+
for m in range(len(payload['data'])):
|
|
481
|
+
if(payload['data'][m]["indexName"] == index.upper()):
|
|
482
|
+
return payload['data'][m]
|
|
483
|
+
|
|
484
|
+
def nse_get_advances_declines(mode="pandas"):
|
|
485
|
+
try:
|
|
486
|
+
if(mode=="pandas"):
|
|
487
|
+
positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
488
|
+
return pd.DataFrame(positions['data'])
|
|
489
|
+
else:
|
|
490
|
+
return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
491
|
+
except:
|
|
492
|
+
logger.info("Pandas is not working for some reason.")
|
|
493
|
+
return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
494
|
+
|
|
495
|
+
def nse_get_top_losers():
|
|
496
|
+
positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
497
|
+
df = pd.DataFrame(positions['data'])
|
|
498
|
+
df = df.sort_values(by="pChange")
|
|
499
|
+
return df.head(5)
|
|
500
|
+
|
|
501
|
+
def nse_get_top_gainers():
|
|
502
|
+
positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
|
|
503
|
+
df = pd.DataFrame(positions['data'])
|
|
504
|
+
df = df.sort_values(by="pChange" , ascending = False)
|
|
505
|
+
return df.head(5)
|
|
506
|
+
|
|
507
|
+
def nse_get_fno_lot_sizes(symbol="all",mode="list"):
|
|
508
|
+
url="https://archives.nseindia.com/content/fo/fo_mktlots.csv"
|
|
509
|
+
|
|
510
|
+
if(mode=="list"):
|
|
511
|
+
s=requests.get(url).text
|
|
512
|
+
res_dict = {}
|
|
513
|
+
for line in s.split('\n'):
|
|
514
|
+
if line != '' and re.search(',', line) and (line.casefold().find('symbol') == -1):
|
|
515
|
+
(code, name) = [x.strip() for x in line.split(',')[1:3]]
|
|
516
|
+
res_dict[code] = int(name)
|
|
517
|
+
if(symbol=="all"):
|
|
518
|
+
return res_dict
|
|
519
|
+
if(symbol!=""):
|
|
520
|
+
return res_dict[symbol.upper()]
|
|
521
|
+
|
|
522
|
+
if(mode=="pandas"):
|
|
523
|
+
payload = pd.read_csv(url)
|
|
524
|
+
if(symbol=="all"):
|
|
525
|
+
return payload
|
|
526
|
+
else:
|
|
527
|
+
payload = payload[(payload.iloc[:, 1] == symbol.upper())]
|
|
528
|
+
return payload
|
|
529
|
+
|
|
530
|
+
def whoistheboss():
|
|
531
|
+
return "subhash"
|
|
532
|
+
|
|
533
|
+
def indiavix():
|
|
534
|
+
payload = nsefetch("https://www.nseindia.com/api/allIndices")
|
|
535
|
+
for x in range(0, len(payload["data"])):
|
|
536
|
+
if(payload["data"][x]["index"]=="INDIA VIX"):
|
|
537
|
+
return payload["data"][x]["last"]
|
|
538
|
+
|
|
539
|
+
def index_info(index):
|
|
540
|
+
payload = nsefetch("https://www.nseindia.com/api/allIndices")
|
|
541
|
+
for x in range(0, len(payload["data"])):
|
|
542
|
+
if(payload["data"][x]["index"]==index):
|
|
543
|
+
return payload["data"][x]
|
|
544
|
+
|
|
545
|
+
import math
|
|
546
|
+
from scipy.stats import norm
|
|
547
|
+
|
|
548
|
+
def black_scholes_dexter(S0,X,t,σ="",r=10,q=0.0,td=365):
|
|
549
|
+
|
|
550
|
+
if(σ==""):σ =indiavix()
|
|
551
|
+
|
|
552
|
+
S0,X,σ,r,q,t = float(S0),float(X),float(σ/100),float(r/100),float(q/100),float(t/td)
|
|
553
|
+
#https://unofficed.com/black-scholes-model-options-calculator-google-sheet/
|
|
554
|
+
|
|
555
|
+
d1 = (math.log(S0/X)+(r-q+0.5*σ**2)*t)/(σ*math.sqrt(t))
|
|
556
|
+
#stackoverflow.com/questions/34258537/python-typeerror-unsupported-operand-types-for-float-and-int
|
|
557
|
+
|
|
558
|
+
#stackoverflow.com/questions/809362/how-to-calculate-cumulative-normal-distribution
|
|
559
|
+
Nd1 = (math.exp((-d1**2)/2))/math.sqrt(2*math.pi)
|
|
560
|
+
d2 = d1-σ*math.sqrt(t)
|
|
561
|
+
Nd2 = norm.cdf(d2)
|
|
562
|
+
call_theta =(-((S0*σ*math.exp(-q*t))/(2*math.sqrt(t))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2))-(r*X*math.exp(-r*t)*norm.cdf(d2))+(q*math.exp(-q*t)*S0*norm.cdf(d1)))/td
|
|
563
|
+
put_theta =(-((S0*σ*math.exp(-q*t))/(2*math.sqrt(t))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2))+(r*X*math.exp(-r*t)*norm.cdf(-d2))-(q*math.exp(-q*t)*S0*norm.cdf(-d1)))/td
|
|
564
|
+
call_premium =math.exp(-q*t)*S0*norm.cdf(d1)-X*math.exp(-r*t)*norm.cdf(d1-σ*math.sqrt(t))
|
|
565
|
+
put_premium =X*math.exp(-r*t)*norm.cdf(-d2)-math.exp(-q*t)*S0*norm.cdf(-d1)
|
|
566
|
+
call_delta =math.exp(-q*t)*norm.cdf(d1)
|
|
567
|
+
put_delta =math.exp(-q*t)*(norm.cdf(d1)-1)
|
|
568
|
+
gamma =(math.exp(-r*t)/(S0*σ*math.sqrt(t)))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2)
|
|
569
|
+
vega = ((1/100)*S0*math.exp(-r*t)*math.sqrt(t))*(1/(math.sqrt(2*math.pi))*math.exp(-(d1*d1)/2))
|
|
570
|
+
call_rho =(1/100)*X*t*math.exp(-r*t)*norm.cdf(d2)
|
|
571
|
+
put_rho =(-1/100)*X*t*math.exp(-r*t)*norm.cdf(-d2)
|
|
572
|
+
|
|
573
|
+
return call_theta,put_theta,call_premium,put_premium,call_delta,put_delta,gamma,vega,call_rho,put_rho
|
|
574
|
+
|
|
575
|
+
def equity_history_virgin(symbol,series,start_date,end_date):
|
|
576
|
+
#url="https://www.nseindia.com/api/historical/cm/equity?symbol="+symbol+"&series=[%22"+series+"%22]&from="+str(start_date)+"&to="+str(end_date)+""
|
|
577
|
+
url = 'https://www.nseindia.com/api/historical/cm/equity?symbol=' + symbol + '&series=["' + series + '"]&from=' + start_date + '&to=' + end_date
|
|
578
|
+
|
|
579
|
+
payload = nsefetch(url)
|
|
580
|
+
return pd.DataFrame.from_records(payload["data"])
|
|
581
|
+
|
|
582
|
+
# You shall see beautiful use the logger function.
|
|
583
|
+
def equity_history(symbol,series,start_date,end_date):
|
|
584
|
+
#We are getting the input in text. So it is being converted to Datetime object from String.
|
|
585
|
+
start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
|
|
586
|
+
end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
|
|
587
|
+
logging.info("Starting Date: "+str(start_date))
|
|
588
|
+
logging.info("Ending Date: "+str(end_date))
|
|
589
|
+
|
|
590
|
+
#We are calculating the difference between the days
|
|
591
|
+
diff = end_date-start_date
|
|
592
|
+
logging.info("Total Number of Days: "+str(diff.days))
|
|
593
|
+
logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
|
|
594
|
+
logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
total=pd.DataFrame()
|
|
598
|
+
for i in range (0,int(diff.days/40)):
|
|
599
|
+
|
|
600
|
+
temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
|
|
601
|
+
start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
|
|
602
|
+
|
|
603
|
+
logging.info("Loop = "+str(i))
|
|
604
|
+
logging.info("====")
|
|
605
|
+
logging.info("Starting Date: "+str(start_date))
|
|
606
|
+
logging.info("Ending Date: "+str(temp_date))
|
|
607
|
+
logging.info("====")
|
|
608
|
+
|
|
609
|
+
#total=total.append(equity_history_virgin(symbol,series,start_date,temp_date))
|
|
610
|
+
#total=total.concat(equity_history_virgin(symbol,series,start_date,temp_date))
|
|
611
|
+
total = pd.concat([total, equity_history_virgin(symbol, series, start_date, temp_date)])
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
logging.info("Length of the Table: "+ str(len(total)))
|
|
615
|
+
|
|
616
|
+
#Preparation for the next loop
|
|
617
|
+
start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
|
|
621
|
+
end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
|
|
622
|
+
|
|
623
|
+
logging.info("End Loop")
|
|
624
|
+
logging.info("====")
|
|
625
|
+
logging.info("Starting Date: "+str(start_date))
|
|
626
|
+
logging.info("Ending Date: "+str(end_date))
|
|
627
|
+
logging.info("====")
|
|
628
|
+
|
|
629
|
+
#total=total.append(equity_history_virgin(symbol,series,start_date,end_date))
|
|
630
|
+
#total=total.concat(equity_history_virgin(symbol,series,start_date,end_date))
|
|
631
|
+
total = pd.concat([total, equity_history_virgin(symbol, series, start_date, end_date)])
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
logging.info("Finale")
|
|
635
|
+
logging.info("Length of the Total Dataset: "+ str(len(total)))
|
|
636
|
+
payload = total.iloc[::-1].reset_index(drop=True)
|
|
637
|
+
return payload
|
|
638
|
+
|
|
639
|
+
def derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
|
|
640
|
+
|
|
641
|
+
instrumentType = instrumentType.lower()
|
|
642
|
+
|
|
643
|
+
if(instrumentType=="options"):
|
|
644
|
+
instrumentType="OPTSTK"
|
|
645
|
+
if("NIFTY" in symbol): instrumentType="OPTIDX"
|
|
646
|
+
|
|
647
|
+
if(instrumentType=="futures"):
|
|
648
|
+
instrumentType="FUTSTK"
|
|
649
|
+
if("NIFTY" in symbol): instrumentType="FUTIDX"
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
#if(((instrumentType=="OPTIDX")or (instrumentType=="OPTSTK")) and (expiry_date!="")):
|
|
653
|
+
if(strikePrice!=""):
|
|
654
|
+
strikePrice = "%.2f" % strikePrice
|
|
655
|
+
strikePrice = str(strikePrice)
|
|
656
|
+
|
|
657
|
+
nsefetch_url = "https://www.nseindia.com/api/historical/fo/derivatives?&from="+str(start_date)+"&to="+str(end_date)+"&optionType="+optionType+"&strikePrice="+strikePrice+"&expiryDate="+expiry_date+"&instrumentType="+instrumentType+"&symbol="+symbol+""
|
|
658
|
+
payload = nsefetch(nsefetch_url)
|
|
659
|
+
logging.info(nsefetch_url)
|
|
660
|
+
logging.info(payload)
|
|
661
|
+
return pd.DataFrame.from_records(payload["data"])
|
|
662
|
+
|
|
663
|
+
def derivative_history(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
|
|
664
|
+
#We are getting the input in text. So it is being converted to Datetime object from String.
|
|
665
|
+
start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
|
|
666
|
+
end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
|
|
667
|
+
logging.info("Starting Date: "+str(start_date))
|
|
668
|
+
logging.info("Ending Date: "+str(end_date))
|
|
669
|
+
|
|
670
|
+
#We are calculating the difference between the days
|
|
671
|
+
diff = end_date-start_date
|
|
672
|
+
logging.info("Total Number of Days: "+str(diff.days))
|
|
673
|
+
logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
|
|
674
|
+
logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
total=pd.DataFrame()
|
|
678
|
+
for i in range (0,int(diff.days/40)):
|
|
679
|
+
|
|
680
|
+
temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
|
|
681
|
+
start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
|
|
682
|
+
|
|
683
|
+
logging.info("Loop = "+str(i))
|
|
684
|
+
logging.info("====")
|
|
685
|
+
logging.info("Starting Date: "+str(start_date))
|
|
686
|
+
logging.info("Ending Date: "+str(temp_date))
|
|
687
|
+
logging.info("====")
|
|
688
|
+
|
|
689
|
+
#total=total.append(derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType))
|
|
690
|
+
#total=total.concat([total, derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType)])
|
|
691
|
+
total = pd.concat([total, derivative_history_virgin(symbol, start_date, temp_date, instrumentType, expiry_date, strikePrice, optionType)])
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
logging.info("Length of the Table: "+ str(len(total)))
|
|
695
|
+
|
|
696
|
+
#Preparation for the next loop
|
|
697
|
+
start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
|
|
701
|
+
end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
|
|
702
|
+
|
|
703
|
+
logging.info("End Loop")
|
|
704
|
+
logging.info("====")
|
|
705
|
+
logging.info("Starting Date: "+str(start_date))
|
|
706
|
+
logging.info("Ending Date: "+str(end_date))
|
|
707
|
+
logging.info("====")
|
|
708
|
+
|
|
709
|
+
#total=total.append(derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType))
|
|
710
|
+
#total = total.concat([total, derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType)])
|
|
711
|
+
total = pd.concat([total, derivative_history_virgin(symbol, start_date, end_date, instrumentType, expiry_date, strikePrice, optionType)])
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
logging.info("Finale")
|
|
716
|
+
logging.info("Length of the Total Dataset: "+ str(len(total)))
|
|
717
|
+
payload = total.iloc[::-1].reset_index(drop=True)
|
|
718
|
+
return payload
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def expiry_history(symbol,start_date="",end_date="",type="options"):
|
|
722
|
+
if(end_date==""):end_date=end_date
|
|
723
|
+
nsefetch_url = "https://www.nseindia.com/api/historical/fo/derivatives/meta?&from="+start_date+"&to="+end_date+"&symbol="+symbol+""
|
|
724
|
+
payload = nsefetch(nsefetch_url)
|
|
725
|
+
|
|
726
|
+
#print(payload)
|
|
727
|
+
|
|
728
|
+
for key, value in payload['expiryDatesByInstrument'].items():
|
|
729
|
+
if type.lower() == "options" and "OPT" in key:
|
|
730
|
+
payload_data = payload['expiryDatesByInstrument'][key]
|
|
731
|
+
break
|
|
732
|
+
elif type.lower() == "futures" and "FUT" in key:
|
|
733
|
+
payload_data = payload['expiryDatesByInstrument'][key]
|
|
734
|
+
break
|
|
735
|
+
|
|
736
|
+
# Convert start_date and end_date to datetime objects
|
|
737
|
+
start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
|
|
738
|
+
end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
|
|
739
|
+
|
|
740
|
+
# Initialize an empty list to store filtered dates
|
|
741
|
+
filtered_date_payload = []
|
|
742
|
+
|
|
743
|
+
# Initialize a flag to check if the first date after end_date has been added
|
|
744
|
+
added_after_end_date = False
|
|
745
|
+
|
|
746
|
+
# Iterate through date_payload and filter dates within the range
|
|
747
|
+
for date_str in payload_data:
|
|
748
|
+
date_obj = datetime.datetime.strptime(date_str, "%d-%b-%Y")
|
|
749
|
+
if start_date <= date_obj <= end_date:
|
|
750
|
+
filtered_date_payload.append(date_str)
|
|
751
|
+
elif date_obj > end_date and not added_after_end_date:
|
|
752
|
+
filtered_date_payload.append(date_str)
|
|
753
|
+
added_after_end_date = True
|
|
754
|
+
|
|
755
|
+
return filtered_date_payload
|
|
756
|
+
|
|
757
|
+
# # Nifty Indicies Site
|
|
758
|
+
|
|
759
|
+
niftyindices_headers = {
|
|
760
|
+
'Connection': 'keep-alive',
|
|
761
|
+
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
|
|
762
|
+
'Accept': 'application/json, text/javascript, */*; q=0.01',
|
|
763
|
+
'DNT': '1',
|
|
764
|
+
'X-Requested-With': 'XMLHttpRequest',
|
|
765
|
+
'sec-ch-ua-mobile': '?0',
|
|
766
|
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
|
|
767
|
+
'Content-Type': 'application/json; charset=UTF-8',
|
|
768
|
+
'Origin': 'https://niftyindices.com',
|
|
769
|
+
'Sec-Fetch-Site': 'same-origin',
|
|
770
|
+
'Sec-Fetch-Mode': 'cors',
|
|
771
|
+
'Sec-Fetch-Dest': 'empty',
|
|
772
|
+
'Referer': 'https://niftyindices.com/reports/historical-data',
|
|
773
|
+
'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
def index_history(symbol,start_date,end_date):
|
|
777
|
+
data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
|
|
778
|
+
payload = requests.post('https://niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString', headers=niftyindices_headers, json=data).json()
|
|
779
|
+
payload = json.loads(payload["d"])
|
|
780
|
+
payload=pd.DataFrame.from_records(payload)
|
|
781
|
+
return payload
|
|
782
|
+
|
|
783
|
+
def index_pe_pb_div(symbol,start_date,end_date):
|
|
784
|
+
data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
|
|
785
|
+
payload = requests.post('https://niftyindices.com/Backpage.aspx/getpepbHistoricaldataDBtoString', headers=niftyindices_headers, json=data).json()
|
|
786
|
+
payload = json.loads(payload["d"])
|
|
787
|
+
payload=pd.DataFrame.from_records(payload)
|
|
788
|
+
return payload
|
|
789
|
+
|
|
790
|
+
def index_total_returns(symbol,start_date,end_date):
|
|
791
|
+
data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
|
|
792
|
+
payload = requests.post('https://niftyindices.com/Backpage.aspx/getTotalReturnIndexString', headers=niftyindices_headers, json=data).json()
|
|
793
|
+
payload = json.loads(payload["d"])
|
|
794
|
+
payload=pd.DataFrame.from_records(payload)
|
|
795
|
+
return payload
|
|
796
|
+
|
|
797
|
+
def get_bhavcopy(date):
|
|
798
|
+
date = date.replace("-","")
|
|
799
|
+
payload=pd.read_csv("https://archives.nseindia.com/products/content/sec_bhavdata_full_"+date+".csv")
|
|
800
|
+
return payload
|
|
801
|
+
|
|
802
|
+
def get_bulkdeals():
|
|
803
|
+
payload=pd.read_csv("https://archives.nseindia.com/content/equities/bulk.csv")
|
|
804
|
+
return payload
|
|
805
|
+
|
|
806
|
+
def get_blockdeals():
|
|
807
|
+
payload=pd.read_csv("https://archives.nseindia.com/content/equities/block.csv")
|
|
808
|
+
return payload
|
|
809
|
+
|
|
810
|
+
#Request from subhash
|
|
811
|
+
## https://unofficed.com/how-to-find-the-beta-of-indian-stocks-using-python/
|
|
812
|
+
def get_beta_df_maker(symbol,days):
|
|
813
|
+
if("NIFTY" in symbol):
|
|
814
|
+
end_date = datetime.datetime.now().strftime("%d-%b-%Y")
|
|
815
|
+
end_date = str(end_date)
|
|
816
|
+
|
|
817
|
+
start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%b-%Y")
|
|
818
|
+
start_date = str(start_date)
|
|
819
|
+
|
|
820
|
+
df2=index_history(symbol,start_date,end_date)
|
|
821
|
+
df2["daily_change"]=df2["CLOSE"].astype(float).pct_change()
|
|
822
|
+
df2=df2[['HistoricalDate','daily_change']]
|
|
823
|
+
df2 = df2.iloc[1: , :]
|
|
824
|
+
return df2
|
|
825
|
+
else:
|
|
826
|
+
end_date = datetime.datetime.now().strftime("%d-%m-%Y")
|
|
827
|
+
end_date = str(end_date)
|
|
828
|
+
|
|
829
|
+
start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%m-%Y")
|
|
830
|
+
start_date = str(start_date)
|
|
831
|
+
|
|
832
|
+
df = equity_history(symbol,"EQ",start_date,end_date)
|
|
833
|
+
|
|
834
|
+
df["daily_change"]=df["CH_CLOSING_PRICE"].pct_change()
|
|
835
|
+
df=df[['CH_TIMESTAMP','daily_change']]
|
|
836
|
+
df = df.iloc[1: , :] #thispointer.com/drop-first-row-of-pandas-dataframe-3-ways/
|
|
837
|
+
return df
|
|
838
|
+
|
|
839
|
+
def getbeta(symbol,days=365,symbol2="NIFTY 50"):
|
|
840
|
+
return get_beta(symbol,days,symbol2)
|
|
841
|
+
|
|
842
|
+
def get_beta(symbol,days=365,symbol2="NIFTY 50"):
|
|
843
|
+
#Default is 248 days. (Input of Subhash)
|
|
844
|
+
df = get_beta_df_maker(symbol,days)
|
|
845
|
+
df2 = get_beta_df_maker(symbol2,days)
|
|
846
|
+
|
|
847
|
+
x=df["daily_change"].tolist()
|
|
848
|
+
y=df2["daily_change"].tolist()
|
|
849
|
+
#stackoverflow.com/questions/42670055/is-there-any-better-way-to-calculate-the-covariance-of-two-lists-than-this
|
|
850
|
+
mean_x = sum(x) / len(x)
|
|
851
|
+
mean_y = sum(y) / len(y)
|
|
852
|
+
covariance = sum((a - mean_x) * (b - mean_y) for (a,b) in zip(x,y)) / len(x)
|
|
853
|
+
|
|
854
|
+
mean = sum(y) / len(y)
|
|
855
|
+
variance = sum((i - mean) ** 2 for i in y) / len(y)
|
|
856
|
+
|
|
857
|
+
beta = covariance/variance
|
|
858
|
+
return round(beta,3)
|
|
859
|
+
|
|
860
|
+
def nse_preopen(key="NIFTY",type="pandas"):
|
|
861
|
+
payload = nsefetch("https://www.nseindia.com/api/market-data-pre-open?key="+key+"")
|
|
862
|
+
if(type=="pandas"):
|
|
863
|
+
payload = pd.DataFrame(payload['data'])
|
|
864
|
+
payload = pd.json_normalize(payload['metadata'])
|
|
865
|
+
return payload
|
|
866
|
+
else:
|
|
867
|
+
return payload
|
|
868
|
+
|
|
869
|
+
#By Avinash https://forum.unofficed.com/t/nsepython-documentation/376/102?u=dexter
|
|
870
|
+
def nse_preopen_movers(key="FO",filter=1.5):
|
|
871
|
+
preOpen_gainer=nse_preopen(key)
|
|
872
|
+
return preOpen_gainer[preOpen_gainer['pChange'] >1.5],preOpen_gainer[preOpen_gainer['pChange'] <-1.5]
|
|
873
|
+
|
|
874
|
+
# type = "securities"
|
|
875
|
+
# type = "etf"
|
|
876
|
+
# type = "sme"
|
|
877
|
+
#
|
|
878
|
+
# sort = "volume"
|
|
879
|
+
# sort = "value"
|
|
880
|
+
|
|
881
|
+
def nse_most_active(type="securities",sort="value"):
|
|
882
|
+
payload = nsefetch("https://www.nseindia.com/api/live-analysis-most-active-"+type+"?index="+sort+"")
|
|
883
|
+
payload = pd.DataFrame(payload["data"])
|
|
884
|
+
return payload
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def nse_eq_symbols():
|
|
888
|
+
#https://forum.unofficed.com/t/feature-request-stocklist-api/1073/11
|
|
889
|
+
eq_list_pd = pd.read_csv('https://archives.nseindia.com/content/equities/EQUITY_L.csv')
|
|
890
|
+
return eq_list_pd['SYMBOL'].tolist()
|
|
891
|
+
|
|
892
|
+
def nse_price_band_hitters(bandtype="both",view="AllSec"):
|
|
893
|
+
payload = nsefetch("https://www.nseindia.com/api/live-analysis-price-band-hitter")
|
|
894
|
+
|
|
895
|
+
#bandtype can be upper, lower, both
|
|
896
|
+
#view can be AllSec,SecGtr20,SecLwr20
|
|
897
|
+
return pd.DataFrame(payload[bandtype][view]["data"])
|
|
898
|
+
|
|
899
|
+
def nse_largedeals(mode="bulk_deals"):
|
|
900
|
+
payload = nsefetch('https://www.nseindia.com/api/snapshot-capital-market-largedeal')
|
|
901
|
+
if(mode=="bulk_deals"):
|
|
902
|
+
return pd.DataFrame(payload["BULK_DEALS_DATA"])
|
|
903
|
+
if(mode=="short_deals"):
|
|
904
|
+
return pd.DataFrame(payload["SHORT_DEALS_DATA"])
|
|
905
|
+
if(mode=="block_deals"):
|
|
906
|
+
return pd.DataFrame(payload["BLOCK_DEALS_DATA"])
|
|
907
|
+
|
|
908
|
+
def nse_largedeals_historical(from_date, to_date, mode="bulk_deals"):
|
|
909
|
+
if mode == "bulk_deals":
|
|
910
|
+
mode = "bulk-deals"
|
|
911
|
+
elif mode == "short_deals":
|
|
912
|
+
mode = "short-selling"
|
|
913
|
+
elif mode == "block_deals":
|
|
914
|
+
mode = "block-deals"
|
|
915
|
+
|
|
916
|
+
url='https://www.nseindia.com/api/historical/' + mode + '?from=' + from_date + '&to=' + to_date
|
|
917
|
+
logging.info("Fetching " + str(url))
|
|
918
|
+
payload = nsefetch(url)
|
|
919
|
+
return pd.DataFrame(payload["data"])
|
|
920
|
+
|
|
921
|
+
#https://forum.unofficed.com/t/feature-request-nse-fno-participant-wise-oi/1179/7
|
|
922
|
+
#print(get_fao_participant_oi("04-06-2021"))
|
|
923
|
+
def get_fao_participant_oi(date):
|
|
924
|
+
date = date.replace("-","")
|
|
925
|
+
payload=pd.read_csv("https://archives.nseindia.com/content/nsccl/fao_participant_oi_"+date+".csv")
|
|
926
|
+
return payload
|
|
927
|
+
|
|
928
|
+
#https://forum.unofficed.com/t/how-to-check-if-the-market-is-open-today-or-not/1268/1
|
|
929
|
+
def is_market_open(segment = "FO"): #COM,CD,CB,CMOT,COM,FO,IRD,MF,NDM,NTRP,SLBS
|
|
930
|
+
|
|
931
|
+
holiday_json = nse_holidays()[segment]
|
|
932
|
+
|
|
933
|
+
# Get today's date in the format 'dd-Mon-yyyy'
|
|
934
|
+
today_date = datetime.date.today().strftime('%d-%b-%Y')
|
|
935
|
+
|
|
936
|
+
# Check if today's date is in the holiday_json
|
|
937
|
+
for holiday in holiday_json:
|
|
938
|
+
if holiday['tradingDate'] != today_date:
|
|
939
|
+
print("FNO Market is open today. Have a Nice Trade!")
|
|
940
|
+
return True
|
|
941
|
+
if holiday['tradingDate'] == today_date:
|
|
942
|
+
print(f"Market is closed today because of {holiday['description']}")
|
|
943
|
+
return False
|
|
944
|
+
|
|
945
|
+
def nse_expirydetails_by_symbol(symbol,meta ="Futures",i=0):
|
|
946
|
+
payload = nse_quote(symbol)
|
|
947
|
+
|
|
948
|
+
if(meta=="Futures"):
|
|
949
|
+
selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
|
|
950
|
+
if(meta=="Options"):
|
|
951
|
+
selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)
|
|
952
|
+
|
|
953
|
+
expiry_dates=payload["expiryDatesByInstrument"][selected_key]
|
|
954
|
+
expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
|
|
955
|
+
expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
|
|
956
|
+
|
|
957
|
+
currentExpiry=expiry_dates[i]
|
|
958
|
+
currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date()
|
|
959
|
+
dte = (currentExpiry - datetime.datetime.now().date()).days
|
|
960
|
+
return currentExpiry,dte
|
|
961
|
+
|
|
962
|
+
def security_wise_archive(from_date, to_date, symbol, series="ALL"):
|
|
963
|
+
base_url = "https://www.nseindia.com/api/historical/securityArchives"
|
|
964
|
+
url = f"{base_url}?from={from_date}&to={to_date}&symbol={symbol.upper()}&dataType=priceVolumeDeliverable&series={series.upper()}"
|
|
965
|
+
payload = nsefetch(url)
|
|
954
966
|
return pd.DataFrame(payload['data'])
|