
import numpy as np
from pandas import Series

def MDD(financials, principal=None):
    ''' 最大回撤 与最大减子序列（非连续）
    '''
    if principal != None:
        financials = [principal] + financials

    finantials = Series(financials)
    history_max = finantials.expanding().max()
    dd2here = finantials / history_max
    dd2here_sorted = dd2here.sort_values()

    '''MDD始末时间和最大回撤率'''
    end_time, maxdd = dd2here_sorted.index[0], 1 - dd2here_sorted.iloc[0]
    start_time = finantials[finantials.index <= dd2here_sorted.index[0]].sort_values(ascending=False).index[0]

    # print('mdd', maxdd, 'start_time', start_time,'end_time', end_time)
    return (maxdd, start_time, end_time)

def curve(financials, principal=None):
    ''' 收益率曲线 '''
    if principal != None:
        financials = np.insert(financials, 0, principal)
        # financials.insert(0, principal)

    rate = []
    for i in range(1, len(financials)):
        rate.append((financials[i] - financials[i - 1]) / financials[i - 1])

    return rate

def Financial(financials, principal=None):
    if principal == None:
        principal = financials[0]

    benefit = financials - len(financials) * [principal]
    return benefit[1:]

def IRR(financials, principal=None):
    ''' 累计收益率 '''
    if principal == None:
        principal = financials[0]

    return (financials[-1] - principal) / principal

def IRR_adj_day(financials, principal=None):
    ''' 累计收益率，每天用相同金额投资 '''
    if principal == None:
        principal = financials[0]
    else:
        financials = [principal] + financials

    irr_list = []
    for i in range(1, len(financials)):
        irr_list.append((financials[i] - financials[i-1]) / principal)
    return irr_list

def IRR_acc_day(financials, principal=None):
    ''' 累计收益率，每天用相同金额投资 '''
    if principal == None:
        principal = financials[0]
    else:
        financials = [principal] + financials

    irr_list = []
    for i in range(1, len(financials)):
        irr_list.append(round((financials[i] - principal) / principal, 3))
    return irr_list

def SR(financials, principal=None):
    ''' 夏普比率 '''
    # if principal != None:
    #     financials = [principal] + financials
    #
    # rate = []   # 收益率
    # for i in range(1, len(financials)):
    #     # rate.append(financials[i] / financials[i - 1])
    #     rate.append((financials[i] - financials[i-1]) / financials[i-1])

    rate = curve(financials, principal)

    avg = np.mean(rate)
    variance = np.var(rate)
    return avg / variance


def gen_metrics(financials):
    metrics = {}

    metrics['financials'] = financials
    metrics['irr_list'] = IRR_acc_day(financials)
    metrics['IRR'] = IRR(financials)
    metrics['SR'] = SR(financials)
    metrics['MDD'] = MDD(financials)

    return metrics

if __name__ == '__main__':
    financials = [3, 4, 5, 2, 3, 1, 10, 7]
    res = MDD(financials)
    print(res)
    pass