My current favourite
using ForwardDiff, ReverseDiff
function callprice(r, T, σ, S₀, K; n = 100)
memo = Dict(); dt = T / n; u = exp(σ * √dt); q = (exp(r * dt) - 1/u) / (u - 1/u)
function helper(i, pos)
get!(memo, (i, pos)) do
if i == n; max(S₀ * u^pos - K, 0) else exp(- r * dt) * (q*helper(i+1, pos+1) + (1-q)*helper(i+1, pos-1)) end end end
helper(0, 0) end
(ForwardDiff.derivative(s -> callprice(r, T, σ, s, K), S₀), ReverseDiff.gradient(s -> callprice(r, T, σ, s[1], K), [S₀]))
Automatic differentiation through a memoized recursive function … would probably not even have tried that in any other language.
Unfortunately, I did not get it to work when using an array instead of a dictionary as the memo-table. Maybe I should have another look at Zygote buffers …