为不完全分布拟合Student-t分布:求拟合值的技术问询
解决Student-t分布拟合后的拟合值获取问题
我懂你的困扰啦——已经用MASS包的fitdistr函数算出了Student-t分布的拟合参数,但不知道怎么把这些参数转换成对应你那组strikes序列的拟合密度值对吧?
先给你提个小细节:示例代码里有个笔误,temp$strike[i]应该写成temp$strikes[i](少了个s),不然运行时会报错哦。
接下来咱们直接说解决方案:拿到拟合参数后,我们可以用R自带的Student-t分布概率密度函数dt()来计算拟合值。具体步骤很简单:
- 从
fitted_parameters里提取三个关键参数:位置参数m、尺度参数s、自由度df; - 对每个
strike值做标准化转换((x - m)/s),传入dt()得到标准t分布的密度,再除以尺度参数s,就能得到对应非标准t分布的拟合密度值了。
下面是修改后的完整代码,包含拟合值的计算逻辑:
# 生成模拟数据 temp = matrix(nrow=1000, ncol=3) colnames(temp) = c("strikes", "first_density", "mulitply_first_density") temp = as.data.frame(temp) temp$strikes = seq(1000,2000,length=1000) temp$first_density = runif(1000,max=0.006, min=1e-10) temp$mulitply_first_density = temp$first_density*1000000 # 生成样本向量(修正笔误:strike -> strikes) vec = vector() for (i in 1:nrow(temp)) { vec = c(vec, rep(temp$strikes[i], temp$mulitply_first_density[i])) } # 加载MASS包并拟合参数 library("MASS") fitted_parameters = fitdistr(vec, "t") # 提取拟合得到的参数 m = fitted_parameters$estimate["m"] s = fitted_parameters$estimate["s"] df = fitted_parameters$estimate["df"] # 计算每个strike对应的拟合密度值 temp$fitted_density = dt((temp$strikes - m)/s, df) / s # 查看前几行的原始密度和拟合密度对比 head(temp[, c("strikes", "first_density", "fitted_density")])
要是你用fitdistrplus包的话,除了用同样的dt()方法计算拟合值,还可以用denscomp()函数直接可视化原始密度和拟合密度的对比,不过单独提取数值的话,还是上面的方法最直接。
如果想直观看看拟合效果,还可以用ggplot2画个对比图:
library(ggplot2) ggplot(temp, aes(x=strikes)) + geom_line(aes(y=first_density, color="原始密度")) + geom_line(aes(y=fitted_density, color="拟合密度")) + labs(x="执行价格", y="密度", color="类型") + theme_minimal()
这样就能清晰看到拟合的Student-t分布和你原始密度的匹配情况啦~
内容的提问来源于stack exchange,提问作者DomingoBrown
相关产品推荐
相关产品推荐

