-
Notifications
You must be signed in to change notification settings - Fork 8
/
options3d.py
1485 lines (1164 loc) · 50 KB
/
options3d.py
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
# https://www.reddit.com/r/options/comments/gvmluu/thought_id_share_a_project_i_just_finished_3d/
# https://pastebin.com/GbfbY6eN
import justpy as jp
'''
Referemces:
- https://www.cboe.com/micro/vix/vixwhite.pdf
- https://en.wikipedia.org/wiki/Greeks_(finance)
- https://en.wikipedia.org/wiki/Bisection_method
- https://en.wikipedia.org/wiki/Newton%27s_method
- https://quant.stackexchange.com/questions/7761/a-simple-formula-for-calculating-implied-volatility
- https://www.risklatte.xyz/Articles/QuantitativeFinance/QF135.php
- https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html
- https://stackoverflow.com/questions/42677160/matplotlib-3d-scatter-plot-date
'''
import datetime as dt
import math as m
import matplotlib.pyplot as plt
import yfinance as yf
from mpl_toolkits import mplot3d
from scipy.stats import norm
plt.switch_backend('TkAgg')
'''
Template for an option contract.
'''
class Option:
'''
Option contract 'object' according to the vanilla Black-Scholes-Merton model for the price of a European option.
Required parameters:
- current date
Starting date to use for the calculation of time left until expiration,
Must be a string with the format 'YYYY-MM-DD'.
- current time
Starting time to use for the calculation of time left until expiration.
Must be a string in 24 hour time with the format 'HH:MM'.
Time to expiration is calculated in minutes, and then converted to years.
- opt_type
The type of option.
Must be a string with the value of either 'call' or 'put'.
- exp
Expiration date of the option.
Must be a string with the format 'YYYY-MM-DD'
- V
Price of the option.
Must be a numerical value.
- S
Current price of the underlying stock or ETF.
Must be a numerical value.
- K
Strike price of the option.
Must be a numerical value.
- r
Annualized risk-free interest rate. Conventional wisdom is to use the interest rate of
treasury bills with time left to maturity equal to the length of time left to expiration
of the option.
Must be a numerical value in decimal form. Example: 1% would be entered as 0.01
Optional parameters. Set these to 0 unless they are relevant (analyzing an entire option chain for example).
- volume
Number of contracts traded today.
Must be an integer.
- openInterest
Number of outstanding contracts of the same type, strike, and expiration.
Must be an integer.
- bid
Current bid price for the contract.
Must be a numerical value.
- ask
Current asking price for the contract.
Must be a numerical value.
**How this works**
This is what takes place When input values are passed and a contract is instantiated:
1) The following values are bound to the contract, available to call at any future point:
(For example: if you have created an option called "x", the expression "x.K" will return
the strike price of the option.)
- V
- S
- K
- t
- r
- itm (returns True if the option is in the money or False if it is out of the money)
- date (current date that was entered into the contract)
- time (current time that was entered into the contract)
- exp (expiration date of the contract)
- volume
- openInterest
- bid
- ask
2) Implied volatility is iteratively calculated using a bisection algorithm. The Newton-Raphson
algorithm was initially used because it is very fast, but has problems converging for deep ITM
options, even with a good initial guess (analytical approximation).
- can be called like "x.IV" using the option called "x" from the previous example.
3) The following greeks are calculated and also available to call:
- delta (change in option price with respect to the change in underlying price)
- gamma (change in delta with respect to the underlying price)
- theta (change in option price with respect to time)
- vega (change in option price with respect to implied volatility)
- rho (change in option price with respect to the risk-free rate)
- Lambda (capitalized because python has a built in 'lambda' function,
is the "leverage" that the contract provides)
**Note: the formulas for the higher order greeks have not been rigorously verified for correctness
- vanna (change in delta with respect to implied volatility)
- charm (change in delta with respect to time)
- vomma (change in vega with respect to implied volatility)
- veta (change in vega with respect to time)
- speed (change in gamma with respect to the underlying price)
- zomma (change in gamma with respect to implied volatility)
- color (change in gamma with respect to time)
- ultima (change in vomma with respect to volatility)
The following functions can also be called on the option:
(look at the functions themselves for further explanation)
- theoPrice
- theoPnL
- impliedPrices
This class can also be modified to take the dividend yield as an input. It is currently not used and set to 0.
'''
# TODO Make the impliedPrices function in terms of standard deviations
# TODO Create function that steps the contract through various times, IVs, and Ss
def __init__(self, current_date, current_time, opt_type, exp, V, S, K, r, volume, openInterest, bid, ask):
'''
Sets all the attributes of the contract.
'''
self.opt_type = opt_type.lower()
if self.opt_type == 'call':
if K < S:
self.itm = True
else:
self.itm = False
elif self.opt_type == 'put':
if S < K:
self.itm = True
else:
self.itm = False
self.exp = exp
self.V = round(V, 2)
self.S = round(S, 2)
self.K = round(K, 2)
self.date = current_date
self.time = current_time
self.exp = exp
self.t = self.__t(current_date, current_time, exp)
self.r = r
self.q = 0
self.volume = volume
self.openInterest = openInterest
self.bid = bid
self.ask = ask
vol_params = self.__BSMIV(self.S, self.t)
self.IV = vol_params[0]
self.vega = vol_params[1]
self.delta = self.__BSMdelta()
self.gamma = self.__BSMgamma()
self.theta = self.__BSMtheta()
self.rho = self.__BSMrho()
self.Lambda = self.__BSMlambda()
self.vanna = self.__BSMvanna()
self.charm = self.__BSMcharm()
self.vomma = self.__BSMvomma()
self.veta = self.__BSMveta()
self.speed = self.__BSMspeed()
self.zomma = self.__BSMzomma()
self.color = self.__BSMcolor()
self.ultima = self.__BSMultima()
def __repr__(self):
'''
Basic contract information.
'''
return '${:.2f} strike {} option expiring {}.'.format(self.K,
self.opt_type,
self.exp)
def __t(self, current_date, current_time, exp):
'''
Calculates the number of minutes to expiration, then converts to years.
Minutes are chosen because the VIX does this.
'''
hr, minute = 17, 30
year, month, day = [int(x) for x in exp.split('-')]
exp_dt = dt.datetime(year, month, day, hr, minute)
hr, minute = [int(x) for x in current_time.split(':')]
year, month, day = [int(x) for x in current_date.split('-')]
current_dt = dt.datetime(year, month, day, hr, minute)
days = 24*60*60*(exp_dt - current_dt).days
seconds = (exp_dt - current_dt).seconds
return (days + seconds) / (365*24*60*60)
def __d1(self, S, t, v):
'''
Struggling to come up with a good explanation.
It's an input into the cumulative distribution function.
'''
K = self.K
r = self.r
q = self.q
return ((m.log(S / K) + (r - q + 0.5*v**2)*t)) / (v*m.sqrt(t))
def __d2(self, S, t, v):
'''
Struggling to come up with a good explanation.
It's an input into the cumulative distribution function.
'''
d1 = self.__d1(S, t, v)
return d1 - v*m.sqrt(t)
def __pvK(self, t):
'''
Present value (pv) of the strike price (K)
'''
K = self.K
r = self.r
return K*m.exp(-r*t)
def __pvS(self, S, t):
'''
Present value (pv) of the stock price (S)
'''
q = self.q
return S*m.exp(-q*t)
def __phi(self, x): return norm.pdf(x)
def __N(self, x): return norm.cdf(x)
def __BSMprice(self, S, t, v):
'''
Black-Scholes-Merton price of a European call or put.
'''
K = self.K
pvK = self.__pvK(t)
pvS = self.__pvS(S, t)
if t != 0:
if self.opt_type == 'call':
Nd1 = self.__N(self.__d1(S, t, v))
Nd2 = -self.__N(self.__d2(S, t, v))
elif self.opt_type == 'put':
Nd1 = -self.__N(-self.__d1(S, t, v))
Nd2 = self.__N(-self.__d2(S, t, v))
return round(pvS*Nd1 + pvK*Nd2, 2)
elif t == 0:
if self.opt_type == 'call':
intrinsic_value = max(0, S - K)
elif self.opt_type == 'put':
intrinsic_value = max(0, K - S)
return round(intrinsic_value, 2)
# First order greek
def __BSMvega(self, S, t, v):
'''
First derivative of the option price (V) with respect to implied volatility (v or IV).
- For a 1% increase in IV, how much will the option price rise?
'''
pvK = self.__pvK(t)
phid2 = self.__phi(self.__d2(S, t, v))
return round((pvK*phid2*m.sqrt(t)) / 100, 4)
def __BSMIV(self, S, t):
'''
Volatility implied by the price of the option (v/IV).
- For the option price (V) to be fair, how volatile does the underlying (S) need to be?
Note: this function also returns vega, because initially the Newton-Raphson method was used, and
that requires vega to be solved at the same time. I didn't feel like rewriting things so I just
tacked on the vega calculation after IV was calculated.
'''
V = self.V
# K = self.K
# Bisection method
# We are trying to solve the error function which is the difference between the estimated price and the actual price
# V_est - V
# We need to generate two initial guesses at IV, one with a positive error and one with a negative error
# Should be reasonable to assume that vol will be somewhere between 1% and 2000%
v_lo = 0
v_hi = 20
v_mid = 0.5*(v_lo + v_hi)
V_mid = self.__BSMprice(S, t, v_mid)
error = V_mid - V
# Keep iterating until the error in estimated price is less than a cent
while v_hi - v_lo >= 0.1 / 100:
if error > 0:
v_hi = v_mid
elif error < 0:
v_lo = v_mid
elif error == 0:
break
v_mid = 0.5*(v_hi + v_lo)
V_mid = self.__BSMprice(S, t, v_mid)
error = V_mid - V
vega = self.__BSMvega(S, t, v_mid)
# Newton-Raphson method
# Kind of a mess because I was trying different things to get it to converge better for certain deep ITM options.
# v = (m.sqrt(2*m.pi) / t)*(V / S)
# min_err = 1000000
# best_v = 0
# best_vega = 0
# i = 0
# if self.opt_type == 'call':
# if V < S - K:
# V = S - K
# elif self.opt_type == 'put':
# if V < K - S:
# V = K - S
# while i < 5000:
# V_est = max(self.__BSMprice(S, t, v), 0.01)
# vega = max(self.__BSMvega(S, t, v), 0.0001)
# error = V_est - V
# if abs(error) < min_err:
# min_err = abs(error)
# best_v = v
# best_vega = vega
# if error == 0:
# break
# else:
# v = v - (error/(vega*100))*0.25
# if (i == 4999) & (error != 0):
# print('error in IV loop')
# i += 1
# return round(best_v, 4), round(best_vega, 4)
return round(v_mid, 4), round(vega, 4)
# First order greek
def __BSMdelta(self):
'''
First derivative of the option price (V) with respect to
the underlying price (S).
- For a $1 increase in S, how much will V rise?
- Also is the risk neutral probability S is at or below K by expiration.
Note that a risk neutral probability is not a real life probability.
It is simply the probability that would exist if it were possible to
create a completely risk free portfolio.
'''
S = self.S
t = self.t
v = self.IV
if self.opt_type == 'call':
Nd1 = self.__N(self.__d1(S, t, v))
elif self.opt_type == 'put':
Nd1 = -self.__N(-self.__d1(S, t, v))
return round(Nd1, 4)
# Second order greek
def __BSMgamma(self):
'''
First dertivative of delta with respect to the price of the underlying (S).
Second derivative of the option price (V) with respect to the stock price.
- For a $1 increase in the stock price, how much will delta increase?
'''
S = self.S
t = self.t
v = self.IV
pvK = self.__pvK(t)
phid2 = self.__phi(self.__d2(S, t, v))
return round((pvK*phid2) / (S**2*v*m.sqrt(t)), 4)
# First order greek
def __BSMtheta(self):
'''
First derivative of the option price (V) with respect to time (t).
- How much less will the option be worth tomorrow?
'''
S = self.S
t = self.t
v = self.IV
pvK = self.__pvK(t)
pvS = self.__pvS(S, t)
if self.opt_type == 'call':
phid1 = self.__phi(self.__d1(S, t, v))
r = -self.r
q = self.q
Nd1 = self.__N(self.__d1(S, t, v))
Nd2 = self.__N(self.__d2(S, t, v))
elif self.opt_type == 'put':
phid1 = self.__phi(-self.__d1(S, t, v))
r = self.r
q = -self.q
Nd1 = self.__N(-self.__d1(S, t, v))
Nd2 = self.__N(-self.__d2(S, t, v))
return round((-((pvS*phid1*v) / (2*m.sqrt(t))) + r*pvK*Nd2 + q*pvS*Nd1) / 365, 4)
# First order greek
def __BSMrho(self):
'''
First derivative of the option price (V) with respect to the risk free interest rate (r).
- For a 1% change in interest rates, by how many dollars will the value of the option change?
'''
S = self.S
t = self.t
v = self.IV
if self.opt_type == 'call':
pvK = self.__pvK(t)
Nd2 = self.__N(self.__d2(S, t, v))
elif self.opt_type == 'put':
pvK = -self.__pvK(t)
Nd2 = self.__N(-self.__d2(S, t, v))
return round((pvK*t*Nd2) / 100, 4)
# First order greek
def __BSMlambda(self):
'''
Measures the percentage change in the option price (V) per percentage change
in the price of the underlying (S).
- How much leverage does this option have?
'''
V = self.V
S = self.S
delta = self.delta
return round(delta*(S / V), 4)
# Second order greek
def __BSMvanna(self):
'''
First derivative of delta with respect to implied volatility.
- If volatility changes by 1%, how much will delta change?
'''
V = self.V
S = self.S
t = self.t
v = self.IV
d1 = self.__d1(S, t, v)
return round((V / S)*(1 - (d1 / (v*m.sqrt(t)))), 4)
# Second order greek
def __BSMcharm(self):
'''
First derivative of delta with respect to time.
- How much different will delta be tomorrow if everything else stays the same?
- Also can think of it as 'delta decay'
'''
S = self.S
t = self.t
r = self.r
v = self.IV
pv = m.exp(-self.q*t)
phid1 = self.__phi(self.__d1(S, t, v))
d2 = self.__d2(S, t, v)
mess = (2*(r - self.q)*t - d2*v*m.sqrt(t)) / (2*t*v*m.sqrt(t))
if self.opt_type == 'call':
q = self.q
Nd1 = self.__N(self.__d1(S, t, v))
elif self.opt_type == 'put':
q = -self.q
Nd1 = self.__N(-self.__d1(S, t, v))
return round((q*pv*Nd1 - pv*phid1*mess) / 365, 4)
# Second order greek
def __BSMvomma(self):
'''
First derivative of vega with respect to implied volatility.
Also the second derivative of the option price (V) with respect to
implied volatility.
- If IV changes by 1%, how will vega change?
'''
S = self.S
t = self.t
vega = self.vega
v = self.IV
d1 = self.__d1(S, t, v)
d2 = self.__d2(S, t, v)
return round((vega*d1*d2) / v, 4)
# Second order greek
def __BSMveta(self):
'''
First derivative of vega with respect to time (t).
- How much different will vega be tomorrow if everything else stays the same?
'''
S = self.S
t = self.t
v = self.IV
pvS = self.__pvS(S, t,)
d1 = self.__d1(S, t, v)
d2 = self.__d2(S, t, v)
phid1 = self.__phi(d1)
r = self.r
q = self.q
mess1 = ((r - q)*d1) / (v*m.sqrt(t))
mess2 = (1 + d1*d2) / (2*t)
return round((-pvS*phid1*m.sqrt(t)*(q + mess1 - mess2)) / (100*365), 4)
# Third order greek
def __BSMspeed(self):
'''
First derivative of gamma with respect to the underlying price (S).
- If S increases by $1, how will gamma change?
'''
gamma = self.gamma
S = self.S
v = self.IV
t = self.t
d1 = self.__d1(S, t, v)
return round(-(gamma / S)*((d1 / (v*m.sqrt(t))) + 1), 4)
# Third order greek
def __BSMzomma(self):
'''
First derivative of gamma with respect to implied volatility.
- If volatility changes by 1%, how will gamma change?
'''
gamma = self.gamma
S = self.S
t = self.t
v = self.IV
d1 = self.__d1(S, t, v)
d2 = self.__d2(S, t, v)
return round(gamma*((d1*d2 - 1) / v), 4)
# Third order greek
def __BSMcolor(self):
'''
First derivative of gamma with respect to time.
- How much different will gamma be tomorrow if everything else stays the same?
'''
S = self.S
t = self.t
r = self.r
v = self.IV
q = self.q
pv = m.exp(-q*t)
d1 = self.__d1(S, t, v)
d2 = self.__d2(S, t, v)
phid1 = self.__phi(d1)
mess = ((2*(r - q)*t - d2*v*m.sqrt(t)) / (v*m.sqrt(t)))*d1
return round((-pv*(phid1 / (2*S*t*v*m.sqrt(t)))*(2*q*t + 1 + mess)) / 365, 4)
# Third order greek
def __BSMultima(self):
'''
First derivative of vomma with respect to volatility.
- ...why? At this point it just seems like an exercise in calculus.
'''
vega = self.vega
S = self.S
t = self.t
v = self.IV
d1 = self.__d1(S, t, v)
d2 = self.__d2(S, t, v)
return round((-vega/(v**2))*(d1*d2*(1 - d1*d2) + d1**2 + d2**2), 4)
def theoPrice(self, date, S, v):
'''
Calculates the theoretical price of the option given:
- date 'YYYY-MM-DD'
- underlying price (S)
- implied volatility (v)
'''
year, month, day = date.split('-')
date = dt.datetime(int(year), int(month), int(day))
year, month, day = self.exp.split('-')
exp = dt.datetime(int(year), int(month), int(day))
t = (exp - date).days / 365
return self.__BSMprice(S, t, v)
def theoPnL(self, date, S, v):
'''
Calculates the theoretical profit/loss given:
- date 'YYYY-MM-DD'
- underlying price (S)
- implied volatility (v)
'''
return round(self.theoPrice(date, S, v) - self.V, 2)
def impliedPrices(self, show):
'''
Returns a tuple containing two lists.
- list[0] = dates from tomorrow until expiration
- list[1] = price on each date
- show = True | plots prices over time
- show = False | does not plot prices over time
If implied volatility is 20% for an option expiring in 1 year, this means that
the market is implying 1 year from now, there is roughly a 68% chance the underlying
will be 20% higher or lower than it currently is.
We can scale this annual number to any timeframe of interest according to v*sqrt(days/365).
The denominator is 365 because calendar days are used for simplicity.
If only trading days were to be taken into account, the denominator would be 252.
'''
S = self.S
v = self.IV
t = self.t
days = [i + 1 for i in range(int(t*365))]
if self.opt_type == 'call':
prices = [round(S + v*m.sqrt(day / 365)*S, 2) for day in days]
elif self.opt_type == 'put':
prices = [round(S - v*m.sqrt(day / 365)*S, 2) for day in days]
today = dt.datetime.now()
dates = [(today + dt.timedelta(days=day)).date() for day in days]
if show == True:
plt.title('Implied moves according to a:\n{}\nLast price: ${:.2f} | IV: {:.2f}%'.format(
self.__repr__(), self.V, 100*self.IV))
plt.xlabel('Date')
plt.ylabel('Spot price ($)')
plt.plot(dates, prices)
plt.show(block=True)
return dates, prices
'''
Plotting
'''
def date_time_input():
'''
Get either current time or user specified time.
It's a lot of code and used for both plot mode and single option mode.
returns current_date 'YYYY-MM-DD', current_time 'HH:MM'
Note: this is done better in single_option_input() for the expiration but I don't feel like refactoring right now
'''
# Print description of the date and time to be input
print('\n"Time" refers to the time to use for the time to expiration calculation.')
print('Example: if it is currently the weekend, and you want to see the metrics')
print('based on EOD Friday (which is what the prices will be from), enter "1",')
print('and enter the date of the most recent Friday, with 16:00 as the time (4pm).\n')
# Get date
which_datetime_string = 'Enter 0 to use current date/time, 1 to specify date/time: '
which_datetime = input(which_datetime_string)
datetime_options = ['0', '1']
# If incorrect input is supplied, loop until the input is correct
while which_datetime not in datetime_options:
which_datetime = input(which_datetime_string)
# If the current date/time is to be used, get the current date/time
if which_datetime == '0':
now = dt.datetime.now()
current_date = str(now.date())
current_time = '{}:{}'.format(now.time().hour, now.time().minute)
# If the date/time is to be specified
elif which_datetime == '1':
# Get current date
current_date_string = 'Enter current date [YYYY-MM-DD]: '
current_date = input(current_date_string)
try:
# Check if the date is in the correct format
year, month, day = [int(x) for x in current_date.split('-')]
dt.datetime(year, month, day)
except:
# If not, loop until the format is correct
stop_loop = 0
while stop_loop == 0:
current_date = input(current_date_string)
try:
year, month, day = [int(x)
for x in current_date.split('-')]
dt.datetime(year, month, day)
stop_loop = 1
except:
stop_loop = 0
# Get current time
current_time_string = 'Enter current 24H time [HH:MM]: '
current_time = input(current_time_string)
try:
# Check if the time is in the correct format
hour, minute = [int(x) for x in current_time.split(':')]
dt.datetime(year, month, day, hour, minute)
except:
# If not, loop until the format is correct
stop_loop = 0
while stop_loop == 0:
current_time = input(current_time_string)
try:
hour, minute = [int(x) for x in current_time.split(':')]
dt.datetime(year, month, day, hour, minute)
stop_loop = 1
except:
stop_loop = 0
return current_date, current_time
def multi_plot_input():
'''
User input for:
- ticker
- params
- price_type
- opt_type
- current_date
- current_time
- r
Returns each of the parameters in a tuple
'''
# Get ticker
ticker_string = '\nEnter ticker symbol: '
ticker = input(ticker_string).upper()
try:
# Try getting the first options expiration of the ticker
# If this succeeds we know it is a valid, optionable ticker symbol
yf.Ticker(ticker).options[0]
except:
# Run an input loop until a valid, optionable ticker is input
stop_loop = 0
while stop_loop == 0:
print('Ticker symbol is either invalid or not optionable.')
ticker = input(ticker_string).upper()
try:
yf.Ticker(ticker).options[0]
stop_loop = 1
except:
stop_loop = 0
# Print out a description of what can be plotted
print('\nStandard Parameters | Nonstandard Parameters')
print(' last or mid price | rho [dV/dr]')
print(' IV | charm [ddelta/dt]')
print(' delta | veta [dvega/dt]')
print(' theta | color [dgamma/dt]')
print(' volume | speed [dgamma/dS]')
print(' vega | vanna [ddelta/dv]')
print(' gamma | vomma [dvega/dv]')
print(' Open Interest | zomma [dgamma/dv]\n')
# Get parameters to plot
param_string = 'Enter 0 for standard parameters, 1 for nonstandard: '
param_type = input(param_string)
# If incorrect input is supplied, loop until the input is correct
while param_type not in ['0', '1']:
param_type = input(param_string)
# Set parameters
if param_type == '0':
params = [
'V',
'IV',
'delta',
'theta',
'volume',
'vega',
'gamma',
'openInterest'
]
elif param_type == '1':
print('\n**Warning: accuracy of higher order greeks has not been verified**\n')
params = [
'rho',
'charm',
'veta',
'color',
'speed',
'vanna',
'vomma',
'zomma'
]
# Get price type
price_type_string = 'Enter price to use for calcs [mid or last]: '
price_type = input(price_type_string)
# If incorrect input is supplied, loop until the input is correct
while price_type not in ['mid', 'last']:
price_type = input(price_type_string)
# Get option type
opt_type_string = 'Enter option type [calls, puts, or both]: '
opt_type = input(opt_type_string)
# If incorrect input is supplied, loop until the input is correct
while opt_type not in ['calls', 'puts', 'both']:
opt_type = input(opt_type_string)
# Get moneyness of options to plot
moneyess_string = 'Enter the moneyness to plot [itm, otm, or both]: '
moneyness = input(moneyess_string).lower()
# If incorrect input is supplied, loop until the input is correct
while moneyness not in ['itm', 'otm', 'both']:
moneyness = input(moneyess_string).lower()
# Get risk free rate
# If incorrect input is supplied, loop until the input is correct
stop_loop = 0
while stop_loop == 0:
r = input('Enter the risk-free rate: ')
try:
r = float(r)
stop_loop = 1
except:
continue
# Get date/time
current_date, current_time = date_time_input()
# Return the parameters
return ticker, params, price_type, opt_type, moneyness, current_date, current_time, r
def single_option_input():
# Get option type
opt_type_string = 'Enter option type [put or call]: '
opt_type = input(opt_type_string)
while opt_type not in ['put', 'call']:
opt_type = input(opt_type_string)
# Get expiration date
exp_string = 'Enter expiration date [YYYY-MM-DD]: '
exp = input(exp_string)
stop_loop = 0
while stop_loop == 0:
try:
year, month, day = [int(x) for x in exp.split('-')]
dt.datetime(year, month, day)
stop_loop = 1
except:
exp = input(exp_string)
# Get option price
V_string = 'Enter option price: '
V = input(V_string)
stop_loop = 0
while stop_loop == 0:
try:
V = float(V)
stop_loop = 1
except:
V = input(V_string)
# Get stock price
S_string = 'Enter the stock price: '
S = input(S_string)
stop_loop = 0
while stop_loop == 0:
try:
S = float(S)
stop_loop = 1
except:
S = input(S_string)
# Get strike price
K_string = 'Enter the strike price: '
K = input(K_string)
stop_loop = 0
while stop_loop == 0:
try:
K = float(K)
stop_loop = 1
except:
K = input(K_string)
# Get risk-free rate
r_string = 'Enter the risk free rate: '
r = input(r_string)
stop_loop = 0
while stop_loop == 0:
try:
r = float(r)
stop_loop = 1