#coding:utf-8
from datetime import datetime as dt

# 用get_market_data订阅历史和实时行情

import time

import pandas as pd
from xtquant import xtdata

def real_price(data):
    for i in data:
        list.append(i)
        xtdata.unsubscribe_quote(id)
        print(i)
        print(list)


if __name__=='__main__':
    '''
    from xtquant import xtdata
    s = '000001.SZ'
    # 实际使用时，该接口每天盘后执行一次即可
    # 该接口会下载历史行情并落地到本地，随后即可通过xtdata.get_local_data接口调用本地行情
    # 同时间、同股票、同周期的行情下载一次即可，
    xtdata.download_history_data(s, '1d','','')
    xtdata.download_history_data('000001.SH', '1d','','')  
    data = xtdata.get_market_data([], [s], '1d', end_time='', count=-1, dividend_type='back')
    # data2 = xtdata.get_local_data([], [s], '1d', end_time='', count=2,dividend_type='back')
    print('data from get_local_data:\n')
    df = pd.DataFrame()
    for column in data:
        if column in ['time', 'open', 'high', 'low', 'close', 'volume', 'amount']:
            # print(f"              {column}\n {data[column].head()}\n")
            print(column, data[column].T)
            df=pd.concat([df, data[column].T],axis=1)
    df.columns = ['time', 'open', 'high', 'low', 'close', 'volume', 'amount']
    df['time']=df['time'].apply(lambda x: dt.fromtimestamp(x / 1000.0))
    print('!!!!!!!', df)
    # print(df['time'].apply(lambda x: dt.fromtimestamp(x / 1000.0)))

    df2 = pd.concat([data[i].T for i in ['time', 'open', 'high', 'low', 'close', 'volume', 'amount']], axis=1)
    df2.columns = ['time', 'open', 'high', 'low', 'close', 'volume', 'amount']
    df2['time']=df2['time'].apply(lambda x: dt.fromtimestamp(x / 1000.0))
    print('>>>>>>>>>>>', df2)
    print(df.index)
    exit()
    #
    # for column in data2:
    #     print(f"              {column}\n {data2[column].head()}\n")

'''

    list=[]
    stocks = xtdata.get_stock_list_in_sector('沪深A股')
    id = xtdata.subscribe_whole_quote(stocks, callback=real_price)
    print(list)
    xtdata.run()
    print(list)