IRC可以直接使用straight MC来计算。我们可以生成了大量的PnL scenarios,并读出了99.9% quantile,为了估计MC错误,我们必须应用批处理apply batching(为什么?原因求解)
straight MC的收敛缓慢:only a small percentage of the scenarios hit the 99.9% tail.
nn, rho = 100, .7
# MC路径
nsim = 40000
p = .99*np.ones(nn)
p[:5] = .95
b = 20
lgdl = 5e6
lgdh = 9e6
def irc0(nsim) :
# (101, 40000) 的随机array
es = np.random.normal(size=[nn+1, nsim])
# (100, 40000) 的随机array,再做了转置(40000, 100)
xs = np.array([np.sqrt(rho)*es[0, :] + np.sqrt(1-rho)*e for e in es[1:, :]]).T
#(40000,) 的随机array,5e6 至 9e6之间
lgd = np.random.uniform(lgdl, lgdh, size=nsim)
# 比较 p=0.99 和 xs的大小球相互违约概率, 求出违约的损失PnL
pnls = np.sum(np.greater(norm.cdf(xs), p), 1)*lgd
# 返回的是99.9 的损失percentile
return np.percentile(pnls, 99.9), pnls
tic = time.clock()
# 前20个的percentile
ircs0 = [(irc0(nsim))[0] for i in range(b)]
t0 = time.clock() - tic
运行时间大概是10秒,返回了20个percentile
df = pd.DataFrame([nsim, np.mean(ircs0), np.std(ircs0)/np.mean(ircs0), t0/b],
index=['paths', 'value', 'rel error', 'run time(s)'],
columns=['IRC'])
fmt.displayDF(df.T, "3g", 4)