-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmontecarlo.py
282 lines (234 loc) · 12.3 KB
/
montecarlo.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
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
import mibian
import scipy as spy
import scipy.stats as stats
class Sim: #We define a class where each member contains the input parameters of the simulation
def __init__(self, S0, k, iv, rf, i_t, i, T):
self.S0 = S0 #known spot price
self.K = k #strike price
self.iv = iv
self.rf = rf #risk-free rate
self.i_t = i_t #no of time step iterations
self.i = i #no. of iterationsp
self.T = T #time period from the past time to today or today to future time
def calcvol_delta(S1, k, r, ttm, optprice, type): #r is in % and ttm is in days, takes the input of already known parameters of a certain option
vol = 0
if type == 'call':
c = mibian.BS([S1, k, r, ttm], callPrice=optprice)
vol = c.impliedVolatility
elif type == 'put':
c = mibian.BS([S1, k, r, ttm], putPrice=optprice)
vol = c.impliedVolatility
return (vol/100)
#We simulate the GBM through the following equation
#delx = nu*delt + vol*sqrt(delt)*Z where x = lnS
def simulation(simlist,type): #returns a results array which holds the spot price values for all time steps for all iterations and for all sims in the simlist
results = []
resultsminus = []
for sim in simlist:
if type == 'Sobol':
k = np.round(np.log2(sim.i) + 1)
k = k.astype(int)
sampler = stats.qmc.Sobol(d=sim.i_t+1, scramble = True) #This if structure tree decides what random number generation to use
Z = sampler.random_base2(m=k)
Z = stats.norm.ppf(Z.T)
Z.resize((sim.i_t+1, sim.i))
delt = sim.T/sim.i_t #This specifies the matrix that contains all the random variables
delx = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*Z #This calculates the incremental increase in the value of lnS or x
delx[0] = 0
dely = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*(-Z) #This calculates the incremental increase in the value of lnS or x
dely[0] = 0
lnSt = np.log(sim.S0) + np.cumsum(delx, axis=0) #This takes the cumulative sum along the rows, this means that it calculates the total values of increment at each time step
St = np.exp(lnSt)
results.append(St)
lnStminus = np.log(sim.S0) + np.cumsum(dely, axis=0)
stminus = np.exp(lnStminus)
resultsminus.append(stminus)
elif type == 'Halton':
sampler = stats.qmc.Halton(d=sim.i_t+1, scramble = True)
Z = sampler.random(m=sim.i)
Z = stats.norm.ppf(Z.T)
delt = sim.T/sim.i_t
delx = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*Z
delx[0] = 0
dely = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*(-Z)
dely[0] = 0
lnSt = np.log(sim.S0) + np.cumsum(delx, axis=0)
St = np.exp(lnSt)
results.append(St)
lnStminus = np.log(sim.S0) + np.cumsum(dely, axis=0)
stminus = np.exp(lnStminus)
resultsminus.append(stminus)
else:
Z = np.random.normal(size=(sim.i_t+1,sim.i))
delt = sim.T/sim.i_t
delx = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*Z
delx[0] = 0
dely = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*(-Z)
dely[0] = 0
lnSt = np.log(sim.S0) + np.cumsum(delx, axis=0)
St = np.exp(lnSt)
results.append(St)
lnStminus = np.log(sim.S0) + np.cumsum(dely, axis=0)
stminus = np.exp(lnStminus)
resultsminus.append(stminus)
return results, resultsminus
def simulation_delta_gamma(simlist,type): #This is similar to the original simulation function but uses Control Variates
results = []
control = []
resultsminus = []
controlminus = []
for sim in simlist:
if type == 'Sobol':
k = np.round(np.log2(sim.i) + 1)
k = k.astype(int)
delt = sim.T/sim.i_t
sampler = stats.qmc.Sobol(d=sim.i_t+1, scramble=True)
Z = sampler.random_base2(m=k)
Z = stats.norm.ppf(Z.T)
Z.resize((sim.i_t+1, sim.i))
delx = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*Z
delx[0] = 0
dely = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*(-Z)
dely[0] = 0
lnSt = np.log(sim.S0) + np.cumsum(delx, axis=0)
St = np.exp(lnSt)
lnStminus = np.log(sim.S0) + np.cumsum(dely, axis=0)
stminus = np.exp(lnStminus)
results.append(St)
resultsminus.append(stminus)
with np.errstate(divide='ignore', invalid='ignore'):
d1 = ((np.log(St[:-1].T/sim.K) + (sim.rf + (sim.iv**2)/2)*np.linspace(sim.T,0,sim.i_t))/(sim.iv*np.linspace(sim.T,0,sim.i_t))).T
delta1 = stats.norm.cdf(d1,0,1)
delcv = delta1*(St[1:]-(St[:-1]*(2.7183**(sim.rf*delt))))
cv = np.cumsum(delcv, axis=0)
control.append(cv)
with np.errstate(divide='ignore', invalid='ignore'):
d1 = ((np.log(stminus[:-1].T/sim.K) + (sim.rf + (sim.iv**2)/2)*np.linspace(sim.T,0,sim.i_t))/(sim.iv*np.linspace(sim.T,0,sim.i_t))).T
delta1 = stats.norm.cdf(d1,0,1)
delcv = delta1*(stminus[1:]-(stminus[:-1]*(2.7183**(sim.rf*delt))))
cvminus = np.cumsum(delcv, axis=0)
controlminus.append(cvminus)
elif type == 'Halton':
delt = sim.T/sim.i_t
sampler = stats.qmc.Halton(d=sim.i_t+1)
Z = sampler.random(sim.i)
Z = stats.norm.ppf(Z.T)
delx = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*Z
delx[0] = 0
dely = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*(-Z)
dely[0] = 0
lnSt = np.log(sim.S0) + np.cumsum(delx, axis=0)
St = np.exp(lnSt)
lnStminus = np.log(sim.S0) + np.cumsum(dely, axis=0)
stminus = np.exp(lnStminus)
results.append(St)
resultsminus.append(stminus)
with np.errstate(divide='ignore', invalid='ignore'):
d1 = ((np.log(St[:-1].T/sim.K) + (sim.rf + (sim.iv**2)/2)*np.linspace(sim.T,0,sim.i_t))/(sim.iv*np.linspace(sim.T,0,sim.i_t))).T
delta1 = stats.norm.cdf(d1,0,1)
delcv = delta1*(St[1:]-(St[:-1]*(2.7183**(sim.rf*delt))))
cv = np.cumsum(delcv, axis=0)
control.append(cv)
with np.errstate(divide='ignore', invalid='ignore'):
d1 = ((np.log(stminus[:-1].T/sim.K) + (sim.rf + (sim.iv**2)/2)*np.linspace(sim.T,0,sim.i_t))/(sim.iv*np.linspace(sim.T,0,sim.i_t))).T
delta1 = stats.norm.cdf(d1,0,1)
delcv = delta1*(stminus[1:]-(stminus[:-1]*(2.7183**(sim.rf*delt))))
cvminus = np.cumsum(delcv, axis=0)
controlminus.append(cvminus)
else:
delt = sim.T/sim.i_t
Z = np.random.normal(size=(sim.i_t+1,sim.i))
delx = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*Z
delx[0] = 0
dely = (sim.rf - 0.5*sim.iv**2)*delt + sim.iv*np.sqrt(delt)*(-Z)
dely[0] = 0
lnSt = np.log(sim.S0) + np.cumsum(delx, axis=0)
St = np.exp(lnSt)
lnStminus = np.log(sim.S0) + np.cumsum(dely, axis=0)
stminus = np.exp(lnStminus)
results.append(St)
resultsminus.append(stminus)
with np.errstate(divide='ignore', invalid='ignore'):
d1 = ((np.log(St[:-1].T/sim.K) + (sim.rf + (sim.iv**2)/2)*np.linspace(sim.T,0,sim.i_t))/(sim.iv*np.linspace(sim.T,0,sim.i_t))).T
delta1 = stats.norm.cdf(d1,0,1)
delcv = delta1*(St[1:]-(St[:-1]*(2.7183**(sim.rf*delt))))
cv = np.cumsum(delcv, axis=0)
control.append(cv)
with np.errstate(divide='ignore', invalid='ignore'):
d1 = ((np.log(stminus[:-1].T/sim.K) + (sim.rf + (sim.iv**2)/2)*np.linspace(sim.T,0,sim.i_t))/(sim.iv*np.linspace(sim.T,0,sim.i_t))).T
delta1 = stats.norm.cdf(d1,0,1)
delcv = delta1*(stminus[1:]-(stminus[:-1]*(2.7183**(sim.rf*delt))))
cvminus = np.cumsum(delcv, axis=0)
controlminus.append(cvminus)
return results, resultsminus, control, controlminus
def atv_payoff(results, resultsminus, simlist): #This is used to calculate the Anti Thetic Variates Payoff
payoff = []
deviation = []
for i in range(len(simlist)):
temp = np.array(results[i])
tempminus = np.array(resultsminus[i])
P = np.exp(-simlist[i].rf*simlist[i].T)*0.5*(np.maximum(0, (temp[-1] - simlist[i].K))+ np.maximum(0, (tempminus[-1] - simlist[i].K))) #calculating and discounting back all the payoff
P0 = np.sum(P)/simlist[i].i #Mean of the payoffs
A = np.sqrt((np.sum((P-P0)**2))/(simlist[i].i-1)) #Standard Error
payoff.append(P0)
deviation.append(A/np.sqrt(simlist[i].i))
return payoff, deviation
def delta_gamma_payoff(results, control, simlist): #This is used for the Control Variates case
payoff = []
deviation = []
for i in range(len(simlist)):
temp = np.array(results[i])
cv = np.array(control[i])
P = np.exp(-simlist[i].rf*simlist[i].T)*(np.maximum(0, (temp[-1] - simlist[i].K))-cv[-1]) #calculating and discounting back all the payoff
P0 = np.sum(P)/simlist[i].i
A = np.sqrt((np.sum((P-P0)**2))/(simlist[i].i-1))
payoff.append(P0)
deviation.append(A/np.sqrt(simlist[i].i))
return payoff, deviation
def normal_payoff(results, simlist): #Takes in the list of the sim parameters and returns the price and the standard error
payoff = []
deviation = []
for i in range(len(simlist)):
temp = np.array(results[i])
P = np.exp(-simlist[i].rf*simlist[i].T)*(np.maximum(0, (temp[-1] - simlist[i].K))) #calculating and discounting back all the payoff
P0 = np.sum(P)/simlist[i].i
A = np.sqrt((np.sum((P-P0)**2))/(simlist[i].i-1))
payoff.append(P0)
deviation.append(A/np.sqrt(simlist[i].i))
return payoff, deviation
def atv_delta_gamma_payoff(results,resultsminus, control, controlminus, simlist):
payoff = []
deviation = []
for i in range(len(simlist)):
temp = np.array(results[i])
tempminus = np.array(resultsminus[i])
cv = np.array(control[i])
cvminus = np.array(controlminus[i])
P = (np.exp(-simlist[i].rf*simlist[i].T))*0.5*(np.maximum(0, (temp[-1] - simlist[i].K)) + np.maximum(0, (tempminus[-1] - simlist[i].K)) - cv[-1] - cvminus[-1]) #calculating and discounting back all the payoff
P0 = np.sum(P)/simlist[i].i
A = np.sqrt((np.sum((P-P0)**2))/(simlist[i].i-1))
payoff.append(P0)
deviation.append(A/np.sqrt(simlist[i].i))
return payoff, deviation
def plotMCS(results, simlist): #Takes in the results that you get from the simulation function and plots it
for i in range(len(results)):
plt.plot(np.linspace(1, np.round(simlist[i].T*365),simlist[i].i_t+1), results[i])
plt.title("Simulation Results")
plt.xlabel("No. of days")
plt.ylabel("Spot Price")
plt.show()
simtemp = Sim(855.4, 850, calcvol_delta(855.4,830,6.26,12,30.3,'call'), 0.0626, 100, 1000, (((dt.date(2023,8,31)-dt.date.today()).days + 1)/365.0))
sims = [simtemp]
S_t, S_tminus, control, controlminus = simulation_delta_gamma(sims,'Sobol')
price1, error1 = normal_payoff(S_t, sims)
price2, error2 = atv_payoff(S_t, S_tminus, sims)
price3, error3 = delta_gamma_payoff(S_t,control,sims)
price4, error4 = atv_delta_gamma_payoff(S_t,S_tminus,control, controlminus, sims)
print(price1,error1) #Normal
print(price2,error2) #Anti-Thetic
print(price3,error3) #Delta Gamma Control Variates
print(price4,error4) #Combined
plotMCS(S_t,sims)