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()
量化交易之回测篇 - back tester - 基于天勤的数据端备用方案
于 2023-04-26 21:56:08 首次发布