量化交易之回测篇 - back tester - 基于天勤的数据端备用方案

import re

import warnings
warnings.filterwarnings('ignore')

from tqz_extern.json_operator import TQZJsonOperator

TIME_GAP = 8 * 60 * 60 * 1000000000


class TQZTianQinClient:
    """
    天勤接口 每次只能拉取单一合约的数据!
    """

    __tq_futures = None

    def __init__(self, account: str = "xxxxxxx", pass_word: str = "xxxxxxx"):
        self.api = TqApi(auth=TqAuth(account, pass_word))

        if TQZTianQinClient.__tq_futures is None:
            TQZTianQinClient.__tq_futures = self.api.query_quotes(ins_class="FUTURE", expired=False)


    def query_history_ticks(self, tq_future: str, tq_data_length: int = 8964):
        assert tq_future in TQZTianQinClient.__tq_futures, f'bad tq_future: {tq_future}'

        ticks = self.api.get_tick_serial(symbol=tq_future, data_length=tq_data_length)
        self.api.close()

        return ticks


    def query_single_quote(self, tq_future: str) -> dict:
        result = self.api.get_quote(symbol=tq_future)
        self.api.close()

        return result  # noqa


    def query_history_bars(self, tq_future: str, tq_duration_seconds: int, tq_data_length: int = 8964):
        assert tq_future in TQZTianQinClient.__tq_futures, f'bad tq_future: {tq_future}'

        tq_result = self.api.get_kline_serial(symbol=tq_future, duration_seconds=tq_duration_seconds, data_length=tq_data_length)
        self.api.close()

        tq_result["datetime"] = pandas.to_datetime(tq_result["datetime"] + TIME_GAP)
        tq_result['datetime'] = tq_result['datetime'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))  # %f是毫秒

        return tq_result


    def load_all_tq_futures(self):
        self.api.close()
        return TQZTianQinClient.__tq_futures


    def load_all_tq_main_futures(self):
        tq_main_contracts = self.api.query_quotes(ins_class="CONT")

        main_vt_symbols = []
        [main_vt_symbols.append(
            self.api.get_quote(
                symbol=main_contract
            ).underlying_symbol
        ) for main_contract in tq_main_contracts]

        self.api.close()
        return main_vt_symbols

    @staticmethod
    def record_data():
        api = TqApi(auth=TqAuth('xxxxxxx', 'xxxxxxx'))

        instruments = ["SHFE.cu2305", "DCE.i2309"]

        quote_map = {}
        data_map = {}  # 之后考虑写共享内存里
        for instrument in instruments:
            quote_map[instrument] = api.get_quote(symbol=instrument)
            data_map[instrument] = pandas.DataFrame()

        while api.wait_update():
            for instrument in instruments:
                if api.is_changing(quote_map[instrument]):
                    # print(quote_map[instrument])
                    data_map[instrument].append(vars(quote_map[instrument]), ignore_index=True)

            if datetime.datetime.now().hour == 15:
                for instrument in instruments:
                    data_map[instrument].to_csv(
                        f'{instrument.replace(".", "_")}_{str(datetime.date.today()).replace("-", "")}.csv',
                        index=False
                    )

                break


if __name__ == '__main__':
    # ret_df = TQZTianQinClient().query_history_bars(tq_future="SHFE.cu2305", tq_duration_seconds=60)
    # print("ret_df: " + str(ret_df))

    # map
    # ret_quote = TQZTianQinClient().query_quote(tq_future="SHFE.cu2305")
    # print("ret_quote: " + str(ret_quote))

    # df
    # ret_tick = TQZTianQinClient().query_history_ticks(tq_future="SHFE.cu2305")
    # print("ret_tick: " + str(ret_tick))

    TQZTianQinClient.record_data()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值