Hi everyone,
I was playing with a simple case of option pricing when I discovered this strange behavior.
After adding an extra conditional statement, the performance of the function actually become faster.
This is somewhat against the intuition, I’m hoping someone can help me to explain what’s happening under the hood.
Thanks
function euroOption(numSims, S, K, r, σ, T, CorP)
S_adj = S * exp((r - σ^2.0/2.0)*T)
psum = 0.0
if CorP == 1
for i in 1:numSims
St = S_adj * exp(σ*sqrt(T)*randn())
prem = St-K
psum += ifelse(prem > 0.0, prem, 0.0)
end
elseif CorP == 0
for i in 1:numSims
St = S_adj * exp(σ*sqrt(T)*randn())
prem = K-St
psum += ifelse(prem > 0.0, prem, 0.0)
end
else
println("invalid option type")
return 0.0
end
price = psum / numSims * exp(-r*T)
return price
end
function euroOption1(numSims, S, K, r, σ, T)
S_adj = S * exp((r - σ^2.0/2.0)*T)
psum = 0.0
for i in 1:numSims
St = S_adj * exp(σ*sqrt(T)*randn())
prem = St-K
psum += ifelse(prem > 0.0, prem, 0.0)
end
price = psum / numSims * exp(-r*T)
return price
end
julia> @time euroOption(10^8, 100.0, 110.0, 0.05, 0.2, 1.0, 1)
1.718544 seconds (35.06 k allocations: 1.771 MiB)
6.041585176794043
julia> @time euroOption(10^8, 100.0, 110.0, 0.05, 0.2, 1.0, 1)
1.813658 seconds (6 allocations: 192 bytes)
6.039173673272666
julia> @time euroOption1(10^8, 100.0, 110.0, 0.05, 0.2, 1.0)
2.046597 seconds (25.51 k allocations: 1.317 MiB)
6.039447950343969
julia> @time euroOption1(10^8, 100.0, 110.0, 0.05, 0.2, 1.0)
2.043858 seconds (6 allocations: 192 bytes)
6.039694854595267