量化交易之vnpy篇 - 主力合约换月 - 拉取当前主力合约数据 (天勤)

该博客介绍了TQZTqClient类,用于从天琴获取当前市场的主力期货合约,并通过TqSdk加载数据。它还包括了数据的更新功能,将主力合约信息写入Excel,以便后续分析。核心功能包括初始化、合约加载和数据同步到Excel文件的操作。
摘要由CSDN通过智能技术生成
class TQZTqClient:
    """
    Client for querying main future contracts of current market from Tianqin.
    """

    def __init__(self, account_name, account_password):
        """
        init api with account_name & account_password
        """

        self.main_vt_symbols = []
        self.tq_api = TqApi(TqKq(), auth=f'{account_name},{account_password}')

    def load_main_contracts(self, ins_class):
        """
        Load main contracts from TqSdk
        """

        try:
            tq_main_contracts = self.tq_api.query_quotes(ins_class=ins_class)

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

        except:
            pass

        finally:
            print("主力合约数据收取完成")
            print("self.main_vt_symbols: " + str(self.main_vt_symbols))
            self.__create_main_contracts(current_main_vt_symbols=self.main_vt_symbols)
            self.tq_api.close()


    # --- private part ---
    def __update_today_main_contracts(self, market_main_vt_symbols):
        """
        Update main contracts of current day to excel
        """
        TQZMainContractsChangeFilePath.ensure_mainContractsFold_is_exist()

        market_main_vt_symbols = sorted(market_main_vt_symbols)

        if os.path.exists(path=TQZMainContractsChangeFilePath.main_contracts_excel()) is False:
            self.__create_main_contracts(current_main_vt_symbols=market_main_vt_symbols)
        else:
            pre_main_contracts_dataframe = self.__init_pre_main_contracts_dataframe(market_main_vt_symbols=market_main_vt_symbols)

            today_main_contracts_dataframe = self.__init_today_main_contracts_dataframe(
                market_main_vt_symbols=market_main_vt_symbols,
                pre_main_contracts_dataframe=pre_main_contracts_dataframe
            )

            self.__to_excel(
                content_dataframe=today_main_contracts_dataframe,
                path=TQZMainContractsChangeFilePath.main_contracts_excel(),
                sheet_name=TQZMainContractsSheetType.CURRENT_FUTURE_MAIN_CONTRACT.value
            )

    @staticmethod
    def __init_today_main_contracts_dataframe(market_main_vt_symbols, pre_main_contracts_dataframe):
        today_main_contracts_dataframe = pandas.DataFrame(
            columns=[
                TQZMainContractsColumnType.MAIN_CONTRACT.value,
                TQZMainContractsColumnType.ENTRY_PRICE.value
            ]
        )
        today_main_contracts_dataframe[TQZMainContractsColumnType.MAIN_CONTRACT.value] = market_main_vt_symbols
        today_main_contracts_dataframe.set_index(TQZMainContractsColumnType.MAIN_CONTRACT.value, inplace=True)
        today_main_contracts_dataframe[TQZMainContractsColumnType.ENTRY_PRICE.value] = pre_main_contracts_dataframe[
            TQZMainContractsColumnType.ENTRY_PRICE.value]
        today_main_contracts_dataframe.reset_index(inplace=True)

        return today_main_contracts_dataframe

    @staticmethod
    def __init_pre_main_contracts_dataframe(market_main_vt_symbols):
        pre_main_contracts_dataframe = pandas.read_excel(
            io=TQZMainContractsChangeFilePath.main_contracts_excel(),
            sheet_name=TQZMainContractsSheetType.CURRENT_FUTURE_MAIN_CONTRACT.value
        )

        not_main_contracts = []
        current_main_contracts = pre_main_contracts_dataframe[
            TQZMainContractsColumnType.MAIN_CONTRACT.value].values.tolist()

        for current_main_contract in current_main_contracts:
            if current_main_contract not in market_main_vt_symbols:
                not_main_contracts.append(current_main_contract)

        pre_main_contracts_dataframe.set_index(TQZMainContractsColumnType.MAIN_CONTRACT.value, inplace=True)
        pre_main_contracts_dataframe.drop(not_main_contracts, inplace=True)  # drop all non_main_contracts

        return pre_main_contracts_dataframe

    def __create_main_contracts(self, current_main_vt_symbols):
        """
        Create main-contracts-excel when excel is not exsit.
        """

        main_contracts_dataframe = pandas.DataFrame(
            columns=[
                TQZMainContractsColumnType.MAIN_CONTRACT.value,
                TQZMainContractsColumnType.ENTRY_PRICE.value
            ]
        )

        main_contracts_dataframe[TQZMainContractsColumnType.MAIN_CONTRACT.value] = sorted(current_main_vt_symbols)

        self.__to_excel(
            content_dataframe=main_contracts_dataframe,
            path=TQZMainContractsChangeFilePath.main_contracts_excel(),
            sheet_name=TQZMainContractsSheetType.CURRENT_FUTURE_MAIN_CONTRACT.value
        )

    @staticmethod
    def __to_excel(content_dataframe, path, sheet_name):
        """
        Write content_dataframe to path/excel/sheet_name
        """

        excel_writer = pandas.ExcelWriter(path=path)
        content_dataframe.to_excel(
            excel_writer,
            sheet_name=sheet_name,
            index=False,
            freeze_panes=(1, 0)
        )
        excel_writer.save()

    @staticmethod
    def __get_vt_symbol(tq_symbol):
        """
        Change tq_symbol format to vt_symbol format
        """
        return f'{tq_symbol.split(".")[1]}.{tq_symbol.split(".")[0]}'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值