from scipy.optimize import fsolve


class ARR:
    '''Average Rate of Return, 平均收益率
    '''
    def __init__(self, investment_amount, numbers_of_years, interest_rate, future_value):
        '''
        Argument:
            - investment_amount: float, 投资额
            - numbers_of_years: Tuple[int], 领取时间与领取期限
            - interest_rate: float, 领取期限内的利率
            - future_value: float, 终值
        '''
        self._ia = investment_amount
        self._nys = numbers_of_years[:2]
        self._ir = interest_rate
        self._fv = future_value

    def monthly(self):
        raise NotImplementedError

    def yearly(self):
        func = lambda i: self._fv + self._ia*self._ir*self._s_ddot(self._nys[1], i) \
            - self._ia*(1+i)**sum(self._nys)
        return fsolve(func, 1)[0]

    def _s_ddot(self, n, i):
        '''n 期标准期初年金的终值
        '''
        return ((1+i)**n-1) / (i/(i+1))


if __name__ == '__main__':
    # 小金猪定期年金
    for args in (
        (1_000, (5,  5), 0.02, 1_349),
        (2_000, (5,  5), 0.02, 2_698),
        (3_000, (5,  5), 0.02, 4_047),
        (1_000, (5, 15), 0.02, 1_753),
        (2_000, (5, 15), 0.02, 3_506),
        (3_000, (5, 15), 0.02, 5_259),
    ):
        print(ARR(*args).yearly())
