
# -*- 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

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

available_field_list = [ '卖五量', '卖四量', '卖三量', '卖二量', '卖一量',
                 '买一量', '买二量', '买三量', '买四量', '买五量',
                 '开盘价', '最高价', '最低价', '收盘价',
                 '成交量', '成交金额', '成交笔数']


def get_stock_df(stock, date_str, cycle='30秒线'):
    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, '30秒线'.decode('utf8').encode('gbk')], {
            'StockID': stock,
        })
    row_size = len(trade_detail_list)
    if row_size == 0:
        return None
    return utils.ts_list_to_dataframe(
        ts_list=trade_detail_list,
        columns=[('时间', '时间')] + zip(available_field_list, available_field_list),
        index_type=pd.DatetimeIndex
    )


def get_labeled_data_by_date(stock, date_str):
    df = get_stock_df(stock, date_str)
    df = df.loc[(df > 0.1).all(axis=1), :]  # 剔除所有含0的数据点

    # 折算“价格”相关，到百分比
    price_field_list = ['开盘价', '最高价', '最低价', '收盘价']
    for price_field in price_field_list:
        df[price_field] = (df[price_field] - df['时点当日开盘']) * 100 / df['时点当日开盘']

    volume_field_list = ['卖五量', '卖四量', '卖三量', '卖二量', '卖一量',
                  '买一量', '买二量', '买三量', '买四量', '买五量']
    volume_sum_series = df[volume_field_list].sum(axis=1)
    for volume_field in volume_field_list:
        df[volume_field] = df[volume_field] * 100 / volume_sum_series
    for minute in [1, 2, 5]:
        calc_minute_stats(df, minute)
    return df


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    stock = 'SZ002415'
    split_date = '2016-06-01'

    date_list = utils.get_trade_date_str_list()
    training_date_list = filter(lambda x: x.startswith('2016-01'), date_list)
    testing_date_list = filter(lambda x: x.startswith('2016-02'), date_list)
    
    