1

I am calculating couple of values for n=1,2,5,10,100,500 and 1000 and not sure how I can do this in more simple code. I wrote the code for n=1,2,5,..,1000 for each and every one and wondering if there is a way writing the code without repeating it?

dt <- T/n1 
T <- 1
sigma <- 0.2
S0 <- 100
K1 <- 1
r <- 0.05
p <- (exp(r*dt)-d)/(u-d)
u <- exp(sigma*(dt)^0.5)
d <- exp(-sigma*(dt)^0.5)
e <- exp(-r*T)
c1 <- gamma(1+n1)/(gamma(1+K1)*gamma(1+(n1-K1)))

##n = 1

n1 <- 1

for(i in 0:n1)
{
calculate1 <- c1*p^i*(1-p)^(n1-i)*(u^(i)*d^(n1-i)*S0-K1)
}

price1 <- e*calculate1
print(price1)

##n = 2
dt <- T/n2 
T <- 1
sigma <- 0.2
S0 <- 100
K2 <- 2
r <- 0.05
p <- (exp(r*dt)-d)/(u-d)
u <- exp(sigma*(dt)^0.5)
d <- exp(-sigma*(dt)^0.5)
e <- exp(-r*T)
c1 <- gamma(1+n2)/(gamma(1+K2)*gamma(1+(n2-K2)))
n2 <- 2

for(i in 0:n2)
{
  calculate2 <- c1*p^i*(1-p)^(n2-i)*(u^(i)*d^(n2-i)*S0-K2)
}

price2 <- e*calculate2
print(price2)

## I do the same thing for n=5,10,100,500 and 1000


pricesintable <- matrix(c(price1,price2,price5,price10, price100, price500,   price1000), ncol =1, byrow = TRUE)
colnames(pricesintable) <- c("Price")
rownames(pricesintable) <- c("1","2","5","10","100","500","1000")
pricesintable <- as.table(pricesintable)
print(pricesintable)

How can I make this more simple code?

R Yoda
  • 8,358
  • 2
  • 50
  • 87
Ella
  • 31
  • 2
  • 2
    Please consider improving your question by making the code reproducible so that we can execute and debug it (see https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). THX :-) – R Yoda Jun 04 '17 at 09:54
  • 1
    First impression to answer your question: Create a function containing your calculation code and the required input as parameters (e. g. `n`). Create a vector with all values of `n`. `lapply` over `n`... – R Yoda Jun 04 '17 at 09:56
  • Following up on @RYoda 's comment, what is n2? – G5W Jun 04 '17 at 11:28

0 Answers0