"""Solve a conventional annual money-weighted return.

Only one initial outflow followed by non-negative annual inflows is supported. Irregular dates and multiple sign changes require different analysis.
All inputs are synthetic teaching examples. Run: python 45_conventional-money-weighted-return.py
"""
from tv_math import *

def annual_irr(flows):
    if len(flows)<2 or flows[0]>=0 or any(x<0 for x in flows[1:]) or not any(x>0 for x in flows[1:]):
        raise ValueError("Use one initial outflow and later non-negative inflows")
    def npv(rate):
        return sum(c/(1+rate)**i for i,c in enumerate(flows))
    low,high=-.99,10.0
    if npv(low)*npv(high)>0:
        raise ValueError("No root in the supported bracket")
    for _ in range(150):
        mid=(low+high)/2
        if npv(mid)>0:
            low=mid
        else:
            high=mid
    return (low+high)/2
rate=annual_irr([-1000,0,1210])
assert abs(rate-.1)<1e-12
assert abs(annual_irr([-1000,1100])-.1)<1e-12
try:
    annual_irr([-100,230,-132])
except ValueError:
    pass
else:
    raise AssertionError("Multiple-sign-change cash flows must be rejected")
print(rate)
