Cannot find what's wrong

For the below code, I keep getting the result 0d0. I am expecting to get 1.3515415d0. Not sure where the bug is.

program test
print *, call_price(n = 5, s = 10d0, sigma = 2d-1, t = 1d0, r = 1d-1, k = 10d0) 

contains

function call_price(n, s, sigma, t, r, k)
  integer(4) :: n, i1, i2 
  real(8) :: s, sigma, t, r, k, call_price, delta_t, u, d, q, stock_tree(n + 1, n + 1), option_tree(n + 1, n + 1)
  delta_t = t/n
  stock_tree = 0d0
  u = exp(sigma*sqrt(delta_t))
  d = exp(-sigma*sqrt(delta_t))
  do i1 = 1, n + 1
    do i2 = 1, i1
      stock_tree(i1, i2) = s*u**(i2 - 1)*d**((i1 - 1) - (i2 - 1))
    end do
  end do
  q = (exp(r*delta_t) - d)/(u - d)
  option_tree = 0d0
  do i2 = 1, n + 1
    option_tree(n + 1, i2) = max(stock_tree(n + 1, i2) - k, 0d0)
  end do
  do i1 = n, 1
    do i2 = 1, i1
      option_tree(i1, i2) = ((1d0 - q)*option_tree(i1 + 1, i2) + q*option_tree(i1 + 1, i2 + 1))/exp(r*delta_t)
    end do
  end do
  call_price = option_tree(1, 1)
end function

end program

The line

do i1 = n, 1

is a zero-trip do loop for n > 1 and should be

do i1 = n, 1, -1

Then the code gives the answer you expected. I figured this out by seeing that call_price was set to option_tree(1,1), that option_tree had been set in a prior double loop, and adding a statement

print*,i1,i2,option_tree(i1,i2)

When that did not print anything I noticed the problem. Any code posted in a request for help should have implicit none (although a mistyped variable was not the problem here).

1 Like