-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathblspricer.py
1149 lines (947 loc) · 32.1 KB
/
blspricer.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
"""
Option pricing module for Risk Management research at the Scientific Computing group
at University of Waterloo
Developed by Luyu Wang
2015-2016
"""
from __future__ import division
import numpy as np
import numpy.random as npr
from math import log, sqrt, exp
from scipy import stats
##########################################################################################
# Random Number Generators
##########################################################################################
def gen_sn(M, I, anti_paths=False, mo_match=False):
''' Function to generate random numbers for simulation with variance reduction
from Y. Hilpisch, Python for Finance
Parameters
==========
M : int
number of time intervals for discretization
I : int
number of paths to be simulated
anti_paths : Boolean
use of antithetic variates
mo_match : Boolean
use of moment matching
'''
if anti_paths is True:
sn = npr.standard_normal((M + 1, I / 2))
sn = np.concatenate((sn, -sn), axis=1)
else:
sn = npr.standard_normal((M + 1, I))
if mo_match is True:
sn = (sn - sn.mean()) / sn.std()
return sn
def gen_sn2(D, I, anti_paths=True, mo_match=True):
''' Function to generate random numbers for simulation.
from Y. Hilpisch, Python for Finance
Modified by L. Wang for handling high dimensional data generation.
Parameters
==========
D : int
number of dimensions
I : int
number of paths to be simulated
anti_paths : Boolean
use of antithetic variates
mo_match : Boolean
use of moment matching
'''
import numpy as np
import numpy.random as npr
if anti_paths is True:
sn = npr.standard_normal((D, I / 2))
sn = np.concatenate((sn, -sn), axis=1)
else:
sn = npr.standard_normal((D, I))
if mo_match is True:
sn = (sn - sn.mean()) / sn.std()
return sn
def normcdfM(x):
''' Gives the normal cumulative density function probabilities
Author: Sivakumar Batthala
'''
from math import log, sqrt, exp, pi
a1 = 0.319381530; a2 = -0.356563782; a3 = 1.781477937; a4 = -1.821255978; a5 = 1.330274429
gamma = 0.2316419
k = 1./(1.+(gamma*x))
nprime = (1./sqrt(2.*pi)) * (exp(-(x**2.)/2.))
if (x >= 0.):
n = 1. - (nprime * (a1*k + a2*k**2. + a3*k**3. + a4*k**4. + a5*k**5.))
else:
n = 1. - normcdfM(-x)
return n
def bivnormcdf(a,b,rho):
''' Gives the bivariate normal distribution function probabilities
As given in Hull's textbook
Author: Sivakumar Batthala
'''
from math import log, sqrt, exp, pi
import numpy as np
if a <= 0. and b <= 0. and rho <= 0. :
aprime = a/sqrt(2.*(1.-rho**2.))
bprime = b/sqrt(2.*(1.-rho**2.))
A = np.array([0.3253030, 0.4211071, 0.1334425, 0.006374323])
B = np.array([0.1337764, 0.6243247, 1.3425378, 2.2626645])
t = 0.
for i in range(4):
for j in range(4):
x = B[i]
y = B[j]
t += A[i]*A[j]* exp(aprime*(2.*x - aprime) \
+ (bprime*(2.*y - bprime)) + (2.*rho * (x - aprime)*(y-bprime)))
p = (sqrt(1.-rho**2.)/pi) * t
elif a * b * rho <= 0. :
if a <= 0. and b >= 0. and rho >= 0. :
p = normcdfM(a) - bivnormcdf(a,-b,-rho)
elif a >= 0. and b <= 0. and rho >= 0. :
p = normcdfM(b) - bivnormcdf(-a,b,-rho)
elif a >= 0. and b >= 0. and rho <= 0. :
p = normcdfM(a) + normcdfM(b) - 1. + bivnormcdf(-a,-b,rho)
elif a*b*rho > 0. :
if a >= 0. :
asign = 1.
else:
asign = -1.
if b >= 0.:
bsign = 1.
else:
bsign = -1.
rho1 = (rho*a - b)*asign/(sqrt(a**2. - (2.*rho*a*b) + b**2.))
rho2 = (rho*b - a)*bsign/(sqrt(a**2. - (2.*rho*a*b) + b**2.))
delta = (1. - (asign*bsign))/4.
p = bivnormcdf(a,0,rho1) + bivnormcdf(b,0,rho2) - delta
return p
##########################################################################################
# Option priceing formulas
##########################################################################################
def blsprice(S0, K, r, T, sigma, optionType='call'):
''' Valuation of European option in BSM model Analytical formula.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
optionType : string
type of the option to be valued ('call', 'put')
Returns
=======
value : float
present value of the European option
'''
# assert type(S0) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d2 = (log(S0 / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
if optionType == 'call':
value = (S0 * stats.norm.cdf(d1, 0.0, 1.0) - K * exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0))
elif optionType == 'put':
value = (K * exp(-r * T) * stats.norm.cdf(-d2, 0.0, 1.0) - S0 * stats.norm.cdf(-d1, 0.0, 1.0))
return value
def blsprice2(S0, K, r, T, sigma):
''' Valuation of European option in BSM model Analytical formula.
'''
# assert type(S0) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d2 = (log(S0 / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
#if optionType == 'call':
C_value = (S0 * stats.norm.cdf(d1, 0.0, 1.0) - K * exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0))
#elif optionType == 'put':
P_value = (K * exp(-r * T) * stats.norm.cdf(-d2, 0.0, 1.0) - S0 * stats.norm.cdf(-d1, 0.0, 1.0))
return (C_value,P_value)
def test_blsprice():
C0 = blsprice(100.,110.,0.03,1.,0.5); P0 = blsprice(100.,110.,0.03,1.,0.5,'put')
print "Analytical: European call option (S0=100,K=110,r=0.03,T=1,sigma=0.5)"
print "[call=17.2031, put=23.9521] <= MATLAB blsprice"
print "[call=%7.4f, put=%7.4f] <= this python implementation" % (C0,P0)
assert abs(C0-17.2031) < 1e-4 and abs(P0-23.9521) < 1e-4, \
"Disagree from MATLAB results."
def blsprice_mcs(S0, K, r, T, sigma, optionType='call', M=1, I=10000):
''' Valuation of European options in Black-Scholes-Merton by Monte Carlo simulation
(of index level paths)
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
optionType : string
type of the option to be valued ('call', 'put')
M : integer
number of time steps
I : integer
number of risk-neutral paths
Returns
=======
value : float
estimated present value of European option
'''
# assert type(S0) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / M
# simulation of index level paths
S = np.zeros((M + 1, I))
S[0] = S0
sn = gen_sn(M, I, anti_paths=False, mo_match=False)
for t in range(1, M + 1):
S[t] = S[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * sn[t])
# case-based calculation of payoff
if optionType == 'call':
hT = np.maximum(S[-1] - K, 0)
elif optionType == 'put':
hT = np.maximum(K - S[-1], 0)
# calculation of MCS estimator
value = np.exp(-r * T) * 1 / I * np.sum(hT)
return value
def blsprice2_mcs(S0, K, r, T, sigma, M=1, I=10000):
''' Valuation of European options in Black-Scholes-Merton by Monte Carlo simulation
(of index level paths)
'''
# assert type(S0) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / M
# simulation of index level paths
S = np.zeros((M + 1, I))
S[0] = S0
sn = gen_sn(M, I, anti_paths=False, mo_match=False)
for t in range(1, M + 1):
S[t] = S[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * sn[t])
# case-based calculation of payoff
#if optionType == 'call':
C_hT = np.maximum(S[-1] - K, 0)
C_value = np.exp(-r * T) * 1 / I * np.sum(C_hT)
#elif optionType == 'put':
P_hT = np.maximum(K - S[-1], 0)
P_value = np.exp(-r * T) * 1 / I * np.sum(P_hT)
return (C_value,P_value)
def test_blsprice_mcs():
C0 = blsprice_mcs(100.,110.,0.03,1.,0.5); P0 = blsprice_mcs(100.,110.,0.03,1.,0.5,'put')
print "Monte Carlo: European call option (S0=100,K=110,r=0.03,T=1,sigma=0.5)"
print "[call=17.2031, put=23.9521] <= MATLAB blsprice"
print "[call=%7.4f, put=%7.4f] <= this python implementation" % (C0,P0)
assert abs(C0-17.2031) < 1 and abs(P0-23.9521) < 1, \
"Disagree from MATLAB results."
def dnOutPut(S0, K, r, T, sigma, Sb):
''' Valuation of European down-and-out barrier put option in BSM model.
Analytical formula.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
Returns
=======
value : float
present value of the European option
'''
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
a = (Sb / S0) ** (-1. + 2. * r / sigma **2)
b = (Sb / S0) ** (1. + 2. * r / sigma **2)
d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d2 = (log(S0 / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d3 = (log(S0 / Sb) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d4 = (log(S0 / Sb) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d5 = (log(S0 / Sb) - (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d6 = (log(S0 / Sb) - (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d7 = (log(S0 * K / Sb ** 2) - (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d8 = (log(S0 * K / Sb ** 2) - (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
value = K * exp(-r * T) * (stats.norm.cdf(d4, 0.0, 1.0) - stats.norm.cdf(d2, 0.0, 1.0) \
- a * (stats.norm.cdf(d7, 0.0, 1.0) - stats.norm.cdf(d5, 0.0, 1.0))) \
- S0 * (stats.norm.cdf(d3, 0.0, 1.0) - stats.norm.cdf(d1, 0.0, 1.0) \
- b * (stats.norm.cdf(d8, 0.0, 1.0) - stats.norm.cdf(d6, 0.0, 1.0)))
value = value.clip(0)
return value
def dnOutCall(S0, K, r, T, sigma, Sb):
''' Valuation of European down-and-out barrier call option in BSM model.
Analytical formula.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
Returns
=======
value : float
present value of the European option
'''
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
a = (Sb / S0) ** (-1. + 2. * r / sigma **2)
b = (Sb / S0) ** (1. + 2. * r / sigma **2)
d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d2 = (log(S0 / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d3 = (log(S0 / Sb) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d4 = (log(S0 / Sb) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d5 = (log(S0 / Sb) - (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d6 = (log(S0 / Sb) - (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d7 = (log(S0 * K / Sb ** 2) - (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d8 = (log(S0 * K / Sb ** 2) - (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
if K >= Sb:
value = S0*(stats.norm.cdf(d1,0.,1.) - b*(1.-stats.norm.cdf(d8,0.,1.)))\
- K*exp(-r*T)*(stats.norm.cdf(d2,0.,1.) - a*(1.-stats.norm.cdf(d7,0.,1.)))
else:
value = S0*(stats.norm.cdf(d3,0.,1.) - b*(1.-stats.norm.cdf(d6,0.,1.)))\
- K*exp(-r*T)*(stats.norm.cdf(d4,0.,1.) - a*(1.-stats.norm.cdf(d5,0.,1.)))
value = value.clip(0)
return value
def test_dnOutPut():
P0 = dnOutPut(S0=100.,K=101.,r=0.03,T=1./12.,sigma=0.2,Sb=91.)
print "Analytical: European down-out put option (S0=100,K=101,r=0.03,T=1/12,sigma=0.2,Sb=91)"
print "1.7088 <= MATLAB blsprice"
print "%6.4f <= this python implementation" % P0
assert abs(P0-1.7088) < 1e-4, "Disagree from MATLAB results."
def rear_end_dnOutPut(S, K, r, T, sig, H, tau, q):
''' Valuation of partial end European down-and-out barrier put option in BSM model.
Analytical formula.
C. H. Hui, Time-Dependent Barrier Option Values, Journal of Futures Markets, 17(6), 776-688 (1997)
implemented by L. Wang
Tested.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
tau : float
barrier starting time
Returns
=======
value : float
present value of the Barrier option
'''
from math import log, sqrt, exp
a = lambda t: (log(S/K) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
a1 = lambda t: (log(S/K) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
b = lambda t: (log(S/H) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
b1 = lambda t: (log(S/H) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
c = lambda t: (log(H/S) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
c1 = lambda t: (log(H/S) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
d = lambda t: (log(H**2./(S*K)) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
d1 = lambda t: (log(H**2./(S*K)) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
rho = sqrt(tau/T)
k1 = 2.*(r-q)/(sig**2.)
P2do = K*exp(-r*T) * (bivnormcdf(b(tau),-a(T),-rho) - bivnormcdf(b(tau),-b(T),-rho)) \
- S*exp(-q*T) * (bivnormcdf(b1(tau),-a1(T),-rho) - bivnormcdf(b1(tau),-b1(T),-rho)) \
- (H/S)**(k1-1.) * K * exp(-r*T) * (bivnormcdf(-c(tau),-d(T),rho) - bivnormcdf(-c(tau),-c(T),rho)) \
+ (H/S)**(k1+1.) * S * exp(-q*T) * (bivnormcdf(-c1(tau),-d1(T),rho) - bivnormcdf(-c1(tau),-c1(T),rho))
return P2do
def rear_end_dnOutCall(S, K, r, T, sig, H, tau, q):
''' Valuation of partial end European down-and-out barrier call option in BSM model.
Analytical formula.
C. H. Hui, Time-Dependent Barrier Option Values, Journal of Futures Markets, 17(6), 776-688 (1997)
implemented by L. Wang
Tested.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
tau : float
barrier starting time
Returns
=======
value : float
present value of the Barrier option
'''
from math import log, sqrt, exp
a = lambda t: (log(S/K) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
a1 = lambda t: (log(S/K) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
b = lambda t: (log(S/H) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
b1 = lambda t: (log(S/H) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
c = lambda t: (log(H/S) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
c1 = lambda t: (log(H/S) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
d = lambda t: (log(H**2./(S*K)) + (r-q)*t) / (sig*sqrt(t)) - sig*sqrt(t)/2.
d1 = lambda t: (log(H**2./(S*K)) + (r-q)*t) / (sig*sqrt(t)) + sig*sqrt(t)/2.
rho = sqrt(tau/T)
k1 = 2.*(r-q)/(sig**2.)
C2do = S*exp(-q*T) * bivnormcdf(b1(tau),a1(T),rho) - K*exp(-r*T) * bivnormcdf(b(tau),a(T),rho) \
- (H/S)**(k1+1.) * S * exp(-q*T) * bivnormcdf(-c1(tau),d1(T),-rho) \
+ (H/S)**(k1-1.) * K * exp(-r*T) * bivnormcdf(-c(tau),d(T),-rho)
return C2do
##########################################################################################
# Option priceing: Monte Carlo
##########################################################################################
def dnOutPut_mcs(S0, K, r, T, sigma, Sb, M=50, I=10000):
''' Valuation of European down-and-out barrier put option in BSM model.
Monte Carlo simulations.
by L. Wang
Tested: has hitting error, resulting a bias making the option price higher than true price.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
Y = np.zeros(M+1); Y[:] = np.log(S0)
multi_a = (r - 0.5 * sigma ** 2) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(0, I):
for i in range(0, M):
sn = npr.standard_normal()
Y[i+1] = Y[i] + multi_a + multi_b * sn
if np.amin(Y) > np.log(Sb):
value[j] = np.maximum(K - np.exp(Y[-1]), 0)
else:
value[j] = 0.
value = np.exp(-r * T) * np.mean(value)
return value
def dnOutCall_mcs(S0, K, r, T, sigma, Sb, M=50, I=10000):
''' Valuation of European down-and-out barrier call option in BSM model.
Monte Carlo simulations.
by L. Wang
Tested: has hitting error, resulting a bias making the option price higher than true price.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
Y = np.zeros(M+1); Y[:] = np.log(S0)
multi_a = (r - 0.5 * sigma ** 2) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(0, I):
for i in range(0, M):
sn = npr.standard_normal()
Y[i+1] = Y[i] + multi_a + multi_b * sn
if np.amin(Y) > np.log(Sb):
value[j] = np.maximum(np.exp(Y[-1]) - K, 0)
else:
value[j] = 0.
value = np.exp(-r * T) * np.mean(value)
return value
def dnOutPut_nmcs(S0, K, r, T, sigma, Sb, M=50, I=10000):
''' Valuation of European down-and-out barrier put option in BSM model.
New Monte Carlo simulations.
from CS676 Asst 1, Winter 2015
by L. Wang
Tested: using Brownian bidge to compute the hitting probability. Lower bias is achieved.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
S = np.zeros(M+1); S[:] = S0
P = np.zeros(M)
multi_a = (r - 0.5 * sigma ** 2.) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(I):
flag = False # Brownin bridge prob hitting flag
for i in range(M):
sn = npr.standard_normal()
S[i+1] = S[i] * np.exp(multi_a + multi_b * sn)
#P[i] = -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. )
P[i] = np.exp( -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. ) )
#print P[i]
if P[i] >= npr.uniform():
flag = True
if np.amin(S) > Sb and flag == False:
value[j] = np.maximum(K - S[-1], 0)
else:
value[j] = 0.
value = np.exp(-r * T) * np.mean(value)
return value
def dnOutCall_nmcs(S0, K, r, T, sigma, Sb, M=100, I=1000):
''' Valuation of European down-and-out barrier put option in BSM model.
New Monte Carlo simulations.
from CS676 Asst 1, Winter 2015
by L. Wang
Tested: using Brownian bidge to compute the hitting probability. Lower bias is achieved.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
S = np.zeros(M+1); S[:] = S0
P = np.zeros(M)
multi_a = (r - 0.5 * sigma ** 2.) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(I):
flag = False # Brownin bridge prob hitting flag
for i in range(M):
sn = npr.standard_normal()
S[i+1] = S[i] * np.exp(multi_a + multi_b * sn)
#P[i] = -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. )
P[i] = np.exp( -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. ) )
#print P[i]
if P[i] >= npr.uniform():
flag = True
if np.amin(S) > Sb and flag == False:
value[j] = np.maximum(S[-1] - K, 0)
else:
value[j] = 0.
value = np.exp(-r * T) * np.mean(value)
return value
def test_dnOutPut_mcs():
P0 = dnOutPut_mcs(S0=100.,K=101.,r=0.03,T=1./12.,sigma=0.2,Sb=91.)
print "Monte Carlo: European down-out put option (S0=100,K=101,r=0.03,T=1/12,sigma=0.2,Sb=91)"
print "1.7088 <= MATLAB blsprice"
print "%6.4f <= this python implementation" % P0
assert abs(P0-1.7088) < 0.5, "Disagree from MATLAB results."
def partial_end_dnOutPut_mcs(S0, K, r, T, sigma, Sb, tau, M=1000, I=10000):
''' Valuation of partial end European down-and-out barrier put option in BSM model.
Monte Carlo simulations.
implemented by L. Wang
Tested.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
tau : float
barrier starting time
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
import math
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
tau_idx = math.ceil(tau*float(M)/T)
Y = np.zeros(M+1); Y[:] = np.log(S0)
multi_a = (r - 0.5 * sigma ** 2) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(0, I):
for i in range(0, M):
sn = npr.standard_normal()
Y[i+1] = Y[i] + multi_a + multi_b * sn
if np.amin(Y[tau_idx:]) > np.log(Sb):
value[j] = np.maximum(K - np.exp(Y[-1]), 0)
value = np.exp(-r * T) * np.mean(value)
return value
def partial_end_dnOutCall_mcs(S0, K, r, T, sigma, Sb, tau, M=1000, I=10000):
''' Valuation of partial end European down-and-out barrier call option in BSM model.
Monte Carlo simulations.
implemented by L. Wang
Tested.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
tau : float
barrier starting time
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
import math
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
tau_idx = math.ceil(tau*float(M)/T)
Y = np.zeros(M+1); Y[:] = np.log(S0)
multi_a = (r - 0.5 * sigma ** 2) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(0, I):
for i in range(0, M):
sn = npr.standard_normal()
Y[i+1] = Y[i] + multi_a + multi_b * sn
if np.amin(Y[tau_idx:]) > np.log(Sb):
value[j] = np.maximum(np.exp(Y[-1]) - K, 0)
value = np.exp(-r * T) * np.mean(value)
return value
def partial_end_dnOutPut_nmcs(S0, K, r, T, sigma, Sb, tau, M=1000, I=10000):
''' Valuation of partial end European down-and-out barrier put option in BSM model.
New Monte Carlo simulations.
implemented by L. Wang
Tested. Lower-bias.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
tau : float
barrier starting time
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
import math
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
tau_idx = math.ceil(tau*float(M)/T)
S = np.zeros(M+1); S[:] = S0
P = np.zeros(M)
multi_a = (r - 0.5 * sigma ** 2.) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(I):
flag = False # Brownin bridge prob hitting flag
for i in range(M):
sn = npr.standard_normal()
S[i+1] = S[i] * np.exp(multi_a + multi_b * sn)
#P[i] = -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. )
P[i] = np.exp( -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. ) )
#print P[i]
if P[i] >= npr.uniform() and i>= tau_idx:
flag = True
if np.amin(S[tau_idx:]) > Sb and flag == False:
value[j] = np.maximum(K - S[-1], 0)
else:
value[j] = 0.
value = np.exp(-r * T) * np.mean(value)
return value
def partial_end_dnOutCall_nmcs(S0, K, r, T, sigma, Sb, tau, M=1000, I=10000):
''' Valuation of partial end European down-and-out barrier call option in BSM model.
New Monte Carlo simulations.
implemented by L. Wang
Tested. Lower-bias.
Parameters
==========
S0 : float
initial stock/index level
K : float
strike price
T : float
maturity data (in year fractions)
r : float
constant risk-free short rate
sigma : float
volatility factor in diffusion term
Sb : float
barrirer level
tau : float
barrier starting time
M : int
number of time steps
I : int
number of Monte Carlo iterations
Returns
=======
value : float
present value of the Barrier option
'''
import math
# assert type(S0) is float and type(Sb) is float and type(K) is float and type(r) is float and type(T) is float and type(sigma) is float, "Unrecongnized input, check type"
dt = T / float(M)
tau_idx = math.ceil(tau*float(M)/T)
S = np.zeros(M+1); S[:] = S0
P = np.zeros(M)
multi_a = (r - 0.5 * sigma ** 2.) * dt; multi_b = sigma * np.sqrt(dt)
value = np.zeros(I)
for j in range(I):
flag = False # Brownin bridge prob hitting flag
for i in range(M):
sn = npr.standard_normal()
S[i+1] = S[i] * np.exp(multi_a + multi_b * sn)
#P[i] = -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. )
P[i] = np.exp( -2. * (Sb-S[i]) * (Sb-S[i+1]) / ( S[i]**2. * multi_b**2. ) )
#print P[i]
if P[i] >= npr.uniform() and i>= tau_idx:
flag = True
if np.amin(S[tau_idx:]) > Sb and flag == False:
value[j] = np.maximum(S[-1] - K, 0)
else:
value[j] = 0.
value = np.exp(-r * T) * np.mean(value)
return value
##########################################################################################
# Other functions
##########################################################################################
def nestedSimulationEX1(Ndata, K1=100, tn=50, n_repeat=1, sampling='mc'):
''' Generation of nested simulation samples at the time horizon.
Single asset example in Broadie et al (2014)
by L. Wang
Tested.
Parameters
==========
Ndata : integer
no. of training samples
K1 : integer
no. of inner loops
tn : integer
no. of time steps in between t = \tau and T
n_repeat : integer
no. of iterations for computing expectations
sigma : float
volatility factor in diffusion term
Returns
=======
Stau : Ndata x 1 nparray
realizations of underlying price at t = \tau
Loss : Ndata x n_repeat nparray
portfolio loss of corresponding Stau
t_prep : float
time spent in this procedure
'''
import time
#from doe_lhs import lhs
from scipy.stats.distributions import norm
# --- Parameters ---
S0 = 100.; mu = 0.08; sigma = 0.2
rfr = 0.03; T = 1./12.; tau = 1./52.
K = np.array([101., 110., 114.5])
H = np.array([91., 100., 104.5])
pos = np.array([1., 1., -1.])
n = len(K) # number of options
t0 = time.time() # timer starts
# --- portfolio price @ t = 0 ---
V0 = np.zeros(n)