# -*- coding: utf-8 -*-

import shutil
import os
import utils
import pandas as pd
import numpy as np
import logging
import warnings
import datetime
import sklearn.tree
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
import random
import talib
import config

warnings.filterwarnings("ignore", category=UnicodeWarning)

available_field_list = ['卖五价', '卖四价', '卖三价', '卖二价', '卖一价',
                        '买一价', '买二价', '买三价', '买四价', '买五价',
                        '卖五量', '卖四量', '卖三量', '卖二量', '卖一量',
                        '买一量', '买二量', '买三量', '买四量', '买五量',
                        '开盘价', '最高价', '最低价', '收盘价',
                        '委比', '量比', '时点当日开盘', '时点当日最高',
                        '时点当日最低', '时点当日累计委比',
                        '成交量', '成交金额', '成交笔数']

logging.basicConfig(level=logging.DEBUG)


class CCILearn(object):
    def __init__(self, stock, train_date_list, test_date_list):
        self.stock = stock
        self.train_date_list = train_date_list
        self.test_date_list = test_date_list
        pass

    def _get_stock_df_30s(self, date_str):
        begin_date = utils.str_to_ts_date(date_str)
        end_date = utils.str_to_ts_date(date_str)
        trade_detail_list = utils.ts_remote_call_func('TradeDetails',
                                                      [begin_date, end_date, utils.str_utf8_to_gbk('5秒线')], {
                                                      # [begin_date, end_date, utils.str_utf8_to_gbk('秒线')], {
                                                          'StockID': self.stock,
                                                          'bRate': 2,  # 前复权
                                                          'RateDay': utils.str_to_ts_date('2017-05-26')
                                                      })
        row_size = len(trade_detail_list)
        if row_size == 0:
            return None
        df = utils.ts_list_to_dataframe(
            ts_list=trade_detail_list,
            columns=[('时间', '时间')] + zip(available_field_list, available_field_list),
            index_type=pd.DatetimeIndex
        )
        if not os.path.exists(os.path.join(config.DATA_ROOT, self.stock + '_5s')):
            os.mkdir(os.path.join(config.DATA_ROOT, self.stock + '_5s'))

        logging.debug('save %s.csv' % date_str)
        df.to_csv(os.path.join(config.DATA_ROOT, self.stock + '_5s', date_str + '.csv'))
        return df

    def _filter_and_extract_labeled_feature(self, date_str):
        df = self._get_stock_df_30s(date_str)[['最高价', '最低价', '收盘价']]

        # print df['最高价'].tolist()
        df['CCI'] = talib.CCI(df['最高价'].as_matrix(), df['最低价'].as_matrix(), df['收盘价'].as_matrix())
        print df

    def run(self):
        self._filter_and_extract_labeled_feature(self.train_date_list[0])
        pass


if __name__ == '__main__':
    stock = 'SZ002415'
    # start_date = '2016-06-01'
    date_list = utils.get_trade_date_str_list(start_date='2016-01-01')
    train_data_ratio = 0.5
    idx = int(len(date_list) * train_data_ratio)
    train_date_list, test_date_list = date_list[:idx], date_list[idx:]

    cci_learn = CCILearn(stock, train_date_list, test_date_list)
    for date_str in date_list:
        cci_learn._get_stock_df_30s(date_str)
