【问题标题】:Plotting fitted values from regression从回归中绘制拟合值
【发布时间】:2021-05-03 11:32:02
【问题描述】:

嘿,我在 R 中有以下代码

S0 = 40
r = log(1 + 0.07)
sigma = 0.3
K = 45
n_steps_per_year = 4
dt = 1 / n_steps_per_year
T = 3
n_steps = n_steps_per_year * T
R = n_paths
Q = 70
P = 72
n_paths = P * Q
d = exp(-r * dt)

N = matrix(rnorm(n_paths * n_steps, mean = 0, sd = 1), n_paths, n_steps)
  
paths_S = matrix(nrow = n_paths, ncol = n_steps + 1, S0)  
  
for(i in 1:n_paths){
  for(j in 1:n_steps){
    paths_S[i, j + 1] = paths_S[i, j] * exp((r - 0.5 * sigma ^ 2) * dt + sigma * sqrt(dt) * N[i, j])
  }
}

I = apply(K - paths_S, c(1,2), max, 0)
V = matrix(nrow = n_paths, ncol = n_steps + 1)
V[, n_steps + 1] = I[, n_steps + 1]
dV = d * V[, n_steps + 1]
model = lm(dV ~ poly(paths_S[, n_steps], 10))

pred = predict(model, data.frame(x = paths_S[, n_steps]))
plot(paths_S[, n_steps], d * V[, n_steps + 1])
lines(paths_S[, n_steps], pred)

但是当我运行最后两行时,我会得到非常奇怪的情节(多行而不是一行)。怎么回事?

【问题讨论】:

  • 您要绘制什么类型的线?这是正常的,因为您正在使用您提供的坐标绘制一条线,因此它将根据坐标的顺序逐个连接每个点

标签: r regression


【解决方案1】:

您没有提供n_paths,我们假设:

n_paths = 7
set.seed(111)

然后运行你的代码,在你绘图之前,你需要在绘图之前订购你的 x 值:

o = order(paths_S[,12])
plot(paths_S[o, n_steps], d * V[o, n_steps + 1],cex=0.2,pch=20)
lines(paths_S[o, n_steps], pred[o],col="blue")

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 2022-11-04
    • 2014-05-16
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2019-12-06
    • 2020-07-24
    相关资源
    最近更新 更多