import os import json import pandas as pd from tqsdk import TqApi, TqAuth from time import sleep from datetime import datetime as dt def get_big_vol(): """ 在主力合约中, 筛选昨日持仓量和成交量较大的 有些品种日线无成交导致异常, 不能合并查询 """ MIN_OI = 1e4 MIN_VOL = 5e3 symbols = [] for _contra in api.query_cont_quotes(): try: df = api.get_kline_serial(_contra, 24 * 60 * 60, data_length=2) except: print(_contra, 'except') continue if len(df) < 2: print(_contra, len(df)) continue if (df['close_oi'].values[0] > MIN_OI) and ( df['volume'].values[0] > MIN_VOL): symbols += [_contra] else: print(_contra, 'min_vol') print('主力合约个数: ', len(symbols)) return symbols def get_small_mkt_val(symbols): """ 排除每手市值较大的合约 保存: 合约每手乘数, 每跳 """ MAX_VAL = 15e4 # MULT, TICK = {}, {} for sym in symbols: quote = api.get_quote(sym) mult = quote.volume_multiple tick = quote.price_tick mkt_val = quote.last_price * mult if mkt_val > MAX_VAL: print(sym, round(mkt_val * 1e-4)) continue MULT[sym] = mult TICK[sym] = tick symbols = MULT.keys() return symbols, MULT, TICK def big_vol_small_val(): """ 每个交易日只查1~2次主力合约 查完存本地文件 """ F_NAME = 'CONTRACTS.txt' now_date = dt.now().strftime("%Y-%m-%d") now_hhmm = dt.now().strftime("%H:%M") if os.path.exists(F_NAME): with open(F_NAME) as f: _dict = json.load(f) f_date = _dict['f_date'] f_hhmm = _dict['f_hhmm'] b_new_day = f_hhmm < '20:00' and now_hhmm > '20:00' if (now_date == f_date) and (not b_new_day): return _dict symbols = get_big_vol() symbols, MULT, TICK = get_small_mkt_val(symbols) _dict = {'f_date': now_date, 'f_hhmm': now_hhmm, 'MULT': MULT, 'TICK': TICK} with open(F_NAME, 'w') as f: # 打开文件 f.write(json.dumps(_dict)) return _dict auth = TqAuth("**", "**") api = TqApi(auth=auth) _dict = big_vol_small_val() print(_dict) sleep(3000)
ringo 已回答的问题 2020年12月21日
粘贴进来, 把我的空格都给吃了. 手工加也不起作用. 大家将就看吧.