从回归绘制拟合值

时间:2021-05-03 11:32:02

标签: r regression

嘿,我在 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)

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

1 个答案:

答案 0 :(得分: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")

enter image description here

相关问题