Reputation: 2533
I'm trying to plot the results of a For Loop, as follows:
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)
}
The last line of the code calls plot()
. I was expecting to see a plot of the marketPrice
variable vs. the callPrice
variable. Instead, I'm seeing a plot of only the LAST marketPrice
and callPrice
of the loop (in this case, 150
and 31.46
, respectively).
Is there a way to plot all of the results of a For Loop?
Upvotes: 1
Views: 1127
Reputation: 36
You could store the values in a matrix during the loop and plot the whole series at the end.
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)
Upvotes: 2