在R中绘制For循环的结果

时间:2015-08-01 00:52:05

标签: r for-loop plot

我正在尝试绘制For循环的结果,如下所示:

marketPrice = 100
strikePrice = 125

tau = 1

dividendYield = .03
interestRate = .02

sigma = .25

lowerMarketBound = 100
upperMarketBound = 150

stepIncrement = 5

callPrice = NULL
putPrice = NULL

plot(marketPrice, callPrice)

for (marketPrice in seq(from=lowerMarketBound, to=upperMarketBound,
 by=stepIncrement)){

d1 = ((log(marketPrice / strikePrice)) + ((interestRate + 
    (sigma**2/2)) * f_tau)) / (sigma * sqrt(tau))
d2 = d1 - (sigma * sqrt(tau))

print(marketPrice)

callPrice = marketPrice * pnorm(d1) - pnorm(d2) * strikePrice * 
    exp(1)^(-interestRate * tau)
putPrice = strikePrice * exp(1)^(-interestRate * tau) * pnorm(-d2) -     
    marketPrice * pnorm(-d1)

print (callPrice)
print (putPrice)
plot(marketPrice, callPrice)
}

代码的最后一行调用plot()。我期待看到marketPrice变量与callPrice变量的关系图。相反,我看到的情节只有循环的最后 marketPricecallPrice(在这种情况下,15031.46,分别地)。

有没有办法绘制For循环的所有结果?

1 个答案:

答案 0 :(得分:1)

您可以在循环期间将值存储在矩阵中,并在结尾处绘制整个系列。

tau = 1

dividendYield = .03
interestRate = .02

sigma = .25

lowerMarketBound = 100
upperMarketBound = 150
stepIncrement = 5
marketPrice = seq(from=lowerMarketBound, to=upperMarketBound,
                  by=stepIncrement)
strikePrice = 125



callPrice = rep(0,length(marketPrice))
putPrice = NULL

for (i in 1:length(marketPrice)){

  d1 = ((log(marketPrice[i] / strikePrice) + (interestRate + (sigma**2/2)) * tau) / (sigma * sqrt(tau)))
  d2 = d1 - (sigma * sqrt(tau))

  print(marketPrice[i])

  callPrice[i] = marketPrice[i] * pnorm(d1) - pnorm(d2) * strikePrice * exp(1)^(-interestRate * tau)
  putPrice = strikePrice * exp(1)^(-interestRate * tau) * pnorm(-d2) - marketPrice[i] * pnorm(-d1)

  print (callPrice[i])
  print (putPrice)
}

plot(marketPrice, callPrice)