Python中的几何布朗运动模拟

tgo*_*ood 6 python simulation finance stocks montecarlo

我试图在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)
Run Code Online (Sandbox Code Playgroud)

蒙特卡罗模拟实例(股价模拟)

我目前正在使用Python 3.6.1.

提前感谢您的帮助.

Bra*_*mon 7

这里有一些代码的重写,可能会使符号S更直观,并允许您检查您的答案是否合理.

初始要点:

  • 在您的代码中,第二个deltat应该替换为np.sqrt(deltat).来源这里(是的,我知道这是不是最官方的,但下面的结果应该是让人放心).
  • 关于不对您的短期利率和西格玛值进行年度化的评论可能不正确.这与您所看到的向下漂移无关.您需要按年率计算这些费用.这些将始终是连续复合(恒定)的速率.

首先,这是Yves Hilpisch的一个GBM路径生成函数--Python for Finance,第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
Run Code Online (Sandbox Code Playgroud)

设置您的初始值(但使用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)
Run Code Online (Sandbox Code Playgroud)

然后生成路径:

np.random.seed(123)
paths = gen_paths(S0, r, sigma, T, N, i)
Run Code Online (Sandbox Code Playgroud)

现在,要检查:在到期时paths[-1]获取结束St值:

np.average(paths[-1])
Out[44]: 104.47389541107971
Run Code Online (Sandbox Code Playgroud)

如你所知,收益将是(St - K, 0)的最大值:

CallPayoffAverage = np.average(np.maximum(0, paths[-1] - K))
CallPayoff = discount_factor * CallPayoffAverage
print(CallPayoff)
20.9973601515
Run Code Online (Sandbox Code Playgroud)

如果你绘制这些路径(很容易使用pd.DataFrame(paths).plot(),你会发现它们不再是向下趋势,而是Sts大致是对数正态分布的.

最后,这是通过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
Run Code Online (Sandbox Code Playgroud)

i在GBM设置中使用更高的值应该会导致更接近的收敛.