2/14/22, 7:56 PM GR5260 Class3_4 – Jupyter Notebook
import numpy as np
import scipy.stats as stats
def BS_option_value(S0, K, T, r, q, v):
Copyright By PowCoder代写 加微信 powcoder
d1 = (np.log(S0/K)+(r-q+0.5*v**2)*T)/(v*np.sqrt(T))
d2 = d1 – v*np.sqrt(T)
price = S0*np.exp(-q*T)*stats.norm.cdf(d1) – K*np.exp(-r*T)*stats.norm.cdf(d2) return price
Out[3]: 22.80986759122129 In [4]:
Out[5]: 22.792245781795266 In [6]:
S0, K, T, r, q, v = 180, 160, 180/365, 0.02, 0.015, 0.20 BS_option_value(S0, K, T, r, q, v)
def sim_option_value(S0, K, T, r, q, v, n):
z = np.random.normal(size=n)
S = S0*np.exp((r-q-0.5*v**2)*T + v*np.sqrt(T)*z) disc_payoff = np.exp(-r*T)*np.maximum(S-K, 0) price = np.mean(disc_payoff)
return price
sim_option_value(S0, K, T, r, q, v, n)
# generate 1000 simulated values
# plot the distribution as a histogram
# n = # samples in computing the simulated option value # m = # simulated values
def sim_values(S0, K, T, r, q, v, n, m):
outputs = np.zeros(m) for i in range(m):
outputs[i] = sim_option_value(S0, K, T, r, q, v, n) return outputs
m, n = 1000, 10000
values = sim_values(S0, K, T, r, q, v, n, m) n = 50000
values2 = sim_values(S0, K, T, r, q, v, n, m)
localhost:8888/notebooks/2022_GR5260/GR5260 Class3_4.ipynb
2/14/22, 7:56 PM GR5260 Class3_4 – Jupyter Notebook
import matplotlib.pyplot as plt plt.hist(values, bins=50, label=’10000′) plt.hist(values2, bins=50, label=’50000′) plt.legend()
Out[9]:
Out[10]: array([[-0.65306766, 0.01162356], [ 0.34113676, -0.15419815],
# generate samples from multivariate normal
mean = np.zeros(2) corr = 0.8
cov = [[1.0, corr],
[corr, 1.0]]
samples = np.random.multivariate_normal(mean, cov, size=5) samples[0:3]
[-0.01199464, 0.89926457]])
# class exercise on Asian option
# monthly average: t1, t2,… t6 = 30, 60,…, 180
def sim_asian_call_price(S0, K, T, r, q, v, t_array, n):
# fill in details
k = len(t_array)
z = np.random.normal(size=(k,n))
S_sum = S = S0*np.exp((r-q-0.5*v**2)*(t_array[0]) + v*np.sqrt(t_array[0])*z[0]) for i in range(1,k):
dt = t_array[i] – t_array[i-1]
S = S*np.exp((r-q-0.5*v**2)*dt + v*np.sqrt(dt)*z[i]) S_sum += S
S_avg = S_sum / k
disc_payoffs = np.exp(-r*T)*np.maximum(S_avg – K,0) price = np.mean(disc_payoffs)
return price
S0, K, T, r, q, v = 180, 160, 180/365, 0.02, 0.015, 0.20 t_array = np.linspace(30, 180, 6)/365
sim_asian_call_price(S0, K, T, r, q, v, t_array, n)
Out[12]: 20.643957080348713
localhost:8888/notebooks/2022_GR5260/GR5260 Class3_4.ipynb
2/14/22, 7:56 PM GR5260 Class3_4 – Jupyter Notebook
np.zeros(shape=(5,4)) #np.linspace
Out[13]: array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.],
[0., 0., 0., 0.]])
Out[14]: array([ 2., 4., 6., 8., 10.])
np.linspace(2, 10, num=5)
localhost:8888/notebooks/2022_GR5260/GR5260 Class3_4.ipynb
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com