Hello, I am a new user of Julia and the Optim package, and I am looking for some guidance on a simple piece of code.
I have given my simple implementation of the equivalent of Excel XIRR (extended internal rate of return) function using both Optim and Roots packages. The implementation using Optim package is a lot faster than the Roots package (median time:32.300 μs (0.00% GC vs 113.100 μs (0.00% GC), but still feels slow when running it on a large cash flow or calling it in a loop for multiple calculations. I will appreciate, guidance on:
Question 1: In the Optim package, I had a to take the function to the power of 2, i.e.
result = optimize(x -> f(x)^2,0.0,1.0,Brent()) as otherwise, I was not getting sensible answers and Brent is the only method that seems to work on this function. Would someone be able to help me understand how I can use other algorithms in the Optim package as simply changing the name of algorithm does not work and why I have to take a function to the power of 2 in this case?
Question 2: My implementation of the xirr function is obviously basic, but I would like to understand if in terms of Julia code it is efficient or what I can do to make it faster to run. Again, will appreciate any guidance.
using Optim, Dates, DayCounts, Roots, BenchmarkTools function xnpv(xirr,cf,dates) interval = map(d -> DayCounts.yearfrac(dates,d,DayCounts.Actual365Fixed()),dates) sum(cf./(1+xirr).^interval) end function xirr(xnpv,cf,dates) f(x) = xnpv(x,cf,dates) result = optimize(x -> f(x)^2,0.0,1.0,Brent()) return result.minimizer end function xirr_roots(xnpv,cf,dates) f(x) = xnpv(x,cf,dates) return fzero(f,[0.0,1.0]) end dates = Date(2012,12,31):Year(1):Date(2016,12,31) cf = [-100,10,10,10,110] @benchmark optimR = xirr(xnpv,cf,dates) @benchmark Roots = xirr_roots(xnpv,cf,dates)
Run time (Optim and Roots)