Hi mighty StackOverflow, I have been following this post's approach to implement an XIRR function in my small personal finance project and have been running into an Overflow Error.
This is the original code:
def xnpv(rate, values, dates, daycount=365):
daycount = float(daycount)
d0 = dates[0] # or min(dates)
# NB: this xnpv implementation discounts the first value LIKE EXCEL
# numpy's npv does NOT, it only starts discounting from the 2nd
return sum([vi / (1.0 + rate) ** (di - d0).days / daycount for vi, di in zip(values, dates)])
def xirr(values, dates, daycount=365, guess=0, maxiters=10000, a=-100, b=1e10):
# a and b: lower and upper bound for the brentq algorithm
cf = np.array(values)
if np.where(cf < 0, 1, 0).sum() == 0 | np.where(cf > 0, 1, 0).sum() == 0:
# if the cashflows are all positive or all negative, no point letting the algorithm
# search forever for a solution which doesn't exist
return np.nan
try:
output = scipy.optimize.newton(lambda r: xnpv(r, values, dates, daycount),x0=guess, maxiter=maxiters, full_output=True, disp=True)[0]
except RuntimeError:
try:
output = scipy.optimize.brentq(lambda r: xnpv(r, values, dates, daycount),
a=a, b=b, maxiter=maxiters, full_output=True, disp=True)[0]
except:
result = scipy.optimize.fsolve(lambda r: xnpv(r, values, dates, daycount),
x0=guess, maxfev=maxiters, full_output=True)
if result[
2] == 1: # ie if the solution converged; if it didn't, result[0] will be the last iteration, which won't be a solution
output = result[0][0]
else:
output = np.nan
return output
What I have tried is to set everything as a Decimal
but this only shifted a type error into the line of scipy.optimize.newton
as there seems to be internal multiplication with the float 1.0 which I can not prevent.
For any tips on how to avoid the Overflow error in the xnpv function or anything else, I would be very grateful. Best J