-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMLMC_RSCAM.py
1920 lines (1658 loc) · 77.5 KB
/
MLMC_RSCAM.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
"""
MLMC_RSCAM
Multilevel Monte Carlo Implementation for RSCAM Group 1
Luke Shaw, Olena Balan, Isabell Linde, Chantal Kool, Josh Mckeown
_______________________________________________________
Functions: Euro_payoff, Asian_payoff, Lookback_payoff, Digital_payoff, and anti_Euro_payoff payoffs.
(diffusion/JD)_path(_min/_avg) for diffusion and jump diffusion, coarse/fine final, avg, min asset prices.
(diffusion/JD)_asset_plot plotting functions for diffusion and jump diffusion asset prices.
Giles_plot plotting functions for mlmc variance/mean, samples per level/complexity and brownian_plot for discretised Brownian motion plots.
Use inspect.getmembers(mlmc_RSCAM,inspect.isroutine) to get full list.
Classes: Option, JumpDiffusion_Option, Diffusion_Option, Merton_Option, GBM_Option, MyOption.
With specific Euro_GBM/Euro_Merton, Lookback_GBM/Lookback_Merton, Asian_GBM/Asian_Merton,
Digital_GBM/Digital_Merton implementations for Merton and GBM models.
Use inspect.getmembers(mlmc_RSCAM,inspect.isclass) to get full list.
________________________________________________________
Example usage:
import MLMC_RSCAM as multi
opt = multi.Euro_GBM(X0=125,K=105,r=0.02,sig=0.5)
sums,N=opt.mlmc(eps=0.01)
print(sum(sums[0,:]/N),opt.BS()) #Compare BS price with mlmc-calculated price
eps=[0.005,0.1,0.2,0.25,0.3]
fig,ax=plt.subplots(2,2,figsize=(30,30))
markers=['o','s','x','d']
multi.Giles_plot(opt,eps,label='European GBM ', markers=markers,fig=fig,Nsamples=10**3) #Plot mean/variance/numbr of levels/complexity plot
opt.asset_plot(L=4,M=4) #Plot asset price on two discretisation levels
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import matplotlib.ticker as ticker
from scipy.special import factorial
from matplotlib.legend import Legend
import weakref
class WeakMethod:
"""
Taken from:
https://stackoverflow.com/questions/55413060/python-passing-functions-as-arguments-to-initialize-the-methods-of-an-object-p
Need to use for passing functions with self as argument in constructor.
"""
def __init__(self, func, instance):
self.func = func
self.instance_ref = weakref.ref(instance)
self.__wrapped__ = func # this makes things like `inspect.signature` work
def __call__(self, *args, **kwargs):
instance = self.instance_ref()
return self.func(instance, *args, **kwargs)
def __repr__(self):
cls_name = type(self).__name__
return '{}({!r}, {!r})'.format(cls_name, self.func, self.instance_ref())
#######################################################################################################################
##General Payoff Funcs
def EA_payoff(self,N_loop,l,M):
"""
Payoff function for European Call or Asian Call option. Depends on what self.path returns.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pf,Pc (numpy.array) : payoff vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
r=self.r
K=self.K
T=self.T
Xf,Xc=self.path(N_loop,l,M)
#Calculate payoffs etc.
Pf=np.maximum(0,Xf-K)
Pf=np.exp(-r*T)*Pf
if l==0:
return Pf,Xc #Just ignore Pc=Xc
else:
Pc=np.maximum(0,Xc-K)
Pc=np.exp(-r*T)*Pc #Payoff at coarse level
return Pf,Pc
def Lookback_payoff(self,N_loop,l,M):
"""
Payoff function for Lookback Call option.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pf,Pc (numpy.array) : payoff vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
r=self.r;T=self.T;beta=self.beta
dt=T/M**l
Xf,Mf,Xc,Mc=self.path(N_loop,l,M)
#Calculate payoffs etc.
Pf=Xf - Mf*(1-self.beta*self.sig*np.sqrt(dt))
Pf=np.exp(-r*T)*Pf #Payoff at fine level
if l==0:
return Pf,Xc #Just ignore Pc
else:
Pc=Xc - Mc*(1-self.beta*self.sig*np.sqrt(M*dt))
Pc=np.exp(-r*T)*Pc #Payoff at coarse level
return Pf,Pc
def Digital_payoff(self,N_loop,l,M):
"""
Payoff function for Digital Call option.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pf,Pc (numpy.array) : payoff vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
r=self.r
T=self.T
K=self.K
Xf,Xc=self.path(N_loop,l,M)
#Calculate payoffs etc.
Pf=np.exp(-r*T)*K*(Xf>K).astype(np.int_)
if l==0:
return Pf,Xc #Just ignore Pc=Xc
else:
Pc=np.exp(-r*T)*K*(Xc>K).astype(np.int_) #Payoff at coarse level
return Pf,Pc
def Amer_payoff(self,N_loop,l,M):
"""
Payoff function for American Put option. self.path should return Xf,Xc - N_loop-by-3 arrays.
For a non-dividend-paying asset, an American Call will have the same value as a Euro Call.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pf,Pc (numpy.array) : payoff vectors for N_loop sample paths (Pc=0 if l==0)
"""
K=self.K;T=self.T;r=self.r
Xf,Xc=self.path(N_loop,l,M)
Pf = Xf[:,2] + Xf[:,1]*np.maximum(K-Xf[:,0],0)*np.exp(-r*T)
if l == 0:
return Pf,0 #ignore Pc
else:
Pc = Xc[:,2] + Xc[:,1]*np.maximum(K-Xc[:,0],0)*np.exp(-r*T)
return Pf,Pc
#######################################################################################################################
#Antithetic funcs
def diffusion_anti_path(self,N_loop,l,M):
"""
Antithetic path function for diffusion sde.
In usage should be called by anti_payoff as self.anti_path. Calls self.sde.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Xf,Xa,Xc (numpy.array) : final asset price vectors for N_loop sample paths (Xc=X0 if l==0)
"""
r=self.r;X0=self.X0;T=self.T;K=self.K;sig=self.sig
sde=self.sde
if M%2!=0:
raise Exception("Cannot calculate antithetic estimator for odd coarseness factor M - please use even M")
Nsteps = M**l #Number of fine steps
dt = T / Nsteps
sqrt_dt = np.sqrt(dt)
# Initialise fine, coarse, antithetic asset prices;
Xf = X0 * np.ones(N_loop)
Xc = X0 * np.ones(N_loop)
Xa = X0 * np.ones(N_loop)
# coarse Brownian increment (BI)
dWc = np.zeros(N_loop)
# this loop generates brownian increments and calculates the estimators
for j in range(2, Nsteps+1, 2): #If l==0, Nsteps=1 and loop is skipped
dWf_odd = np.random.randn(N_loop) * sqrt_dt
dWf_even = np.random.randn(N_loop) * sqrt_dt
# odd step
t_=j*dt
Xf += sde(Xf,dt,t_,dWf_odd)
Xa += sde(Xa,dt,t_,dWf_even)
t_+=dt
# even step
Xf += sde(Xf,dt,t_,dWf_even)
Xa += sde(Xa,dt,t_,dWf_odd)
dWc += dWf_odd + dWf_even
if j%M==0:
Xc += sde(Xc,M*dt,j*dt,dWc) #...Develop coarse path
dWc = np.zeros(N_loop) #...Re-initialise coarse BI to 0
if l == 0: #Loop has been skipped
Xf += sde(Xf,dt,0,np.random.randn(N_loop)*sqrt_dt)
return Xf,Xf,Xc #Just ignore Xa=Xf,Xc=X0
else:
return Xf,Xa,Xc
def diffusion_anti_path_avg(self,N_loop,l,M):
"""
Antithetic path function for diffusion sde. Calculates antithetic path averages.
In usage should be called by anti_payoff as self.anti_path. Calls self.sde.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Af/T,Aa/T,Ac/T (numpy.array) : final average asset price vectors for N_loop sample paths (Ac=X0 if l==0)
"""
r=self.r;X0=self.X0;T=self.T;K=self.K;sig=self.sig
sde=self.sde
if M%2!=0:
raise Exception("Cannot calculate antithetic estimator for odd coarseness factor M - please use even M")
Nsteps = M**l #Number of fine steps
dt = T / Nsteps
sqrt_dt = np.sqrt(dt)
# Initialise fine, coarse, antithetic asset prices;
Xf = X0 * np.ones(N_loop)
Xc = X0 * np.ones(N_loop)
Xa = X0 * np.ones(N_loop)
Af=0.5*dt*Xf
Aa=0.5*dt*Xa
Ac=0.5*M*dt*Xc
# coarse Brownian increment (BI)
dWc = np.zeros(N_loop)
# this loop generates brownian increments and calculates the estimators
for j in range(2, Nsteps+1, 2): #If l==0, Nsteps=1 and loop is skipped
dWf_odd = np.random.randn(N_loop) * sqrt_dt
dWf_even = np.random.randn(N_loop) * sqrt_dt
# odd step
t_=j*dt
Xf += sde(Xf,dt,t_,dWf_odd)
Xa += sde(Xa,dt,t_,dWf_even)
Af+=dt*Xf #fine average
Aa+=dt*Xa #antithetic average
t_+=dt
# even step
Xf += sde(Xf,dt,t_,dWf_even)
Xa += sde(Xa,dt,t_,dWf_odd)
Af+=dt*Xf #fine average
Aa+=dt*Xa #antithetic average
dWc += dWf_odd + dWf_even
if j%M==0:
Xc += sde(Xc,M*dt,j*dt,dWc) #...Develop coarse path
Ac+=dt*M*Xc #coarse average
dWc = np.zeros(N_loop) #...Re-initialise coarse BI to 0
if l == 0: #Loop has been skipped
Xf += sde(Xf,dt,0,np.random.randn(N_loop)*sqrt_dt)
Af+=0.5*dt*Xf
return Af/T,Af/T,Xc #Just ignore Xa=Xf,Xc=X0
else: #Correct for not halving the final X value
Af-=0.5*Xf*dt
Aa-=0.5*Xa*dt
Ac-=0.5*Xc*(M*dt)
return Af/T,Aa/T,Ac/T
def anti_EA_payoff(self,N_loop,l,M):
"""
Antithetic payoff function for European Call or Asian Call option. Depends on what self.path returns.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pf,Pc (numpy.array) : payoff vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
r=self.r;K=self.K;T=self.T
Xf,Xa,Xc=self.anti_path(N_loop,l,M) #call anti_path function (returns Xf,Xa,Xc if Euro, Af/T,Aa/T,Ac/T if Asian)
#Calculate payoffs etc.
Pf=np.maximum(0,Xf-K)
Pf=np.exp(-r*T)*Pf #Payoff at fine level
if l==0:
return Pf,Xc #Just ignore Pc=Xc
else:
Pa=np.maximum(0,Xa-K)
Pa=np.exp(-r*T)*Pa #Antithetic payoff
Pc=np.maximum(0,Xc-K)
Pc=np.exp(-r*T)*Pc #Payoff at coarse level
return 0.5 * (Pf + Pa), Pc
#######################################################################################################################
##Path funcs
def diffusion_path(self,N_loop,l,M):
"""
The path function for Euler-Maruyama diffusion, which calculates final asset prices X(T).
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Xf,Xc (numpy.array) : final asset price vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
T=self.T;X0=self.X0;sde=self.sde
Nsteps=M**l
dt=T/Nsteps
sqrt_dt=np.sqrt(dt)
#Initialise fine, coarse asset prices; coarse Brownian increment (BI)
Xf=X0*np.ones(N_loop)
Xc=X0*np.ones(N_loop)
dWc=np.zeros(N_loop)
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
t_=(j-1)*dt #Current time to simulate from in Ito calculus
dWf=np.random.randn(N_loop)*sqrt_dt
dWc=dWc+dWf #Keep adding to coarse BI every loop until j is integer multiple of M
Xf+=sde(Xf,dt,t_,dWf)
if j%M==0: #if j is integer multiple of M...
Xc+=sde(Xc,M*dt,t_,dWc) #...Develop coarse path
dWc=np.zeros(N_loop) #...Re-initialise coarse BI to 0
return Xf,Xc
def diffusion_path_avg(self,N_loop,l,M):
"""
The path function for Euler-Maruyama diffusion, which calculates final average asset price avg(X).
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Af/T,Ac/T (numpy.array) : final average asset price vectors for N_loop sample paths (Ac=Xc=X0 if l==0)
"""
T=self.T;X0=self.X0
sde=self.sde
Nsteps=M**l;dt=T/Nsteps;sqrt_dt=np.sqrt(dt)
#Initialise fine, coarse asset prices; coarse Brownian increment (BI)
Xf=X0*np.ones(N_loop)
Xc=X0*np.ones(N_loop)
Af=0.5*dt*Xf
Ac=0.5*M*dt*Xc
dWc=np.zeros(N_loop)
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
t_=(j-1)*dt #Current time to simulate from in Ito calculus
dWf=np.random.randn(N_loop)*sqrt_dt
dWc=dWc+dWf #Keep adding to coarse BI every loop until j is integer multiple of M
Xf+=sde(Xf,dt,t_,dWf)
Af+=Xf*dt
if j%M==0: #if j is integer multiple of M...
Xc+=sde(Xc,M*dt,t_,dWc) #...Develop coarse path
Ac+=Xc*M*dt
dWc=np.zeros(N_loop) #...Re-initialise coarse BI to 0
Af-=0.5*Xf*dt
Ac-=0.5*Xc*M*dt
return Af/T,Ac/T
def diffusion_path_min(self,N_loop,l,M):
"""
The path function for Lookback Call Option with Euler-Maruyama diffusion, which calculates final asset prices and
minima.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Xf,Mf,Xc,Mc (numpy.array) : final asset price vectors Xf,Xc and minima Mf,Mc for N_loop sample paths (Xc=Mc=X0 if
l==0)
"""
T=self.T;X0=self.X0
sde=self.sde
Nsteps=M**l
dt=T/Nsteps
sqrt_dt=np.sqrt(dt)
#Initialise fine, coarse asset prices; coarse Brownian increment (BI)
Xf=X0*np.ones(N_loop)
Xc=X0*np.ones(N_loop)
Mf=X0*np.ones(N_loop)
Mc=X0*np.ones(N_loop)
dWc=np.zeros(N_loop)
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
t_=(j-1)*dt #Current time to simulate from in Ito calculus
dWf=np.random.randn(N_loop)*sqrt_dt
dWc=dWc+dWf #Keep adding to coarse BI every loop until j is integer multiple of M
Xf+=sde(Xf,dt,t_,dWf)
Mf=np.minimum(Xf,Mf)
if j%M==0: #if j is integer multiple of M...
Xc+=sde(Xc,M*dt,t_,dWc) #...Develop coarse path
Mc=np.minimum(Xc,Mc)
dWc=np.zeros(N_loop) #...Re-initialise coarse BI to 0
return Xf,Mf,Xc,Mc
def JD_path(self,N_loop,l,M):
"""
The path function for Euler-Maruyama JD, which calculates final asset price X(T).
Parameters:
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Xf,Xc (numpy.array) : final asset price vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
lam=self.lam;X0=self.X0;T=self.T;
Xf=np.zeros(N_loop)
Xc=np.zeros(N_loop)
num=0
Nsteps=M**l
sde=self.sde
jumpsize=self.jumpsize
jumptime=self.jumptime
while num<N_loop:
#Initialise asset price and time
dWc=0;tau=0;tf=0;tc=0;dtc=0
Sf=X0;Sc=X0;
##Algorithm Start
tau+=jumptime(scale=1/lam)
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
tn=j*T/Nsteps #Fine timestepping right boundary
while tau<tn: #If jump is before right boundary...
dt=tau-tf #Adaptive step size is from last jump or left fine timestep
dtc+=dt #Coarse timestep increments
dWf=np.random.randn()*np.sqrt(dt) #Brownian motion for adaptive time step
dWc+=dWf #Increment coarse BI
dJ=np.exp(jumpsize())-1 #Generate jump
#Develop fine path
Sf+=sde(Sf,dt,tf,dWf,dJ)
#Develop coarse path
Sc+=sde(Sc,dtc,tc,dWc,dJ)
dWc=0 #Reset coarse BI
dtc=0 #Reset coarse timestep
tf=tau #Both fine and coarse paths now at t_=latest jump time
tc=tau
tau+=jumptime(scale=1/lam) #Next jump time
#Next jump time is after current right fine timestep
dt=tn-tf #Adaptive time step is time from recent jump or left fine time up to right fine time
dtc+=dt #Increment coarse timestep
dWf=np.random.randn()*np.sqrt(dt) #Fine BI for adaptive timestep
dWc+=dWf #Increment coarse BI
Sf+=sde(Sf,dt,tf,dWf) #Develope fine timestep
tf=tn #Fine path now at j*T/Nsteps, set as left boundary
if j%M==0: #If reached coarse timepoint, then bring coarse path up to this point
Sc+=sde(Sc,dtc,tc,dWc)#...Develop coarse path
tc=tn #Coarse path now at j*T/Nsteps
dtc=0
dWc=0 #...Re-initialise coarse BI to 0
Xf[num]=Sf
Xc[num]=Sc
num+=1 #One more simulation down
return Xf,Xc
def JD_path_avg(self,N_loop,l,M):
"""
The path function for Euler-Maruyama JD, which calculates average asset price over path, avg(X).
Parameters:
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Af/T,Ac/T (numpy.array) : final average asset price vectors for N_loop sample paths (Ac=Xc=X0 if l==0)
"""
lam=self.lam;X0=self.X0;T=self.T;
Af=np.zeros(N_loop)
Ac=np.zeros(N_loop)
num=0
Nsteps=M**l
sde=self.sde
jumpsize=self.jumpsize
jumptime=self.jumptime
while num<N_loop:
#Initialise asset price and time
dWc=0;tau=0;tf=0;tc=0;dtc=0
Sf=X0;Sc=X0;
avg_f=0;avg_c=0
##Algorithm Start
tau+=jumptime(scale=1/lam)
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
tn=j*T/Nsteps #Fine timestepping right boundary
while tau<tn: #If jump is before right boundary...
dt=tau-tf #Adaptive step size is from last jump or left fine timestep
dtc+=dt #Coarse timestep increments
dWf=np.random.randn()*np.sqrt(dt) #Brownian motion for adaptive time step
dWc+=dWf #Increment coarse BI
dJ=np.exp(jumpsize())-1 #Generate jump
avg_f+=0.5*dt*Sf #S_n
Sf+=sde(Sf,dt,tf,dWf) #Develop fine path
avg_f+=0.5*dt*Sf #S-_n+1
Sf+=Sf*dJ
avg_c+=0.5*dtc*Sc #S_n
Sc+=sde(Sc,dtc,tc,dWc) #Develop coarse path
avg_c+=0.5*dtc*Sc #S-_n+1
Sc+=Sc*dJ
dWc=0 #Reset coarse BI
dtc=0 #Reset coarse timestep
tf=tau #Both fine and coarse paths now at t_=latest jump time
tc=tau
tau+=jumptime(scale=1/lam) #Next jump time
#Next jump time is after current right fine timestep
dt=tn-tf #Adaptive time step is time from recent jump or left fine time up to right fine time
dtc+=dt #Increment coarse timestep
dWf=np.random.randn()*np.sqrt(dt) #Fine BI for adaptive timestep
dWc+=dWf #Increment coarse BI
avg_f+=0.5*dt*Sf #S_n
Sf+=sde(Sf,dt,tf,dWf) #Develope fine timestep
avg_f+=0.5*dt*Sf #S-_n+1
tf=tn #Fine path now at j*T/Nsteps, set as left boundary
if j%M==0: #If reached coarse timepoint, then bring coarse path up to this point
avg_c+=0.5*dtc*Sc #S_n
Sc+=sde(Sc,dtc,tc,dWc)#...Develop coarse path
avg_c+=0.5*dtc*Sc #S-_n+1
tc=tn #Coarse path now at j*T/Nsteps
dtc=0
dWc=0 #...Re-initialise coarse BI to 0
Af[num]=avg_f
Ac[num]=avg_c
num+=1 #One more simulation down
return Af/T,Ac/T
def JD_path_min(self,N_loop,l,M):
"""
The path function for Euler-Maruyama JD, which calculates final asset prices Xf,Xc and minima Mf,Mc.
Parameters:
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Xf,Mf,Xc,Mc (numpy.array) : final asset price vectors Xf,Xc and minima Mf,Mc for N_loop sample paths (Xc=Mc=X0 if l==0)
"""
lam=self.lam;X0=self.X0;T=self.T;
Xf=np.zeros(N_loop)
Xc=np.zeros(N_loop)
Mf=np.zeros(N_loop)
Mc=np.zeros(N_loop)
num=0
Nsteps=M**l
sde=self.sde
jumpsize=self.jumpsize
jumptime=self.jumptime
while num<N_loop:
#Initialise asset price and time
dWc=0;tau=0;tf=0;tc=0;dtc=0
Sf=X0;Sc=X0;
##Algorithm Start
tau+=jumptime(scale=1/lam)
mf=X0
mc=X0
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
tn=j*T/Nsteps #Fine timestepping right boundary
while tau<tn: #If jump is before right boundary...
dt=tau-tf #Adaptive step size is from last jump or left fine timestep
dtc+=dt #Coarse timestep increments
dWf=np.random.randn()*np.sqrt(dt) #Brownian motion for adaptive time step
dWc+=dWf #Increment coarse BI
dJ=np.exp(jumpsize())-1 #Generate jump
#Develop fine path
Sf+=sde(Sf,dt,tf,dWf,dJ)
#Develop coarse path
Sc+=sde(Sc,dtc,tc,dWc,dJ)
#Update minima
mf=min(mf,Sf)
mc=min(mc,Sc)
dWc=0 #Reset coarse BI
dtc=0 #Reset coarse timestep
tf=tau #Both fine and coarse paths now at t_=latest jump time
tc=tau
tau+=jumptime(scale=1/lam) #Next jump time
#Next jump time is after current right fine timestep
dt=tn-tf #Adaptive time step is time from recent jump or left fine time up to right fine time
dtc+=dt #Increment coarse timestep
dWf=np.random.randn()*np.sqrt(dt) #Fine BI for adaptive timestep
dWc+=dWf #Increment coarse BI
Sf+=sde(Sf,dt,tf,dWf) #Develope fine timestep
tf=tn #Fine path now at j*T/Nsteps, set as left boundary
mf=min(mf,Sf) #Update minimum
if j%M==0: #If reached coarse timepoint, then bring coarse path up to this point
Sc+=sde(Sc,dtc,tc,dWc)#...Develop coarse path
mc=min(mc,Sc) #Update minimum
tc=tn #Coarse path now at j*T/Nsteps
dtc=0
dWc=0 #...Re-initialise coarse BI to 0
Mf[num]=mf
Mc[num]=mc
Xf[num]=Sf
Xc[num]=Sc
num+=1 #One more simulation down
return Xf,Mf,Xc,Mc
#######################################################################################################################
##Asset Plots
def diffusion_asset_plot(self,L=6,M=2):
"""
Plots underlying asset price for diffusion with given sde function (EM) on a fine and coarse grid differing by factor
of M.
Modelling SDE:
~~ dS=mu(S,t)dt+sig(S,t)*dW~~
Parameters:
self(Option): option that function is called through
L(int) : fine discretisation level
M(int) : coarseness factor s.t number of fine steps = M**L
"""
T=self.T;X0=self.X0
sde=self.sde
Nsteps=M**L
dt=T/Nsteps
sqrt_dt=np.sqrt(dt)
#Initialise fine, coarse asset prices; coarse Brownian increment (BI)
Xf=[X0];Xc=[X0]
dWc=0
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
t_=(j-1)*dt #Current time to simulate from in Ito calculus
dWf=np.random.randn()*sqrt_dt
dWc=dWc+dWf #Keep adding to coarse BI every loop until j is integer multiple of M
Xf+=[Xf[-1] + sde(Xf[-1],dt,t_,dWf)]
if j%M==0: #if j is integer multiple of M...
Xc+=[Xc[-1] + sde(Xc[-1],M*dt,t_,dWc)] #...Develop coarse path
dWc=0 #...Re-initialise coarse BI to 0
##Plot and label
tf=np.linspace(0,T,Nsteps+1) #Fine time grid
tc=np.linspace(0,T,M**(L-1)+1) #Coarse time grid
plt.plot(tf,Xf,'k-',label='Fine')
plt.plot(tc,Xc,'k--',label='Coarse')
label=' '.join(str(type(self).__name__).split('_'))
plt.legend(framealpha=1,frameon=True)
plt.title(label+f' Underlying Asset Price, $M={M}, L={L}$')
plt.xlabel('$t$')
plt.ylabel('Asset Price')
def JD_asset_plot(self,L=6,M=2):
"""
Plots underlying asset price for general JD with given sde function (EM) on a fine and coarse grid differing by factor
of M.
Modelling SDE:
~~ S_=r*(Sn)*dt+sig(Sn,t)*dW+c(Sn,t)*[-lam*Jbar*dt] - term in square brackets to make process martingale
~~ Sn+1=S_+c(Sn,t)*dJ
Idea:
___o_X_o__oX_o___X_o___X | Coarse with jumps
__Xo_X_oX_oX_oX__X_oX__X | Fine with jumps
-------------oX--X------ | Fine has to have fine timestep
-------------o---X------ | Coarse can have longer increment here, but has to respect jumps
Parameters:
self(Option): option that function is called through
L(int) : fine discretisation level
M(int) : coarseness factor s.t number of fine steps = M**L
"""
X0=self.X0;lam=self.lam;T=self.T
sde=self.sde
Nsteps=M**L
#Initialise asset price and time
dWc=0;tau=0;tf=0;tc=0;dtc=0
Xf=[X0];Xc=[X0];times_f=[0];times_c=[0]
##Algorithm Start
tau+=self.jumptime(scale=1/lam)
for j in range(1,Nsteps+1): #Note that if Nsteps=1 (l=0), j=1 and so coarse path not developed
tn=j*T/Nsteps #Fine timestepping right boundary
while tau<tn: #If jump is before right boundary...
dt=tau-tf #Adaptive step size is from last jump or left fine timestep
dtc+=dt #Coarse timestep increments
dWf=np.random.randn()*np.sqrt(dt) #Brownian motion for adaptive time step
dWc+=dWf #Increment coarse BI
dJ=np.exp(self.jumpsize())-1 #Generate jump
#Develop fine path
Xf+=[Xf[-1]+sde(Xf[-1],dt,tf,dWf,dJ)]
#Develop coarse path
Xc+=[Xc[-1]+sde(Xc[-1],dtc,tc,dWc,dJ)]
dWc=0 #Reset coarse BI
dtc=0 #Reset coarse timestep
tf=tau #Both fine and coarse paths now at t_=latest jump time
tc=tau
times_f+=[tau]
times_c+=[tau]
tau+=self.jumptime(scale=1/lam) #Next jump time
#Next jump time is after current right fine timestep
dt=tn-tf #Adaptive time step is time from recent jump or left fine time up to right fine time
dtc+=dt #Increment coarse timestep
dWf=np.random.randn()*np.sqrt(dt) #Fine BI for adaptive timestep
dWc+=dWf #Increment coarse BI
Xf+=[Xf[-1]+sde(Xf[-1],dt,tf,dWf)] #Develope fine timestep
tf=tn #Fine path now at j*T/Nsteps, set as left boundary
times_f+=[tf]
if j%M==0: #If reached coarse timepoint, then bring coarse path up to this point
Xc+=[Xc[-1]+sde(Xc[-1],dtc,tc,dWc)]#...Develop coarse path
tc=tn #Coarse path now at j*T/Nsteps
times_c+=[tc]
dtc=0
dWc=0 #...Re-initialise coarse BI to 0
##Plot and label
plt.plot(times_f,Xf,'k-',label='Fine')
plt.plot(times_c,Xc,'k--',label='Coarse')
plt.legend(framealpha=1, frameon=True)
label=' '.join(str(type(self).__name__).split('_'))
plt.title(label+f' Underlying Asset Price, $M={M}, L={L}$')
plt.xlabel('$t$')
plt.ylabel('Asset Price')
#######################################################################################################################
class Option:
"""
Base class for all options.
Attributes:
alpha_0 (float) : weak order of convergence of option sde
beta_0 (float) : order of convergence of variance of P_l-P_l-1
X0 (float) : Initial underlying asset price X(0)
r (float) : risk-free interest rate
K (float) : Strike price (overridden and set to None for Lookback options)
T (float) : Time to maturity for option
Methods:
__init__: Constructor
payoff : payoff function for option type
path : calculates path-wise quantities necessary to evaluate payoff
sde : time-stepping function to develop underlying asset path
looper : Interfaces with mlmc function to implement loop over Nl samples and generate payoff sums
"""
def __init__(self,alpha_0=None,beta_0=None,X0=100,K=100,T=1,r=0.05):
"""
The Constructor for Option class.
Parameters:
alpha_0 (float) : weak order of convergence of option sde
beta_0 (float) : order of convergence of variance of P_l-P_l-1
X0 (float) : Initial underlying asset price X(0)
r (float) : risk-free interest rate
K (float) : Strike price (overridden and set to None for Lookback options)
T (float) : Time to maturity for option
"""
self.alpha_0=alpha_0
self.beta_0=beta_0
self.X0=X0
self.r = r
self.K = K
self.T = T
#Virtual functions to be overridden by specific sub-classes
def payoff(self,N_loop,l,M): #Depends on option type
"""
The payoff function for Option inheritor. Should call self.path function.
No default. Should be implemented for any specific Option inheritors.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pf,Pc (numpy.array) : payoff vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
raise NotImplementedError("Option instance has no implemented payoff method")
def anti_payoff(self,N_loop,l,M): #Depends on option type
"""
The anti_payoff function for Option inheritor with antithetic estimators. Should call self.anti_path function.
No default. Should be implemented for any specific Option inheritors.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pf,Pc (numpy.array) : payoff vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
raise NotImplementedError("Option instance has no implemented anti_payoff method")
def path(self,N_loop,l,M): #Depends on underlying SDE
"""
The path function for option inheritor, which calculates path-wise quantities. Should call self.sde function.
No default. Should be implemented for any specific Option inheritors.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pathwise_f,Pathwise_c (numpy.array) : pathwise quantity vectors for N_loop sample paths (Pc=Xc=X0 if l==0)
"""
raise NotImplementedError("Option instance has no implemented path method")
def anti_path(self,N_loop,l,M): #Depends on underlying SDE
"""
The anti_path function for option inheritor, which calculates antithetic path-wise quantities. Should call self.sde function.
No default. Should be implemented for any specific Option inheritors.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
Returns:
Pathwise_f,Pathwise_a,Pathwise_c (numpy.array) : pathwise quantity vectors for N_loop sample paths (Pa=Pf,Pc=Xc=X0 if l==0)
"""
raise NotImplementedError("Option instance has no implemented anti_path method")
def sde(self,X,dt,t_,dW,dJ=0): #Depends on underlying SDE
"""
The sde time stepping function for option inheritor, which develops underlying asset path.
No default. Should be implemented for any specific Option inheritors.
Parameters:
self(Option): option that function is called through
X(np.array of floats): vector of asset prices at current time step for various sample paths
dt(float) : size of time step
t_(float) : current time
dW(np.array of floats): same size as X, vector of Brownian increments
dJ(np.array of floats): same size as X, vector of jumps s.t Xt=(1+dJ)*Xt-
Returns:
Xnew (numpy.array) : vector of asset prices at next time step
"""
raise NotImplementedError("Option instance has no implemented sde method")
def BS(self): #Depends on whether BS formula exists for option
"""
The analytic Black-Scholes formula for the given Option instance, if it exists.
No default. Should be implemented for any specific Option inheritors.
Parameters:
self(Option): option that function is called through
Returns:
c (float) : analytic option price
"""
raise NotImplementedError("Option instance has no implemented BS method")
def asset_plot(self,L=6,M=2):
"""
Plots underlying asset price for given sde function (EM) on a fine and coarse grid differing by factor of M.
No default. Should be implemented for any specific Option inheritors.
Parameters:
self(Option): option that function is called through
L(int) : fine discretisation level
M(int) : coarseness factor s.t number of fine steps = M**L
"""
raise NotImplementedError("Option instance has no implemented asset_plot method")
#~~~Common functions to all sub-classes~~~#
##Interfaces with mlmc algorithm
def looper(self,Nl,l,M,anti,Npl=10**4):
"""
Interfaces with mlmc function to implement loop over Nl samples and generate payoff sums.
Parameters:
self(Option): option that function is called through
N_loop(int): total number of sample paths to evaluate payoff on
l(int) : discretisation level
M(int) : coarseness factor, number of fine steps = M**l
anti(bool) : whether to use antithetic estimator
Npl(int) : size of sample path vector for each loop (i.e. number of samples per loop)
Returns:
suml (numpy.array) = [np.sum(dP_l),np.sum(dP_l**2),sumPf,sumPf2,sumPc,sumPc2,sum(Pf*Pc)]
7d vector of various payoff sums and payoff-squared sums for Nl samples at level l/l-1
Returns [sumPf,sumPf2,sumPf,sumPf2,0,0,0] is l=0.
"""
num_rem=Nl #Initialise remaining samples for while loop
suml=np.zeros(7)
while (num_rem>0): #<---Parallelise this while loop
N_loop=min(Npl,num_rem) #Break up Nl into manageable chunks of size Npl, until last iteration
num_rem-=N_loop #On final iteration N_loop=num_rem, so num_rem will be=0 and loop terminates
if anti==True: #Use antithetic estimators
Pf,Pc=self.anti_payoff(N_loop,l,M)
else:
Pf,Pc=self.payoff(N_loop,l,M)
sumPf=np.sum(Pf)
sumPf2=np.sum(Pf**2)
if l==0:
suml+=np.array([sumPf,sumPf2,sumPf,sumPf2,0,0,0])
else:
dP_l=Pf-Pc #Payoff difference
sumPc=np.sum(Pc)
sumPc2=np.sum(Pc**2)
sumPcPf=np.sum(Pc*Pf)
suml+=np.array([np.sum(dP_l),np.sum(dP_l**2),sumPf,sumPf2,sumPc,sumPc2,sumPcPf])
return suml
##MLMC function
def mlmc(self,eps,M=2,anti=False,N0=10**3, warm_start=True):
"""
Runs MLMC algorithm for given option (e.g. European) which returns an array of sums at each level.
________________
Example usage:
Euro=Euro_GBM()
sums,N=Euro.mlmc(eps=0.1)
________________
Parameters:
self(Option) : Option instance (with SDE params and order of weak convergence of method alpha_0)
eps(float) : desired accuracy
M(int) = 2 : coarseness factor
anti(bool) = False : whether to use antithetic estimator
N0(int) = 10**3 : default number of samples to use when initialising new level
warm_start(bool) = True: whether to save calculated alpha as alpha_0 for future function calls
Returns: sums=[np.sum(dP_l),np.sum(dP_l**2),sumPf,sumPf2,sumPc,sumPc2,sum(Pf*Pc)],N
sums(np.array) : sums of payoff diffs at each level and sum of payoffs at fine level, each column is a level
N(np.array of ints) : final number of samples at each level
"""
#Orders of convergence
alpha=max(0,self.alpha_0)
beta=max(0,self.beta_0)
L=2
V=np.zeros(L+1) #Initialise variance vector of each levels' variance
N=np.zeros(L+1) #Initialise num. samples vector of each levels' num. samples
dN=N0*np.ones(L+1) #Initialise additional samples for this iteration vector for each level
sums=np.zeros((7,L+1)) #Initialise sums array, each column is a level
sqrt_h=np.sqrt(M**(np.arange(0,L+1)))
while (np.sum(dN)>0): #Loop until no additional samples asked for
for l in range(L+1):
num=dN[l]
if num>0: #If asked for additional samples...
sums[:,l]+=self.looper(int(num),l,M,anti) #Call function which gives sums
N+=dN #Increment samples taken counter for each level
Yl=np.abs(sums[0,:])/N