
参考 Python For Finance 第二版
在财务做衍生商品一般会遇到的问题,其实在实际中需要商品都是导不出公式的,也就是没有规律可循。对于这些生成随机数据的随机过程我们并不是束手无策,我们通过风险因子来模拟随机过程。今天我们学习如何使用 numpy 生成随机数。
import math
import numpy as np
import numpy.random as npr
from pylab import plt,mpl
为了图表能够看起来标准点,我们引入 seaborn
plt.style.use('seaborn')
# mpl.rcParams['fon']
%matplotlib inline
npr.seed(100)
# 设置数据的精度,这样看起来很舒服
np.set_printoptions(precision=4)
虽然使用 numpy 生成随机数,但是通过为随机数指定 seed 来保证我们的代码运行的效果和书中的内容得到效果一样
rand 方法
生成的随机数在 0-1 之间,并服从均匀分布
npr.rand(10)
array([0.8904, 0.9809, 0.0599, 0.8905, 0.5769, 0.7425, 0.6302, 0.5818,
0.0204, 0.21 ])
rand 也可以生成二维的随机数数组
npr.rand(5,5)
array([[0.8596, 0.6253, 0.9824, 0.9765, 0.1667],
[0.0232, 0.1607, 0.9235, 0.9535, 0.211 ],
[0.3605, 0.5494, 0.2718, 0.4606, 0.6962],
[0.5004, 0.7161, 0.526 , 0.0014, 0.3947],
[0.4922, 0.4029, 0.3543, 0.5006, 0.4452]])
利用一些小技巧可以让 rand 生成的随机数在 5-10 之间,并服从均匀分布, 这里用了一个小技巧,首先扩展分布空间,然后在将分布空间进行平移。
a = 5.
b = 10.
npr.rand(10) * (b - a) + a
array([6.3838, 6.2327, 5.868 , 9.833 , 9.7851, 7.9899, 8.6565, 6.7019,
5.4603, 7.3175])
npr.rand(5,5) * (b - a) + a
array([[7.5435, 5.4423, 7.6402, 9.9608, 6.9752],
[6.678 , 9.0273, 8.7717, 6.5653, 8.1702],
[7.702 , 6.484 , 5.5539, 6.5632, 7.2849],
[8.2947, 6.2713, 8.2055, 6.0006, 8.2881],
[8.8914, 8.898 , 8.0516, 6.545 , 8.4887]])
sample_size = 500
# 生成 sample_size 行 3 列的个数随机变量
rn1 = npr.rand(sample_size,3)
# 生成整数的随机数
rn2 = npr.randint(0,10,sample_size)
# 功能与 rand 一样,smaple 只能生成一维的随机数
rn3 = npr.sample(size=sample_size)
# 在有对给定数组进行又放回的随机采样
a = [0,25,50,75,100]
rn5 = npr.choice(a,size=sample_size)
然后我们用图表更直观将这些方法生成随机数表达出来
fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2,ncols=2,figsize=(10,8))
ax1.hist(rn1,bins=25,stacked=True)
ax1.set_title('rand')
ax1.set_ylabel('frequency')
ax2.hist(rn2,bins=25)
ax2.set_title('randint')
ax2.set_ylabel('frequency')
ax3.hist(rn3,bins=25)
ax3.set_title('sample')
ax3.set_ylabel('frequency')
ax4.hist(rn5,bins=10)
ax4.set_title('choice')

sample_size = 500
rn1 = npr.standard_normal(sample_size)
rn2 = npr.normal(100,20,sample_size)
rn3 = npr.chisquare(df=0.5,size=sample_size)
rn5 = npr.poisson(lam=1.0,size=sample_size)
fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2,ncols=2,figsize=(10,8))
ax1.hist(rn1,bins=25)
ax1.set_title('standard_normal')
ax1.set_ylabel('frequency')
# 看图正态分布的两边收尾会很快,其实实际总分布并没有真么快,例如有钱的人很多,股市上大涨大跌概率也不仅仅图上表现这些
ax2.hist(rn2,bins=25)
ax2.set_title('normal')
ax2.set_ylabel('frequency')
#
ax3.hist(rn3,bins=25)
ax3.set_title('chisquare')
ax3.set_ylabel('frequency')
# 期望值就是其自由度
ax4.hist(rn5,bins=10)
ax4.set_title('poisson')
# possion 期望就是 1
Text(0.5, 1.0, 'poisson')

网友评论