mcEstimate

首发版本:3.00.6.4

语法

mcEstimate(samples, [confidenceLevel=0.95])

详情

对已有的 Monte Carlo 样本计算均值、无偏样本方差、均值标准误和正态渐近置信区间。

注:
如果样本来自对偶模拟,调用前必须先计算每对 f(Z) 与 f(-Z) 的平均值,再将这些平均值传入。本函数不会自动识别或重建对偶配对。

参数

samples 数值向量或数值矩阵,计算前转换为 DOUBLE 类型。输入为数值向量时,表示单输出样本;为数值矩阵时,表示多输出样本,每行表示一个样本,每列表示一个待估计目标。样本数必须不小于 2,矩阵至少包含 1 列。所有元素均须为非 NULL 的有限数值。

confidenceLevel 可选参数,DOUBLE 标量,指定置信水平,默认值为 0.95,取值范围为 (0,1)。

返回值

返回一个字典,包含样本的均值、无偏样本方差、均值标准误和正态渐近置信区间等:

键 类型与形式 说明
"estimate" DOUBLE 标量或向量 样本均值
"variance" DOUBLE 标量或向量 样本方差
"stdError" DOUBLE 标量或向量 标准误
"confidenceLower" DOUBLE 标量或向量 置信区间下限
"confidenceUpper" DOUBLE 标量或向量 置信区间上限
"confidenceLevel" DOUBLE 标量 置信水平
"sampleCount" LONG 标量 样本数量,向量长度或矩阵行数。
  • samples 为数值向量时,前五个字段为 DOUBLE 标量;samples 为数值矩阵时,为与输入列数相同的 DOUBLE 向量。

  • 置信区间为估计值加减标准正态分布相应分位数与标准误的乘积,分位点为 (1 + confidenceLevel) / 2。

  • 多列样本逐列计算边际置信区间,不表示所有输出同时覆盖的联合置信区间。

例子

例 1. 计算单输出样本的统计量

第一个调用对 5 个样本做统计,第二个调用把两列样本按 99% 置信水平逐列估计。结果依次为均值、无偏样本方差、标准误、样本数,以及多列估计的均值与置信区间上下限。

stats = mcEstimate(1.0 2.0 3.0 4.0 5.0)
samples = matrix(1.0 2.0 3.0 4.0, 10.0 20.0 30.0 40.0)
multi = mcEstimate(samples, 0.99)
[stats["estimate"], stats["variance"], stats["stdError"], stats["sampleCount"], multi["estimate"], multi["confidenceLower"], multi["confidenceUpper"]]
// output: [3, 2.5, 0.707106781186548, 5, [2.5, 25], [0.837309334113677, 8.37309334113677], [4.162690665886324, 41.626906658863234]]

例 2. 逐列统计多个输出

输入为 4 行 2 列的矩阵,指定 99% 置信水平。返回两列的均值。

samples = matrix(1.0 2.0 3.0 4.0, 10.0 20.0 30.0 40.0)
result = mcEstimate(samples=samples, confidenceLevel=0.99)
result["estimate"]
// output: [2.5, 25]

例 3. 对偶样本必须配对后再统计

指定 antithetic=true 时,相邻两条路径互为对偶,构成一个统计单元。若把全部样本当独立样本直接传入,估计值不变,但标准误会被高估,置信区间偏宽。正确做法是先按配对求平均,再把平均值传入。

def gbmEvolve(t, state, dt, noise, p) {
    return state * exp((p["rate"] - 0.5 * p["volatility"] * p["volatility"]) * dt + p["volatility"] * sqrt(dt) * noise)
}
p = dict(STRING, ANY)
p["rate"] = 0.03
p["volatility"] = 0.2
options = dict(STRING, ANY)
options["seed"] = 42
options["antithetic"] = true
options["batchSize"] = 5000
simulation = mcSimulate(gbmEvolve, 100.0, 0..12 / 12.0, 20000, 1, p, options)
terminal = flatten(simulation["paths"][size(simulation["paths"]) - 1])
samples = exp(-0.03) * max(terminal - 100.0, 0.0)
naive = mcEstimate(samples)
idx = 0..(size(samples) / 2 - 1)
pairedSamples = (samples[2 * idx] + samples[2 * idx + 1]) / 2.0
paired = mcEstimate(pairedSamples)
[naive["estimate"], paired["estimate"], naive["stdError"], paired["stdError"]]
// output: [9.350371878604676, 9.350371878604683, 0.099102747780388, 0.073832573115757]

例 4. 不同置信水平下的区间宽度

内部风控与监管报送常用不同口径。点估计与标准误不随置信水平变化,只有区间端点移动。

samples = 1.2 0.8 1.5 1.1 0.9 1.3 1.0 1.4
wide = mcEstimate(samples, 0.99)
narrow = mcEstimate(samples, 0.90)
[wide["confidenceLower"], wide["confidenceUpper"], narrow["confidenceLower"], narrow["confidenceUpper"]]
// output: [0.926926638731427, 1.373073361268572, 1.007551497355305, 1.292448502644694]

相关函数: monteCarlo, mcSimulate