# -*- coding: utf-8 -*-
"""
Created on 20180313

@author: Matthew
"""

import numpy as np
from matplotlib import pyplot as plt
import datetime
import matplotlib.pyplot as plt

from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
#mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']    # 指定默认字体：解决plot不能显示中文问题
mpl.rcParams['axes.unicode_minus'] = False           # 解决保存图像是负号'-'显示为方块的问题



def anualizedreturn(netvalue):
    '''
    年化收益
    ''' 
    myreturn = ( netvalue[-1] - netvalue[0] ) / netvalue[0]
    annualReturn = str( round( ((1+myreturn)**(250/len(netvalue)) - 1) * 100 , 2)) + '%'
    print( '年化收益为 %s'%annualReturn)
    return annualReturn

def growthPercent(netvalue):
    '''
    策略涨幅
    '''
    print('期间涨幅为 ' + str( round( ( netvalue[-1] - netvalue[0] ) / netvalue[0] * 100 , 2)) + '%')
    return str( round( ( netvalue[-1] - netvalue[0] ) / netvalue[0] * 100 , 2)) + '%' 

def maxdrawdown(netvalue):
    i = np.argmax( (np.maximum.accumulate(netvalue) - netvalue ) / np.maximum.accumulate(netvalue) ) # end of the period
    #print('i:', i)
    j = np.argmax( netvalue[:i] )
    drawdown = ( 1 - netvalue[i] / netvalue[j] )
    print('最大回撤为 ' + str(round(drawdown*100,2)) + '%')
    return str(round(drawdown*100,2)) + '%'

def maxdrawdown2(netvalue):
    '''
    我的方法更实用
    最大回撤，当前点，历史最高点，
    如果当前点在历史最高点以下，算出之间的降幅，只保留最大的那个降幅
    如果当前点在历史最高点以上，不做任何计算，

    '''
    index = 0
    drawdown = 0
    for dot in netvalue:
        highestDot = max(netvalue[:index]) if index is not 0 else netvalue[0]
        if dot >= highestDot:
            index += 1 
            continue
        elif dot < highestDot and (dot - highestDot)/highestDot < drawdown:
            drawdown = (dot - highestDot)/highestDot
            index += 1
    print('最大回撤为 ' + str(round(drawdown*100,2)) + '%')
    return str(round(drawdown*100,2)) + '%'


def evaluator(strategyID,BTRecords,indexRecords,plot):
    '''
    indexRecords: list of index objs
    self.BTRecords[oneDay] = dict()
    self.BTRecords[oneDay]['positionList'] = positionList
    self.BTRecords[oneDay]['totalValue'] = totalValue
    self.BTRecords[oneDay]['cash'] = cash
    self.BTRecords[oneDay]['positionListValue'] = positionListValue
    '''

    
    BTtradingDays = []
    totalValue = []
    cash = []
    positionListValue = []

    for day,value in BTRecords.items():
        BTtradingDays.append(day)
        totalValue.append(value['totalValue'])
        cash.append(value['cash'])
        positionListValue.append(value['positionListValue'])

    BTNetvalue = [x/totalValue[0] for x in totalValue]
    cashNetValue = [x/cash[0] for x in cash]

    # positionvalue is 0 initially
    positionListNetValue = [x/cash[0] for x in positionListValue]


    print('\n策略评价：')
    growthPercent(BTNetvalue)
    anualizedreturn(BTNetvalue)
    maxdrawdown2(BTNetvalue)


    print('\n同期指数评价：')
    #print(type(indexRecords),indexRecords)
    indexNetvalue = [x.ClosePrice/indexRecords[0].ClosePrice for x in indexRecords]
    indexDate = [x.TradeDate for x in indexRecords]
    growthPercent(indexNetvalue)
    anualizedreturn(indexNetvalue)
    maxdrawdown2(indexNetvalue)

    '''
    print('len(BTtradingDays): ',len(BTtradingDays),BTtradingDays[:5])
    print('len(BTNetvalue): ',len(BTNetvalue))
    print('len(indexDate): ',len(indexDate),indexDate[:5])
    print('len(indexNetvalue): ',len(indexNetvalue))
    print('difference in days: ', set(indexDate) - set(BTtradingDays))
    '''
    '''
    print('\n写入文件：')
    with open('./Strategy Records/strategy_%s.txt'%strategyID,'a+') as f:
        f.write('--------' + '策略评估' + '----------\n')
        f.write('期间涨幅: %s\n'%growthPercent(BTNetvalue))
        f.write('年化收益: %s\n'%anualizedreturn(BTNetvalue))
        f.write('最大回撤: %s\n'%maxdrawdown2(BTNetvalue))

        f.write('--------' + '指数对比' + '----------\n')
        f.write('期间涨幅: %s\n'%growthPercent(indexNetvalue))
        f.write('年化收益: %s\n'%anualizedreturn(indexNetvalue))
        f.write('最大回撤: %s\n'%maxdrawdown2(indexNetvalue))
    '''
    if plot == True:  
        dates = [datetime.datetime.strptime(x,'%Y-%m-%d') for x in BTtradingDays]
        #print('%0.0f %0.0f %0.0f %0.0f %0.0f'%(len(dates),len(BTNetvalue),len(cashNetValue),len(positionListNetValue),len(indexNetvalue)))
        plt.plot(dates,BTNetvalue,'r-',dates,cashNetValue,'g-',dates,positionListNetValue,'y.',dates,indexNetvalue,'b--',)
        plt.ylabel('净值')
        plt.xlabel('时间')
        plt.axis('tight')
        plt.legend(['策略','现金','持仓','指数'])
        plt.grid()
        plt.show()

if __name__ == '__main__':
    netvalue = [1,0.5,1,2,3,1]
    netvalue = [1,1,1.01,1.03,0.4,100,10]
    #maxdrawdown(netvalue)
    maxdrawdown2(netvalue)




