-
Notifications
You must be signed in to change notification settings - Fork 1
/
multiple.py
694 lines (509 loc) · 21.7 KB
/
multiple.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
'''
File Name : multiple.py
Aouthor : Junwen Peng
E-Mail : [email protected] / [email protected]
'''
import abc
import numpy as np
import numpy.linalg as la
from paths import *
from pricing import *
import warnings
warnings.filterwarnings("ignore")
class MultiMonteCarloSim(MonteCarloSim):
'''
Multiple Monte Carlo simulation abstract base class which should only be inherited by subclasses
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
model,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, model, **model_params)
model_types_list = [
MultiCEV,
MultiGeoBrownianMotion]
assert model in model_types_list, 'Selcet an available model type'
self.n_assets = len(init_price)
@abc.abstractmethod
@MonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivatives
abstract method which must be implemented in the inherited class
the overwritten method of 'value()' in the inherited class must be decorated with 'MonteCarloSim.generate_paths' decorator
'''
print('Base class MonteCarloSim has no concrete implementation of .value() and return None')
self.payoff_vector = None
simulated_price = None
return simulated_price
def std(self, index):
'''
compute standard variation of the ith sample paths
'''
assert index <= self.n_assets, 'The index of ith asset is greater than the number of assets'
try:
return np.std(self.price_process[index-1,:,-1])
except:
raise ValueError('There is no payoff which is computed')
class EuropeanVanillaSpreadMonteCarloSim(MultiMonteCarloSim):
'''
monte carlo simulation for european vanilla spread options
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
strike,
option_type='call',
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, model, **model_params)
assert self.n_assets == 2, 'The number of assets must be 2'
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
self.strike = strike
self.option_type = option_type
@MultiMonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivative
'''
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:x-self.strike if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:self.strike-x if self.strike-x >= 0 else 0,1,1)
self.payoff_vector = relu_func(self.price_process[0,:,-1]-self.price_process[1,:,-1])
simulated_price = np.exp(-self.rate*self.tau) * np.mean(self.payoff_vector)
return simulated_price
class EuropeanVanillaExchangeMonteCarloSim(EuropeanVanillaSpreadMonteCarloSim):
'''
monte carlo simulation for european vanilla exchange options
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, 0, 'call', model, **model_params)
class EuropeanVanillaBasketMonteCarloSim(MultiMonteCarloSim):
'''
monte carlo simulation for european vanilla basket options
'''
def __init__(
self,
init_price,
weight,
maturity,
n_trials,
nper_per_year,
strike,
option_type='call',
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, model, **model_params)
assert len(weight) == self.n_assets, 'The number of weights must be euqal to the number of the assets'
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
self.weight = np.array(weight/np.sum(weight)).reshape(self.n_assets,1)
self.strike = strike
self.option_type = option_type
@MultiMonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivative
'''
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:x-self.strike if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:self.strike-x if self.strike-x >= 0 else 0,1,1)
self.payoff_vector = relu_func(self.weight.T @ self.price_process[:,:,-1])
simulated_price = np.exp(-self.rate*self.tau) * np.mean(self.payoff_vector)
return simulated_price
class EuropeanVanillaRainbowMonteCarloSim(MultiMonteCarloSim):
'''
monte carlo simulation for european vanilla rainbow options
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
strike,
option_type='call',
payoff_type='max',
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, model, **model_params)
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
self.strike = strike
self.option_type = option_type
self.payoff_type = payoff_type
@MultiMonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivative
'''
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:x-self.strike if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:self.strike-x if self.strike-x >= 0 else 0,1,1)
if self.payoff_type == 'max':
self.payoff_vector = relu_func(np.max(self.price_process[:,:,-1], axis=0))
elif self.payoff_type == 'min':
self.payoff_vector = relu_func(np.min(self.price_process[:,:,-1], axis=0))
simulated_price = np.exp(-self.rate*self.tau) * np.mean(self.payoff_vector)
return simulated_price
class EuropeanBarrierSpreadMonteCarloSim(MultiMonteCarloSim):
'''
monte carlo simulation for european barrier spread options
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
strike,
barrier_up=None,
barrier_down=None,
option_type='call',
knock_type='out',
direction='up',
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, model, **model_params)
assert self.n_assets == 2, 'The number of assets must be 2'
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
assert knock_type.lower() in ('in', 'out'), 'Knock type must be in or out'
assert direction.lower() in ('up', 'down', 'double'), 'Direction type must be up or down or double'
if direction == 'up':
assert barrier_up != None , 'Please input an upward barrier'
elif direction == 'down':
assert barrier_down != None , 'Please input a downward barrier'
elif direction == 'double':
assert barrier_up != None and barrier_down != None, 'Please input both an upward barrier and a downward barrier'
self.strike = strike
self.option_type = option_type
self.knock_type = knock_type
self.direction = direction
self.barrier_up = (init_price[0]-init_price[1])*barrier_up
self.barrier_down = init_price*barrier_down
@MultiMonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivative
'''
spread_process = self.price_process[0,:,:]-self.price_process[1,:,:]
indicator_matrix = np.zeros((self.n_trials,1))
if self.direction == 'up':
if self.knock_type == 'out':
indicator_matrix = np.array(np.max(spread_process,axis=1) < self.barrier_up, dtype=int)
elif self.knock_type == 'in':
indicator_matrix = np.array(np.max(spread_process,axis=1) >= self.barrier_up, dtype=int)
elif self.direction == 'down':
if self.knock_type == 'out':
indicator_matrix = np.array(np.min(spread_process,axis=1) > self.barrier_down, dtype=int)
elif self.knock_type == 'in':
indicator_matrix = np.array(np.min(spread_process,axis=1) <= self.barrier_down, dtype=int)
elif self.direction == 'double':
if self.knock_type == 'out':
indicator_matrix = np.array(np.max(spread_process,axis=1) < self.barrier_up, dtype=int) * np.array(np.min(spread_process,axis=1) > self.barrier_down, dtype=int)
elif self.knock_type == 'in':
indicator_matrix = 1-((1-np.array(np.max(spread_process,axis=1) >= self.barrier_up, dtype=int)) * (1-np.array(np.min(spread_process,axis=1) <= self.barrier_down, dtype=int)))
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:x-self.strike if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:self.strike-x if self.strike-x >= 0 else 0,1,1)
self.payoff_vector = relu_func(spread_process[:,-1])*indicator_matrix
simulated_price = np.exp(-self.rate*self.tau) * np.mean(self.payoff_vector)
return simulated_price
class EuropeanAsianBasketMonteCarloSim(MultiMonteCarloSim):
'''
monte carlo simulation for european asian basket options
'''
def __init__(
self,
init_price,
weight,
maturity,
n_trials,
nper_per_year,
strike,
option_type='call',
ave_type='arith',
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, model, **model_params)
assert len(weight) == self.n_assets, 'The number of weights must be euqal to the number of the assets'
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
assert ave_type.lower() in ('arith', 'geo'), 'The average type must be arithmetic or geometric'
self.weight = np.array(weight/np.sum(weight)).reshape(self.n_assets,1)
self.strike = strike
self.option_type = option_type
self.ave_type = ave_type
@MultiMonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivative
'''
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:x-self.strike if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:self.strike-x if self.strike-x >= 0 else 0,1,1)
if self.ave_type == 'arith':
self.payoff_vector = relu_func(np.mean(np.tensordot(self.weight.T, self.price_process, axes=1), axis=1))
elif self.ave_type == 'geo':
self.payoff_vector = relu_func(np.exp(np.mean(np.log(np.tensordot(self.weight.T, self.price_process, axes=1)), axis=1)))
simulated_price = np.exp(-self.rate*self.tau) * np.mean(self.payoff_vector)
return simulated_price
class EuropeanBinaryRainbowMonteCarloSim(MultiMonteCarloSim):
'''
monte carlo simulation for european binary rainbow options
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
strike,
option_type='call',
payoff_type='max',
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, model, **model_params)
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
self.strike = strike
self.option_type = option_type
self.payoff_type = payoff_type
@MultiMonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivative
'''
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:1 if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:1 if self.strike-x >= 0 else 0,1,1)
if self.payoff_type == 'max':
self.payoff_vector = relu_func(np.max(self.price_process[:,:,-1], axis=0))
elif self.payoff_type == 'min':
self.payoff_vector = relu_func(np.min(self.price_process[:,:,-1], axis=0))
simulated_price = np.exp(-self.rate*self.tau) * np.mean(self.payoff_vector)
return simulated_price
class MultiLeastSquaredMonteCarloSim(LeastSquaredMonteCarloSim,MonteCarloSim):
'''
multiple least squared monte carlo simulation base class
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
regression_model,
features_degree,
model,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, regression_model, features_degree, model, **model_params)
model_types_list = [
MultiCEV,
MultiGeoBrownianMotion]
assert model in model_types_list, 'Selcet an available model type'
self.n_assets = len(init_price)
@abc.abstractmethod
def process_to_2d(self):
'''
reduce the assets dimension on process tensor by the payoff structure
'''
pass
def std(self, index):
'''
compute standard variation of the ith sample paths
'''
return MultiMonteCarloSim.std(index)
@LeastSquaredMonteCarloSim.generate_paths
def value(self):
'''
valuation of the derivative
'''
self.process_to_2d()
self.exercise_matrix = np.where(self.payoff(-1) > 0, 1,0).reshape(self.n_trials, 1)
for i in range(self.n_intervals-1):
itm_index = self.itm_path_index(-i-2)
if len(itm_index) < 1:
self.exercise_matrix = np.concatenate([np.array([0]*self.n_trials).reshape(self.n_trials,1), self.exercise_matrix], axis=1)
continue
itm_paths = self.price_process[itm_index].reshape(len(itm_index), self.n_intervals)
dis_cash_flow = np.exp(-self.rate*self.delta_time)*(self.payoff(-i-1)[np.array(itm_index)])
reg_X = np.ones((len(itm_index), 1))
for j in range(self.features_degree):
reg_X = np.concatenate([reg_X, np.array([[x_value**(j+1) for x_value in itm_paths[:,-i-2]]]).T], axis=1)
regressor = self.regression_model().fit(reg_X, dis_cash_flow)
reg_result = regressor.predict(reg_X)
exercise_vector = np.array([0]*self.n_trials)
np.put(exercise_vector, itm_index, np.where(self.payoff(-i-2)[np.array(itm_index)] > reg_result, 1,0))
self.exercise_matrix = np.concatenate([np.array(exercise_vector).reshape(len(exercise_vector),1), self.exercise_matrix], axis=1)
exercise_index = np.squeeze(np.argmax(self.exercise_matrix, axis=1))
exercise_indicator = np.max(self.exercise_matrix, axis=1)
exercise_payoff = self.payoff()[range(self.n_trials), exercise_index] * exercise_indicator
expire_maturity = ((exercise_index + 1) * exercise_indicator) / self.nper_per_year
discount_func = np.frompyfunc(lambda x:np.exp(-self.rate*x),1,1)
simulated_price = np.mean(discount_func(expire_maturity) * exercise_payoff)
return simulated_price
class AmericanVanillaBasketLSMC(MultiLeastSquaredMonteCarloSim):
'''
least squared monte carlo simulation for american vanilla basket options
'''
def __init__(
self,
init_price,
weight,
maturity,
n_trials,
nper_per_year,
strike,
option_type='put',
regression_model=LinearRegression,
features_degree=2,
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, regression_model, features_degree, model, **model_params)
assert len(weight) == self.n_assets, 'The number of weights must be euqal to the number of the assets'
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
self.rate = model_params['rate']
self.weight = np.array(weight/np.sum(weight)).reshape(self.n_assets,1)
self.strike = strike
self.option_type = option_type
def process_to_2d(self):
'''
reduce the assets dimension on process tensor by the payoff structure
'''
self.price_process = np.tensordot(self.weight.T, self.price_process, axes=1).reshape(self.n_trials, self.n_intervals)
def payoff(self, time_i=None):
'''
define the exercise payoff for a certain derivative
'''
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:x-self.strike if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:self.strike-x if self.strike-x >= 0 else 0,1,1)
if time_i != None:
return relu_func(self.price_process[:,time_i])
else:
return relu_func(self.price_process)
def itm_path_index(self, time_i):
'''
filter the in the money paths
'''
if self.option_type == 'call':
return np.argwhere(self.price_process[:,time_i] > self.strike)
elif self.option_type == 'put':
return np.argwhere(self.price_process[:,time_i] < self.strike)
class AmericanAsianRainbowLSMC(MultiLeastSquaredMonteCarloSim):
'''
least squared monte carlo simulation for american asian rainbow options
'''
def __init__(
self,
init_price,
maturity,
n_trials,
nper_per_year,
strike,
option_type='put',
ave_type='arith',
payoff_type='max',
regression_model=LinearRegression,
features_degree=2,
model=MultiGeoBrownianMotion,
**model_params):
'''
intiaialize the structure parameters
'''
super().__init__(init_price, maturity, n_trials, nper_per_year, regression_model, features_degree, model, **model_params)
assert option_type.lower() in ('call', 'put'), 'The option type must be call or put'
assert ave_type.lower() in ('arith', 'geo'), 'The average type must be arithmetic or geometric'
self.rate = model_params['rate']
self.strike = strike
self.option_type = option_type
self.ave_type = ave_type
self.payoff_type = payoff_type
def process_to_2d(self):
'''
reduce the assets dimension on process tensor by the payoff structure
'''
if self.payoff_type == 'max':
self.price_process = np.max(self.price_process, axis=0)
elif self.payoff_type == 'min':
self.price_process = np.min(self.price_process, axis=0)
def payoff(self, time_i=None):
'''
define the exercise payoff for a certain derivative
'''
if self.option_type == 'call':
relu_func = np.frompyfunc(lambda x:x-self.strike if x-self.strike >= 0 else 0,1,1)
elif self.option_type == 'put':
relu_func = np.frompyfunc(lambda x:self.strike-x if self.strike-x >= 0 else 0,1,1)
if time_i != None:
if self.ave_type == 'arith':
return relu_func(np.mean(self.price_process[:,:time_i], axis=1))
elif self.ave_type == 'geo':
return relu_func(np.exp(np.mean(np.log(self.price_process[:,:time_i]), axis=1)))
else:
if self.ave_type == 'arith':
return relu_func(np.cumsum(self.price_process, axis=1)/np.array([[i+1 for i in range(self.n_intervals)]]*self.n_trials))
elif self.ave_type == 'geo':
return relu_func(np.exp(np.cumsum(np.log(self.price_process), axis=1)/np.array([[i+1 for i in range(self.n_intervals)]]*self.n_trials)))
def itm_path_index(self, time_i):
'''
filter the in the money paths
'''
if self.option_type == 'call':
if self.ave_type == 'arith':
return np.argwhere(np.mean(self.price_process[:,:time_i], axis=1) > self.strike)
elif self.ave_type == 'geo':
return np.argwhere(np.exp(np.mean(np.log(self.price_process[:,:time_i]), axis=1)) > self.strike)
elif self.option_type == 'put':
if self.ave_type == 'arith':
return np.argwhere(np.mean(self.price_process[:,:time_i], axis=1) < self.strike)
elif self.ave_type == 'geo':
return np.argwhere(np.exp(np.mean(np.log(self.price_process[:,:time_i]), axis=1)) < self.strike)