【问题标题】:Plotting the results of a For Loop in R在 R 中绘制 For 循环的结果
【发布时间】:2015-08-01 00:52:05
【问题描述】:

我正在尝试绘制 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 变量的关系图。相反,我看到的只是循环的 LAST marketPricecallPrice(在本例中,分别为 15031.46)。

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

【问题讨论】:

标签: r for-loop plot


【解决方案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)

【讨论】:

    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2020-02-26
    相关资源
    最近更新 更多