# -*- encoding:utf-8 -*-
import numpy as np
from keras.models import load_model
import joblib


def read_data(path):
    day_lines = {}
    with open(path) as f:
        for line in f.readlines()[:]:
            line = eval(line.strip())
            date = str(line[-1][-1])
            if date in day_lines:
                day_lines[date].append(line)
            else:
                day_lines[date] = [line]
    # print(len(day_lines['20191230']))
    return day_lines


def predict(file_path='', model_path='15min_dnn_seq'):
    day_lines = read_data(file_path)
    print('数据读取完毕')

    models = []
    for x in range(0, 12):
        models.append(load_model(model_path + '_' + str(x) + '.h5'))
    estimator = joblib.load('km_dmi_18.pkl')
    print('模型加载完毕')

    items = sorted(day_lines.keys())
    for key in items:
        # print(day)
        lines = day_lines[key]

        up_num = 0
        down_num = 0
        x = 24 # 每条数据项数
        k = 18 # 周期
        for line in lines:
            v = line[1:x*k + 1]
            v = np.array(v)
            v = v.reshape(k, x)
            v = v[:,4:8]
            v = v.reshape(1, 4*k)
            # print(v)
            r = estimator.predict(v)

            train_x = np.array([line[:-1]])
            result = models[r[0]].predict(train_x)

            if result[0][3] > 0.5 or result[0][4] > 0.5:
                down_num = down_num + 1
            elif result[0][1] > 0.5 or result[0][2] > 0.5:
                up_num = up_num + 0.5  # 乐观调大 悲观调小

            # if result[0][0] > 0.5 or result[0][1] > 0.5:
            #     if r[0] in [0,2,3,4,5,9,10,11]:
            #         up_num = up_num + 1
            #     elif r[0] in [8]:
            #         up_num = up_num + 0.6
            #     else:
            #         up_num = up_num + 0.4
            # if result[0][3] > 0.5 or result[0][4] > 0.5:
            #     if r[0] in [4,6,]:
            #         down_num = down_num + 1
            #     elif r[0] in [0,1,3,7,8,]:
            #         down_num = down_num + 0.6
            #     else:
            #         down_num = down_num + 0.4

        print(key, int(up_num), int(down_num), (down_num*1.2 + 2)/(up_num*1.2 + 2))


if __name__ == '__main__':
    # predict(file_path='D:\\data\\quantization\\stock6_5_test.log', model_path='5d_dnn_seq.h5')
    # predict(file_path='D:\\data\\quantization\\stock9_18_20200220.log', model_path='18d_dnn_seq.h5')
    # predict(file_path='D:\\data\\quantization\\stock9_18_2.log', model_path='18d_dnn_seq.h5')
    predict(file_path='D:\\data\\quantization\\stock11_18d_20200303.log', model_path='11_18d_dnn_seq')
    # predict(file_path='D:\\data\\quantization\\stock12_18d_20200226.log', model_path='11_18d_dnn_seq')
    # predict(file_path='D:\\data\\quantization\\stock9_18_4.log', model_path='18d_dnn_seq.h5')
