我试图在Python中模拟几何布朗运动,通过蒙特卡罗模拟为欧洲看涨期权定价。我对Python比较陌生,而且我收到了一个我认为错误的答案,因为它无法收敛到BS价格,并且由于某种原因,迭代似乎是负面趋势。任何帮助将不胜感激。
import numpy as np
from matplotlib import pyplot as plt
S0 = 100 #initial stock price
K = 100 #strike price
r = 0.05 #risk-free interest rate
sigma = 0.50 #volatility in market
T = 1 #time in years
N = 100 #number of steps within each simulation
deltat = T/N #time step
i = 1000 #number of simulations
discount_factor = np.exp(-r*T) #discount factor
S = np.zeros([i,N])
t = range(0,N,1)
for y in range(0,i-1):
S[y,0]=S0
for x in range(0,N-1):
S[y,x+1] = S[y,x]*(np.exp((r-(sigma**2)/2)*deltat + sigma*deltat*np.random.normal(0,1)))
plt.plot(t,S[y])
plt.title('Simulations %d Steps %d Sigma %.2f r %.2f S0 %.2f' % (i, N, sigma, r, S0))
plt.xlabel('Steps')
plt.ylabel('Stock Price')
plt.show()
C = np.zeros((i-1,1), dtype=np.float16)
for y in range(0,i-1):
C[y]=np.maximum(S[y,N-1]-K,0)
CallPayoffAverage = np.average(C)
CallPayoff = discount_factor*CallPayoffAverage
print(CallPayoff)
蒙特卡罗模拟示例(股票价格模拟)
我目前正在使用Python 3.6.1。
提前感谢您的帮助。
答案 0 :(得分:6)
这里有一些代码重写,可能会使S
的符号更直观,并且可以让您检查答案的合理性。
初步要点:
deltat
应替换为np.sqrt(deltat)
。来源here(是的,我知道这不是最正式的,但下面的结果应该让人放心)。首先,这是Yves Hilpisch的一个GBM路径生成函数 - Python for Finance ,chapter 11。参数在链接中进行了解释,但设置与您的设置非常相似。
def gen_paths(S0, r, sigma, T, M, I):
dt = float(T) / M
paths = np.zeros((M + 1, I), np.float64)
paths[0] = S0
for t in range(1, M + 1):
rand = np.random.standard_normal(I)
paths[t] = paths[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt +
sigma * np.sqrt(dt) * rand)
return paths
设置初始值(但使用N=252
,1年内的交易天数,作为时间增量的数量):
S0 = 100.
K = 100.
r = 0.05
sigma = 0.50
T = 1
N = 252
deltat = T / N
i = 1000
discount_factor = np.exp(-r * T)
然后生成路径:
np.random.seed(123)
paths = gen_paths(S0, r, sigma, T, N, i)
现在,要检查:paths[-1]
在到期时获取结束St
值:
np.average(paths[-1])
Out[44]: 104.47389541107971
现在,收益将是(St - K, 0
)的最大值:
CallPayoffAverage = np.average(np.maximum(0, paths[-1] - K))
CallPayoff = discount_factor * CallPayoffAverage
print(CallPayoff)
20.9973601515
如果您绘制这些路径(很容易使用pd.DataFrame(paths).plot()
),您会发现它们不再是向下趋势,而是St
近似正常分布。
最后,这是通过BSM进行的健全性检查:
class Option(object):
"""Compute European option value, greeks, and implied volatility.
Parameters
==========
S0 : int or float
initial asset value
K : int or float
strike
T : int or float
time to expiration as a fraction of one year
r : int or float
continuously compounded risk free rate, annualized
sigma : int or float
continuously compounded standard deviation of returns
kind : str, {'call', 'put'}, default 'call'
type of option
Resources
=========
http://www.thomasho.com/mainpages/?download=&act=model&file=256
"""
def __init__(self, S0, K, T, r, sigma, kind='call'):
if kind.istitle():
kind = kind.lower()
if kind not in ['call', 'put']:
raise ValueError('Option type must be \'call\' or \'put\'')
self.kind = kind
self.S0 = S0
self.K = K
self.T = T
self.r = r
self.sigma = sigma
self.d1 = ((np.log(self.S0 / self.K)
+ (self.r + 0.5 * self.sigma ** 2) * self.T)
/ (self.sigma * np.sqrt(self.T)))
self.d2 = ((np.log(self.S0 / self.K)
+ (self.r - 0.5 * self.sigma ** 2) * self.T)
/ (self.sigma * np.sqrt(self.T)))
# Several greeks use negated terms dependent on option type
# For example, delta of call is N(d1) and delta put is N(d1) - 1
self.sub = {'call' : [0, 1, -1], 'put' : [-1, -1, 1]}
def value(self):
"""Compute option value."""
return (self.sub[self.kind][1] * self.S0
* norm.cdf(self.sub[self.kind][1] * self.d1, 0.0, 1.0)
+ self.sub[self.kind][2] * self.K * np.exp(-self.r * self.T)
* norm.cdf(self.sub[self.kind][1] * self.d2, 0.0, 1.0))
option.value()
Out[58]: 21.792604212866848
在GBM设置中使用i
的较高值会导致更接近的收敛。
答案 1 :(得分:0)