12 Python总结之蒙特卡洛模拟

蒙特卡洛模拟

蒙特卡洛模拟是金融学和数值科学中最重要的算法之一。它之所以重要,是因为在期权定价或者风险管理问题上有很强的能力。和其它数值方法相比,蒙特卡洛方法很容易处理高维问题,在这种问题上复杂度和计算需求通常以线性方式增大。

蒙特卡洛方法的缺点是:它本身是高计算需求的,即使对于相当简单的问题也往往需要海量的计算。因此,必须高效的实现蒙特卡洛算法。

下面使用不同的方法实现蒙特卡洛算法

1.Scipy

2.纯Python

3.向量化Numpy

4.全向量化Numpy

方法一:Scipy

欧式看涨期权的定价公式Black-Scholes-Merton(1973):

其中:

C—期权初始合理价格

L—期权交割价格

S—所交易金融资产现价

T—期权有效期

r—连续复利计无风险利率

σ2—年度化方差

N()—正态分布变量的累积概率分布函数

# 导用到的库
from math import log, sqrt, exp
from scipy import stats
# 期权的定价计算,根据公式1.
def bsm_call_value(S_0, K, T, r, sigma):
    S_0 = float(S_0)
    d_1 = (log(S_0 / K) + (r + 0.5 *sigma **2) *T)/(sigma * sqrt(T))
    d_2 = (log(S_0 / K) + (r - 0.5 *sigma **2) *T)/(sigma * sqrt(T))
    C_0 = (S_0 * stats.norm.cdf(d_1, 0.0, 1.0) - K * exp(-r * T) * stats.norm.cdf(d_2, 0.0, 1.0))
    return C_0
# 计算的一些初始值
S_0 = 100.0    # 股票或指数初始的价格;
K = 105        #  行权价格
T = 1.0        #  期权的到期年限(距离到期日时间间隔)
r = 0.05       #   无风险利率
sigma = 0.2    # 波动率(收益标准差)
# 到期期权价值
%time print (bsm_call_value(S_0, K, T, r, sigma))
8.021352235143176
Wall time: 511 µs

方法二:Python

下面的计算仍基于BSM(balck-scholes-merton),模型中的高风险标识(股票指数)在风险中立的情况下遵循以随机微分方程(SDE)表示的布朗运动.

在这里插入图片描述

在这里插入图片描述

# 导入python模块
from time import time
from math import exp, sqrt, log
from random import gauss, seed
seed(2000)
# 计算的一些初始值
S_0 = 100.0    # 股票或指数初始的价格;
K = 105        #  行权价格
T = 1.0        #  期权的到期年限(距离到期日时间间隔)
r = 0.05       #   无风险利率
sigma = 0.2    # 波动率(收益标准差)
M = 50         # number of time steps
dt = T/M       # time enterval
I = 20000       # number of simulation
start = time()
S = []     # 
for i in range(I):
    path = []    # 时间间隔上的模拟路径
    for t in range(M+1):
        if t==0:
            path.append(S_0)
        else:
            z = gauss(0.0, 1.0)
            S_t = path[t-1] * exp((r-0.5*sigma**2) * dt + sigma * sqrt(dt) * z)
            path.append(S_t)
    S.append(path)
# 计算期权现值
C_0 = exp(-r * T) *sum([max(path[-1] -K, 0) for path in S])/I
total_time = time() - start
print ('European Option value %.6f'% C_0)
print ('total time is %.6f seconds'% total_time)
European Option value 8.159995
total time is 1.616999 seconds

前三十条模拟路径

# 选取部分模拟路径可视化

import matplotlib.pyplot as plt 
%matplotlib inline 
plt.figure(figsize=(10,7))
plt.grid(True)
plt.xlabel('Time step')
plt.ylabel('index level')
for i in range(30):
    plt.plot(S[i])

在这里插入图片描述

方法三: 向量化的Numpy

使用numpy的一些数组,来减少运算

# 导入模块
import numpy as np
from time import time
# 计算的一些初始值
S_0 = 100.0    # 股票或指数初始的价格;
K = 105        #  行权价格
T = 1.0        #  期权的到期年限(距离到期日时间间隔)
r = 0.05       #   无风险利率
sigma = 0.2    # 波动率(收益标准差)
M = 50         # number of time steps
dt = T/M       # time enterval
I = 20000       # number of simulation
# 20000条模拟路径,每条路径50个时间步数
S = np.zeros((M+1, I))
S[0] = S_0
np.random.seed(2000)
start = time()
for t in range(1, M+1):
    z = np.random.standard_normal(I)
    S[t] = S[t-1] * np.exp((r- 0.5 * sigma **2)* dt + sigma * np.sqrt(dt)*z)
C_0 = np.exp(-r * T)* np.sum(np.maximum(S[-1] - K, 0))/I
end = time()
# 估值结果
print ('total time is %.6f seconds'%(end-start))
print ('European Option Value %.6f'%C_0)
total time is 0.039680 seconds
European Option Value 7.993282

前20条模拟路径

# 前20条模拟路径
import matplotlib.pyplot as plt
%matplotlib inline 
plt.figure(figsize=(10,7))
plt.grid(True)
plt.xlabel('Time step')
plt.ylabel('index level')
for i in range(20):
    plt.plot(S.T[i])

在这里插入图片描述

到期指数模拟水平

# 到期时所有模拟指数水平的频率直方图
%matplotlib inline
plt.hist(S[-1], bins=50)
plt.grid(True)
plt.xlabel('index level')
plt.ylabel('frequency')
Text(0, 0.5, 'frequency')

在这里插入图片描述

到期期权内在价值

# 模拟期权到期日的内在价值
%matplotlib inline
plt.hist(np.maximum(S[-1]-K, 0), bins=50)
plt.grid(True)
plt.xlabel('option inner value')
plt.ylabel('frequency')
Text(0, 0.5, 'frequency')

在这里插入图片描述

方法四:全向量化的Numpy

import numpy as np
from time import time
# 计算的一些初始值
S_0 = 100.0    # 股票或指数初始的价格;
K = 105        #  行权价格
T = 1.0        #  期权的到期年限(距离到期日时间间隔)
r = 0.05       #   无风险利率
sigma = 0.2    # 波动率(收益标准差)
M = 50         # number of time steps
dt = T/M       # time enterval
I = 20000       # number of simulation
np.random.seed(2000)
start = time()
# 生成一个随机变量的数组,M+1行,I列
# 同时计算出没一条路径,每一个时间点的指数水平的增量
# np.cumsum(axis=0),在列的方向上进行累加得到每一个时间步数上的指数水平
S = S_0 * np.exp(np.cumsum((r - 0.5*sigma **2) *dt +sigma *np.sqrt(dt) *np.random.standard_normal((M+1, I)),axis=0))
S [0] = S_0
C_0 = np.exp(-r * T) * np.sum(np.maximum(S[-1] - K, 0))/I
end = time()
print ('toatl time is %.6f seconds'%(end-start))
print ('Europaen Option Value %.6f'%C_0)
toatl time is 0.077348 seconds
Europaen Option Value 8.113643

前20条模拟路径

# 前20条模拟路径
import matplotlib.pyplot as plt
%matplotlib inline 
plt.figure(figsize=(10,7))
plt.grid(True)
plt.xlabel('Time step')
plt.ylabel('index level')
plt.plot(S[:,:20])
[<matplotlib.lines.Line2D at 0x201fca9a400>,
 <matplotlib.lines.Line2D at 0x201fca9a550>,
 <matplotlib.lines.Line2D at 0x201fca9a6a0>,
 <matplotlib.lines.Line2D at 0x201fca9a7f0>,
 <matplotlib.lines.Line2D at 0x201fca9a940>,
 <matplotlib.lines.Line2D at 0x201fca9aa90>,
 <matplotlib.lines.Line2D at 0x201fca9abe0>,
 <matplotlib.lines.Line2D at 0x201fca9ad30>,
 <matplotlib.lines.Line2D at 0x201fca9ae80>,
 <matplotlib.lines.Line2D at 0x201fca9afd0>,
 <matplotlib.lines.Line2D at 0x201fca62780>,
 <matplotlib.lines.Line2D at 0x201fcaa1278>,
 <matplotlib.lines.Line2D at 0x201fcaa13c8>,
 <matplotlib.lines.Line2D at 0x201fcaa1518>,
 <matplotlib.lines.Line2D at 0x201fcaa1668>,
 <matplotlib.lines.Line2D at 0x201fcaa17b8>,
 <matplotlib.lines.Line2D at 0x201fcaa1908>,
 <matplotlib.lines.Line2D at 0x201fcaa1a58>,
 <matplotlib.lines.Line2D at 0x201fcaa1ba8>,
 <matplotlib.lines.Line2D at 0x201fcaa1cf8>]

在这里插入图片描述

模拟到期指数水平

# 到期时所有模拟指数水平的频率直方图
import matplotlib.pyplot as plt
%matplotlib inline
plt.hist(S[-1], bins=50)
plt.grid(True)
plt.xlabel('index level')
plt.ylabel('frequency')
Text(0, 0.5, 'frequency')

在这里插入图片描述

模拟到期期权内在价值

# 模拟期权到期日的内在价值
%matplotlib inline
plt.hist(np.maximum(S[-1]-K, 0), bins=50)
plt.grid(True)
plt.xlabel('option inner value')
plt.ylabel('frequency')
Text(0, 0.5, 'frequency')

在这里插入图片描述

sum(S[-1] < K)    # 在两万次模拟中超过一万次到期期权内在价值为0
10748

结果对比

1.Scipy,估值结果:8.021352,耗时:511 µs

2.Python,估值结果:8.159995,耗时:1.616999s

3.向量化Numpy,估值结果:7.993282,耗时:0.039680s

4.完全向量化Numpy,估值结果:8.113643,耗时:0.077348

Scipy,用时最短是因为,沒有进行20000次的模拟估值.其他三个方法进行了20000次的模拟,基于Numpy的计算方法速度比较快.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mind_programmonkey

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值