text
stringlengths
81
112k
创建一个新的DataStruct data 默认是self.data 🛠todo 没有这个?? inplace 是否是对于原类的修改 ?? def new(self, data=None, dtype=None, if_fq=None): """ 创建一个新的DataStruct data 默认是self.data 🛠todo 没有这个?? inplace 是否是对于原类的修改 ?? """ data = self.data if data is None else data dtype = self.type if dtype is None else dtype if_fq = self.if_fq if if_fq is None else if_fq temp = copy(self) temp.__init__(data, dtype, if_fq) return temp
reindex Arguments: ind {[type]} -- [description] Raises: RuntimeError -- [description] RuntimeError -- [description] Returns: [type] -- [description] def reindex(self, ind): """reindex Arguments: ind {[type]} -- [description] Raises: RuntimeError -- [description] RuntimeError -- [description] Returns: [type] -- [description] """ if isinstance(ind, pd.MultiIndex): try: return self.new(self.data.reindex(ind)) except: raise RuntimeError('QADATASTRUCT ERROR: CANNOT REINDEX') else: raise RuntimeError( 'QADATASTRUCT ERROR: ONLY ACCEPT MULTI-INDEX FORMAT' )
转换DataStruct为json def to_json(self): """ 转换DataStruct为json """ data = self.data if self.type[-3:] != 'min': data = self.data.assign(datetime= self.datetime) return QA_util_to_json_from_pandas(data.reset_index())
IO --> hdf5 def to_hdf(self, place, name): 'IO --> hdf5' self.data.to_hdf(place, name) return place, name
判断是否相同 def is_same(self, DataStruct): """ 判断是否相同 """ if self.type == DataStruct.type and self.if_fq == DataStruct.if_fq: return True else: return False
将一个DataStruct按code分解为N个DataStruct def splits(self): """ 将一个DataStruct按code分解为N个DataStruct """ return list(map(lambda x: self.select_code(x), self.code))
QADATASTRUCT的指标/函数apply入口 Arguments: func {[type]} -- [description] Returns: [type] -- [description] def add_func(self, func, *arg, **kwargs): """QADATASTRUCT的指标/函数apply入口 Arguments: func {[type]} -- [description] Returns: [type] -- [description] """ return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs)
获取不同格式的数据 Arguments: columns {[type]} -- [description] Keyword Arguments: type {str} -- [description] (default: {'ndarray'}) with_index {bool} -- [description] (default: {False}) Returns: [type] -- [description] def get_data(self, columns, type='ndarray', with_index=False): """获取不同格式的数据 Arguments: columns {[type]} -- [description] Keyword Arguments: type {str} -- [description] (default: {'ndarray'}) with_index {bool} -- [description] (default: {False}) Returns: [type] -- [description] """ res = self.select_columns(columns) if type == 'ndarray': if with_index: return res.reset_index().values else: return res.values elif type == 'list': if with_index: return res.reset_index().values.tolist() else: return res.values.tolist() elif type == 'dataframe': if with_index: return res.reset_index() else: return res
增加对于多列的支持 def pivot(self, column_): """增加对于多列的支持""" if isinstance(column_, str): try: return self.data.reset_index().pivot( index='datetime', columns='code', values=column_ ) except: return self.data.reset_index().pivot( index='date', columns='code', values=column_ ) elif isinstance(column_, list): try: return self.data.reset_index().pivot_table( index='datetime', columns='code', values=column_ ) except: return self.data.reset_index().pivot_table( index='date', columns='code', values=column_ )
选择code,start,end 如果end不填写,默认获取到结尾 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 def selects(self, code, start, end=None): """ 选择code,start,end 如果end不填写,默认获取到结尾 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 """ def _selects(code, start, end): if end is not None: return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), code), :] else: return self.data.loc[(slice(pd.Timestamp(start), None), code), :] try: return self.new(_selects(code, start, end), self.type, self.if_fq) except: raise ValueError( 'QA CANNOT GET THIS CODE {}/START {}/END{} '.format( code, start, end ) )
选择起始时间 如果end不填写,默认获取到结尾 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 def select_time(self, start, end=None): """ 选择起始时间 如果end不填写,默认获取到结尾 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 """ def _select_time(start, end): if end is not None: return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(None)), :] else: return self.data.loc[(slice(pd.Timestamp(start), None), slice(None)), :] try: return self.new(_select_time(start, end), self.type, self.if_fq) except: raise ValueError( 'QA CANNOT GET THIS START {}/END{} '.format(start, end) )
选取日期(一般用于分钟线) Arguments: day {[type]} -- [description] Raises: ValueError -- [description] Returns: [type] -- [description] def select_day(self, day): """选取日期(一般用于分钟线) Arguments: day {[type]} -- [description] Raises: ValueError -- [description] Returns: [type] -- [description] """ def _select_day(day): return self.data.loc[day, slice(None)] try: return self.new(_select_day(day), self.type, self.if_fq) except: raise ValueError('QA CANNOT GET THIS Day {} '.format(day))
选择月份 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 def select_month(self, month): """ 选择月份 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 """ def _select_month(month): return self.data.loc[month, slice(None)] try: return self.new(_select_month(month), self.type, self.if_fq) except: raise ValueError('QA CANNOT GET THIS Month {} '.format(month))
选择股票 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 def select_code(self, code): """ 选择股票 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复 """ def _select_code(code): return self.data.loc[(slice(None), code), :] try: return self.new(_select_code(code), self.type, self.if_fq) except: raise ValueError('QA CANNOT FIND THIS CODE {}'.format(code))
获取一个bar的数据 返回一个series 如果不存在,raise ValueError def get_bar(self, code, time): """ 获取一个bar的数据 返回一个series 如果不存在,raise ValueError """ try: return self.data.loc[(pd.Timestamp(time), code)] except: raise ValueError( 'DATASTRUCT CURRENTLY CANNOT FIND THIS BAR WITH {} {}'.format( code, time ) )
将天软本地数据导入 QA 数据库 :param client: :param ui_log: :param ui_progress: :param data_path: 存放天软数据的路径,默认文件名格式为类似 "SH600000.csv" 格式 def QA_SU_trans_stock_min(client=DATABASE, ui_log=None, ui_progress=None, data_path: str = "D:\\skysoft\\", type_="1min"): """ 将天软本地数据导入 QA 数据库 :param client: :param ui_log: :param ui_progress: :param data_path: 存放天软数据的路径,默认文件名格式为类似 "SH600000.csv" 格式 """ code_list = list(map(lambda x: x[2:8], os.listdir(data_path))) coll = client.stock_min coll.create_index([ ("code", pymongo.ASCENDING), ("time_stamp", pymongo.ASCENDING), ("date_stamp", pymongo.ASCENDING), ]) err = [] def __transform_ss_to_qa(file_path: str = None, end_time: str = None, type_="1min"): """ 导入相应 csv 文件,并处理格式 1. 这里默认为天软数据格式: time symbol open high low close volume amount 0 2013-08-01 09:31:00 SH600000 7.92 7.92 7.87 7.91 518700 4105381 ... 2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配,具体处理详见相应源码 open close high low vol amount ... datetime 2018-12-03 09:31:00 10.99 10.90 10.99 10.90 2.211700e+06 2.425626e+07 ... """ if file_path is None: raise ValueError("输入文件地址") df_local = pd.read_csv(file_path) # 列名处理 df_local = df_local.rename( columns={"time": "datetime", "volume": "vol"}) # 格式处理 df_local = df_local.assign( code=df_local.symbol.map(str).str.slice(2), date=df_local.datetime.map(str).str.slice(0, 10), ).drop( "symbol", axis=1) df_local = df_local.assign( datetime=pd.to_datetime(df_local.datetime), date_stamp=df_local.date.apply(lambda x: QA_util_date_stamp(x)), time_stamp=df_local.datetime.apply( lambda x: QA_util_time_stamp(x)), type="1min", ).set_index( "datetime", drop=False) df_local = df_local.loc[slice(None, end_time)] df_local["datetime"] = df_local["datetime"].map(str) df_local["type"] = type_ return df_local[[ "open", "close", "high", "low", "vol", "amount", "datetime", "code", "date", "date_stamp", "time_stamp", "type", ]] def __saving_work(code, coll): QA_util_log_info( "##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log) try: col_filter = {"code": code, "type": type_} ref_ = coll.find(col_filter) end_time = ref_[0]['datetime'] # 本地存储分钟数据最早的时间 filename = "SH"+code+".csv" if code[0] == '6' else "SZ"+code+".csv" __data = __transform_ss_to_qa( data_path+filename, end_time, type_) # 加入 end_time, 避免出现数据重复 QA_util_log_info( "##JOB03.{} Now Saving {} from {} to {} == {}".format( type_, code, __data['datetime'].iloc[0], __data['datetime'].iloc[-1], type_, ), ui_log=ui_log, ) if len(__data) > 1: coll.insert_many( QA_util_to_json_from_pandas(__data)[1::]) except Exception as e: QA_util_log_info(e, ui_log=ui_log) err.append(code) QA_util_log_info(err, ui_log=ui_log) executor = ThreadPoolExecutor(max_workers=4) res = { executor.submit(__saving_work, code_list[i_], coll) for i_ in range(len(code_list)) } count = 0 for i_ in concurrent.futures.as_completed(res): strProgress = "TRANSFORM PROGRESS {} ".format( str(float(count / len(code_list) * 100))[0:4] + "%") intProgress = int(count / len(code_list) * 10000.0) count = count + 1 if len(err) < 1: QA_util_log_info("SUCCESS", ui_log=ui_log) else: QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log) QA_util_log_info(err, ui_log=ui_log) if len(err) < 1: QA_util_log_info("SUCCESS", ui_log=ui_log) else: QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log) QA_util_log_info(err, ui_log=ui_log)
用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip 默认使用特定品种1min的方式的获取 def get_best_ip_by_real_data_fetch(_type='stock'): """ 用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip 默认使用特定品种1min的方式的获取 """ from QUANTAXIS.QAUtil.QADate import QA_util_today_str import time #找到前两天的有效交易日期 pre_trade_date=QA_util_get_real_date(QA_util_today_str()) pre_trade_date=QA_util_get_real_date(pre_trade_date) # 某个函数获取的耗时测试 def get_stock_data_by_ip(ips): start=time.time() try: QA_fetch_get_stock_transaction('000001',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port']) end=time.time() return end-start except: return 9999 def get_future_data_by_ip(ips): start=time.time() try: QA_fetch_get_future_transaction('RBL8',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port']) end=time.time() return end-start except: return 9999 func,ip_list=0,0 if _type=='stock': func,ip_list=get_stock_data_by_ip,stock_ip_list else: func,ip_list=get_future_data_by_ip,future_ip_list from pathos.multiprocessing import Pool def multiMap(func,sequence): res=[] pool=Pool(4) for i in sequence: res.append(pool.apply_async(func,(i,))) pool.close() pool.join() return list(map(lambda x:x.get(),res)) res=multiMap(func,ip_list) index=res.index(min(res)) return ip_list[index]
根据ping排序返回可用的ip列表 2019 03 31 取消参数filename :param ip_list: ip列表 :param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip :param _type: ip类型 :return: 可以ping通的ip列表 def get_ip_list_by_multi_process_ping(ip_list=[], n=0, _type='stock'): ''' 根据ping排序返回可用的ip列表 2019 03 31 取消参数filename :param ip_list: ip列表 :param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip :param _type: ip类型 :return: 可以ping通的ip列表 ''' cache = QA_util_cache() results = cache.get(_type) if results: # read the data from cache print('loading ip list from {} cache.'.format(_type)) else: ips = [(x['ip'], x['port'], _type) for x in ip_list] ps = Parallelism() ps.add(ping, ips) ps.run() data = list(ps.get_results()) results = [] for i in range(len(data)): # 删除ping不通的数据 if data[i] < datetime.timedelta(0, 9, 0): results.append((data[i], ip_list[i])) # 按照ping值从小大大排序 results = [x[1] for x in sorted(results, key=lambda x: x[0])] if _type: # store the data as binary data stream cache.set(_type, results, age=86400) print('saving ip list to {} cache {}.'.format(_type, len(results))) if len(results) > 0: if n == 0 and len(results) > 0: return results else: return results[:n] else: print('ALL IP PING TIMEOUT!') return [{'ip': None, 'port': None}]
[summary] Arguments: ip {[type]} -- [description] port {[type]} -- [description] Returns: [type] -- [description] def get_mainmarket_ip(ip, port): """[summary] Arguments: ip {[type]} -- [description] port {[type]} -- [description] Returns: [type] -- [description] """ global best_ip if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is None: best_ip = select_best_ip() ip = best_ip['stock']['ip'] port = best_ip['stock']['port'] elif ip is None and port is None and best_ip['stock']['ip'] is not None and best_ip['stock']['port'] is not None: ip = best_ip['stock']['ip'] port = best_ip['stock']['port'] else: pass return ip, port
按bar长度推算数据 Arguments: code {[type]} -- [description] _type {[type]} -- [description] lens {[type]} -- [description] Keyword Arguments: ip {[type]} -- [description] (default: {best_ip}) port {[type]} -- [description] (default: {7709}) Returns: [type] -- [description] def QA_fetch_get_security_bars(code, _type, lens, ip=None, port=None): """按bar长度推算数据 Arguments: code {[type]} -- [description] _type {[type]} -- [description] lens {[type]} -- [description] Keyword Arguments: ip {[type]} -- [description] (default: {best_ip}) port {[type]} -- [description] (default: {7709}) Returns: [type] -- [description] """ ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() with api.connect(ip, port): data = pd.concat([api.to_df(api.get_security_bars(_select_type(_type), _select_market_code( code), code, (i - 1) * 800, 800)) for i in range(1, int(lens / 800) + 2)], axis=0) data = data \ .drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \ .assign(datetime=pd.to_datetime(data['datetime']), date=data['datetime'].apply(lambda x: str(x)[0:10]), date_stamp=data['datetime'].apply( lambda x: QA_util_date_stamp(x)), time_stamp=data['datetime'].apply( lambda x: QA_util_time_stamp(x)), type=_type, code=str(code)) \ .set_index('datetime', drop=False, inplace=False).tail(lens) if data is not None: return data else: return None
获取日线及以上级别的数据 Arguments: code {str:6} -- code 是一个单独的code 6位长度的str start_date {str:10} -- 10位长度的日期 比如'2017-01-01' end_date {str:10} -- 10位长度的日期 比如'2018-01-01' Keyword Arguments: if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhfq' --定点后复权 frequency {str} -- day/week/month/quarter/year 也可以是简写 D/W/M/Q/Y ip {str} -- [description] (default: None) ip可以通过select_best_ip()函数重新获取 port {int} -- [description] (default: {None}) Returns: pd.DataFrame/None -- 返回的是dataframe,如果出错比如只获取了一天,而当天停牌,返回None Exception: 如果出现网络问题/服务器拒绝, 会出现socket:time out 尝试再次获取/更换ip即可, 本函数不做处理 def QA_fetch_get_stock_day(code, start_date, end_date, if_fq='00', frequence='day', ip=None, port=None): """获取日线及以上级别的数据 Arguments: code {str:6} -- code 是一个单独的code 6位长度的str start_date {str:10} -- 10位长度的日期 比如'2017-01-01' end_date {str:10} -- 10位长度的日期 比如'2018-01-01' Keyword Arguments: if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhfq' --定点后复权 frequency {str} -- day/week/month/quarter/year 也可以是简写 D/W/M/Q/Y ip {str} -- [description] (default: None) ip可以通过select_best_ip()函数重新获取 port {int} -- [description] (default: {None}) Returns: pd.DataFrame/None -- 返回的是dataframe,如果出错比如只获取了一天,而当天停牌,返回None Exception: 如果出现网络问题/服务器拒绝, 会出现socket:time out 尝试再次获取/更换ip即可, 本函数不做处理 """ ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() try: with api.connect(ip, port, time_out=0.7): if frequence in ['day', 'd', 'D', 'DAY', 'Day']: frequence = 9 elif frequence in ['w', 'W', 'Week', 'week']: frequence = 5 elif frequence in ['month', 'M', 'm', 'Month']: frequence = 6 elif frequence in ['quarter', 'Q', 'Quarter', 'q']: frequence = 10 elif frequence in ['y', 'Y', 'year', 'Year']: frequence = 11 start_date = str(start_date)[0:10] today_ = datetime.date.today() lens = QA_util_get_trade_gap(start_date, today_) data = pd.concat([api.to_df(api.get_security_bars(frequence, _select_market_code( code), code, (int(lens / 800) - i) * 800, 800)) for i in range(int(lens / 800) + 1)], axis=0) # 这里的问题是: 如果只取了一天的股票,而当天停牌, 那么就直接返回None了 if len(data) < 1: return None data = data[data['open'] != 0] data = data.assign(date=data['datetime'].apply(lambda x: str(x[0:10])), code=str(code), date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(str(x)[0:10]))) \ .set_index('date', drop=False, inplace=False) end_date = str(end_date)[0:10] data = data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[ start_date:end_date] if if_fq in ['00', 'bfq']: return data else: print('CURRENTLY NOT SUPPORT REALTIME FUQUAN') return None # xdxr = QA_fetch_get_stock_xdxr(code) # if if_fq in ['01','qfq']: # return QA_data_make_qfq(data,xdxr) # elif if_fq in ['02','hfq']: # return QA_data_make_hfq(data,xdxr) except Exception as e: if isinstance(e, TypeError): print('Tushare内置的pytdx版本和QUANTAXIS使用的pytdx 版本不同, 请重新安装pytdx以解决此问题') print('pip uninstall pytdx') print('pip install pytdx') else: print(e)
深市代码分类 Arguments: code {[type]} -- [description] Returns: [type] -- [description] def for_sz(code): """深市代码分类 Arguments: code {[type]} -- [description] Returns: [type] -- [description] """ if str(code)[0:2] in ['00', '30', '02']: return 'stock_cn' elif str(code)[0:2] in ['39']: return 'index_cn' elif str(code)[0:2] in ['15']: return 'etf_cn' elif str(code)[0:2] in ['10', '11', '12', '13']: # 10xxxx 国债现货 # 11xxxx 债券 # 12xxxx 可转换债券 # 12xxxx 国债回购 return 'bond_cn' elif str(code)[0:2] in ['20']: return 'stockB_cn' else: return 'undefined'
获取指数列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) Returns: [type] -- [description] def QA_fetch_get_index_list(ip=None, port=None): """获取指数列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() with api.connect(ip, port): data = pd.concat( [pd.concat([api.to_df(api.get_security_list(j, i * 1000)).assign(sse='sz' if j == 0 else 'sh').set_index( ['code', 'sse'], drop=False) for i in range(int(api.get_security_count(j) / 1000) + 1)], axis=0) for j in range(2)], axis=0) # data.code = data.code.apply(int) sz = data.query('sse=="sz"') sh = data.query('sse=="sh"') sz = sz.assign(sec=sz.code.apply(for_sz)) sh = sh.assign(sec=sh.code.apply(for_sh)) return pd.concat([sz, sh]).query('sec=="index_cn"').sort_index().assign( name=data['name'].apply(lambda x: str(x)[0:6]))
实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前 def QA_fetch_get_stock_transaction_realtime(code, ip=None, port=None): '实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前' ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() try: with api.connect(ip, port): data = pd.DataFrame() data = pd.concat([api.to_df(api.get_transaction_data( _select_market_code(str(code)), code, (2 - i) * 2000, 2000)) for i in range(3)], axis=0) if 'value' in data.columns: data = data.drop(['value'], axis=1) data = data.dropna() day = datetime.date.today() return data.assign(date=str(day)).assign( datetime=pd.to_datetime(data['time'].apply(lambda x: str(day) + ' ' + str(x)))) \ .assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False, inplace=False) except: return None
除权除息 def QA_fetch_get_stock_xdxr(code, ip=None, port=None): '除权除息' ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() market_code = _select_market_code(code) with api.connect(ip, port): category = { '1': '除权除息', '2': '送配股上市', '3': '非流通股上市', '4': '未知股本变动', '5': '股本变化', '6': '增发新股', '7': '股份回购', '8': '增发新股上市', '9': '转配股上市', '10': '可转债上市', '11': '扩缩股', '12': '非流通股缩股', '13': '送认购权证', '14': '送认沽权证'} data = api.to_df(api.get_xdxr_info(market_code, code)) if len(data) >= 1: data = data \ .assign(date=pd.to_datetime(data[['year', 'month', 'day']])) \ .drop(['year', 'month', 'day'], axis=1) \ .assign(category_meaning=data['category'].apply(lambda x: category[str(x)])) \ .assign(code=str(code)) \ .rename(index=str, columns={'panhouliutong': 'liquidity_after', 'panqianliutong': 'liquidity_before', 'houzongguben': 'shares_after', 'qianzongguben': 'shares_before'}) \ .set_index('date', drop=False, inplace=False) return data.assign(date=data['date'].apply(lambda x: str(x)[0:10])) else: return None
股票基本信息 def QA_fetch_get_stock_info(code, ip=None, port=None): '股票基本信息' ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() market_code = _select_market_code(code) with api.connect(ip, port): return api.to_df(api.get_finance_info(market_code, code))
板块数据 def QA_fetch_get_stock_block(ip=None, port=None): '板块数据' ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() with api.connect(ip, port): data = pd.concat([api.to_df(api.get_and_parse_block_info("block_gn.dat")).assign(type='gn'), api.to_df(api.get_and_parse_block_info( "block.dat")).assign(type='yb'), api.to_df(api.get_and_parse_block_info( "block_zs.dat")).assign(type='zs'), api.to_df(api.get_and_parse_block_info("block_fg.dat")).assign(type='fg')]) if len(data) > 10: return data.assign(source='tdx').drop(['block_type', 'code_index'], axis=1).set_index('code', drop=False, inplace=False).drop_duplicates() else: QA_util_log_info('Wrong with fetch block ')
期货代码list def QA_fetch_get_extensionmarket_list(ip=None, port=None): '期货代码list' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() with apix.connect(ip, port): num = apix.get_instrument_count() return pd.concat([apix.to_df( apix.get_instrument_info((int(num / 500) - i) * 500, 500)) for i in range(int(num / 500) + 1)], axis=0).set_index('code', drop=False)
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 42 3 商品指数 TI 60 3 主力期货合约 MA 28 3 郑州商品 QZ 29 3 大连商品 QD 30 3 上海期货(原油+贵金属) QS 47 3 中金所期货 CZ 50 3 渤海商品 BH 76 3 齐鲁商品 QL 46 11 上海黄金(伦敦金T+D) SG def QA_fetch_get_future_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 42 3 商品指数 TI 60 3 主力期货合约 MA 28 3 郑州商品 QZ 29 3 大连商品 QD 30 3 上海期货(原油+贵金属) QS 47 3 中金所期货 CZ 50 3 渤海商品 BH 76 3 齐鲁商品 QL 46 11 上海黄金(伦敦金T+D) SG """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==42 or market==28 or market==29 or market==30 or market==47')
全球指数列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 37 11 全球指数(静态) FW 12 5 国际指数 WI def QA_fetch_get_globalindex_list(ip=None, port=None): """全球指数列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 37 11 全球指数(静态) FW 12 5 国际指数 WI """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==12 or market==37')
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 42 3 商品指数 TI 60 3 主力期货合约 MA 28 3 郑州商品 QZ 29 3 大连商品 QD 30 3 上海期货(原油+贵金属) QS 47 3 中金所期货 CZ 50 3 渤海商品 BH 76 3 齐鲁商品 QL 46 11 上海黄金(伦敦金T+D) SG def QA_fetch_get_goods_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 42 3 商品指数 TI 60 3 主力期货合约 MA 28 3 郑州商品 QZ 29 3 大连商品 QD 30 3 上海期货(原油+贵金属) QS 47 3 中金所期货 CZ 50 3 渤海商品 BH 76 3 齐鲁商品 QL 46 11 上海黄金(伦敦金T+D) SG """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==50 or market==76 or market==46')
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 14 3 伦敦金属 LM 15 3 伦敦石油 IP 16 3 纽约商品 CO 17 3 纽约石油 NY 18 3 芝加哥谷 CB 19 3 东京工业品 TO 20 3 纽约期货 NB 77 3 新加坡期货 SX 39 3 马来期货 ML def QA_fetch_get_globalfuture_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 14 3 伦敦金属 LM 15 3 伦敦石油 IP 16 3 纽约商品 CO 17 3 纽约石油 NY 18 3 芝加哥谷 CB 19 3 东京工业品 TO 20 3 纽约期货 NB 77 3 新加坡期货 SX 39 3 马来期货 ML """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query( 'market==14 or market==15 or market==16 or market==17 or market==18 or market==19 or market==20 or market==77 or market==39')
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB def QA_fetch_get_hkstock_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==31 or market==48')
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB def QA_fetch_get_hkindex_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==27')
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB def QA_fetch_get_hkfund_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==49')
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) ## 美股 USA STOCK 74 13 美国股票 US 40 11 中国概念股 CH 41 11 美股知名公司 MG def QA_fetch_get_usstock_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) ## 美股 USA STOCK 74 13 美国股票 US 40 11 中国概念股 CH 41 11 美股知名公司 MG """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==74 or market==40 or market==41')
宏观指标列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 38 10 宏观指标 HG def QA_fetch_get_macroindex_list(ip=None, port=None): """宏观指标列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 38 10 宏观指标 HG """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==38')
期权列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) ## 期权 OPTION 1 12 临时期权(主要是50ETF) 4 12 郑州商品期权 OZ 5 12 大连商品期权 OD 6 12 上海商品期权 OS 7 12 中金所期权 OJ 8 12 上海股票期权 QQ 9 12 深圳股票期权 (推测) def QA_fetch_get_option_list(ip=None, port=None): """期权列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) ## 期权 OPTION 1 12 临时期权(主要是50ETF) 4 12 郑州商品期权 OZ 5 12 大连商品期权 OD 6 12 上海商品期权 OS 7 12 中金所期权 OJ 8 12 上海股票期权 QQ 9 12 深圳股票期权 (推测) """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('category==12 and market!=1')
#🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series def QA_fetch_get_option_contract_time_to_market(): ''' #🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series ''' result = QA_fetch_get_option_list('tdx') # pprint.pprint(result) # category market code name desc code ''' fix here : See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy result['meaningful_name'] = None C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead ''' # df = pd.DataFrame() rows = [] result['meaningful_name'] = None for idx in result.index: # pprint.pprint((idx)) strCategory = result.loc[idx, "category"] strMarket = result.loc[idx, "market"] strCode = result.loc[idx, "code"] # 10001215 strName = result.loc[idx, 'name'] # 510050C9M03200 strDesc = result.loc[idx, 'desc'] # 10001215 if strName.startswith("510050"): # print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, ) if strName.startswith("510050C"): putcall = '50ETF,认购期权' elif strName.startswith("510050P"): putcall = '50ETF,认沽期权' else: putcall = "Unkown code name : " + strName expireMonth = strName[7:8] if expireMonth == 'A': expireMonth = "10月" elif expireMonth == 'B': expireMonth = "11月" elif expireMonth == 'C': expireMonth = "12月" else: expireMonth = expireMonth + '月' # 第12位期初设为“M”,并根据合约调整次数按照“A”至“Z”依序变更,如变更为“A”表示期权合约发生首次调整,变更为“B”表示期权合约发生第二次调整,依此类推; # fix here : M ?? if strName[8:9] == "M": adjust = "未调整" elif strName[8:9] == 'A': adjust = " 第1次调整" elif strName[8:9] == 'B': adjust = " 第2调整" elif strName[8:9] == 'C': adjust = " 第3次调整" elif strName[8:9] == 'D': adjust = " 第4次调整" elif strName[8:9] == 'E': adjust = " 第5次调整" elif strName[8:9] == 'F': adjust = " 第6次调整" elif strName[8:9] == 'G': adjust = " 第7次调整" elif strName[8:9] == 'H': adjust = " 第8次调整" elif strName[8:9] == 'I': adjust = " 第9次调整" elif strName[8:9] == 'J': adjust = " 第10次调整" else: adjust = " 第10次以上的调整,调整代码 %s" + strName[8:9] executePrice = strName[9:] result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % ( putcall, expireMonth, adjust, executePrice) row = result.loc[idx] rows.append(row) elif strName.startswith("SR"): # print("SR") # SR1903-P-6500 expireYear = strName[2:4] expireMonth = strName[4:6] put_or_call = strName[7:8] if put_or_call == "P": putcall = "白糖,认沽期权" elif put_or_call == "C": putcall = "白糖,认购期权" else: putcall = "Unkown code name : " + strName executePrice = strName[9:] result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % ( putcall, expireYear, expireMonth, executePrice) row = result.loc[idx] rows.append(row) pass elif strName.startswith("CU"): # print("CU") # print("SR") # SR1903-P-6500 expireYear = strName[2:4] expireMonth = strName[4:6] put_or_call = strName[7:8] if put_or_call == "P": putcall = "铜,认沽期权" elif put_or_call == "C": putcall = "铜,认购期权" else: putcall = "Unkown code name : " + strName executePrice = strName[9:] result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % ( putcall, expireYear, expireMonth, executePrice) row = result.loc[idx] rows.append(row) pass # todo 新增期权品种 棉花,玉米, 天然橡胶 elif strName.startswith("RU"): # print("M") # print(strName) ## expireYear = strName[2:4] expireMonth = strName[4:6] put_or_call = strName[7:8] if put_or_call == "P": putcall = "天然橡胶,认沽期权" elif put_or_call == "C": putcall = "天然橡胶,认购期权" else: putcall = "Unkown code name : " + strName executePrice = strName[9:] result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % ( putcall, expireYear, expireMonth, executePrice) row = result.loc[idx] rows.append(row) pass elif strName.startswith("CF"): # print("M") # print(strName) ## expireYear = strName[2:4] expireMonth = strName[4:6] put_or_call = strName[7:8] if put_or_call == "P": putcall = "棉花,认沽期权" elif put_or_call == "C": putcall = "棉花,认购期权" else: putcall = "Unkown code name : " + strName executePrice = strName[9:] result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % ( putcall, expireYear, expireMonth, executePrice) row = result.loc[idx] rows.append(row) pass elif strName.startswith("M"): # print("M") # print(strName) ## expireYear = strName[1:3] expireMonth = strName[3:5] put_or_call = strName[6:7] if put_or_call == "P": putcall = "豆粕,认沽期权" elif put_or_call == "C": putcall = "豆粕,认购期权" else: putcall = "Unkown code name : " + strName executePrice = strName[8:] result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % ( putcall, expireYear, expireMonth, executePrice) row = result.loc[idx] rows.append(row) pass elif strName.startswith("C") and strName[1] != 'F' and strName[1] != 'U': # print("M") # print(strName) ## expireYear = strName[1:3] expireMonth = strName[3:5] put_or_call = strName[6:7] if put_or_call == "P": putcall = "玉米,认沽期权" elif put_or_call == "C": putcall = "玉米,认购期权" else: putcall = "Unkown code name : " + strName executePrice = strName[8:] result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % ( putcall, expireYear, expireMonth, executePrice) row = result.loc[idx] rows.append(row) pass else: print("未知类型合约") print(strName) return rows
#🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series def QA_fetch_get_option_50etf_contract_time_to_market(): ''' #🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series ''' result = QA_fetch_get_option_list('tdx') # pprint.pprint(result) # category market code name desc code ''' fix here : See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy result['meaningful_name'] = None C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead ''' # df = pd.DataFrame() rows = [] result['meaningful_name'] = None for idx in result.index: # pprint.pprint((idx)) strCategory = result.loc[idx, "category"] strMarket = result.loc[idx, "market"] strCode = result.loc[idx, "code"] # 10001215 strName = result.loc[idx, 'name'] # 510050C9M03200 strDesc = result.loc[idx, 'desc'] # 10001215 if strName.startswith("510050"): # print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, ) if strName.startswith("510050C"): putcall = '50ETF,认购期权' elif strName.startswith("510050P"): putcall = '50ETF,认沽期权' else: putcall = "Unkown code name : " + strName expireMonth = strName[7:8] if expireMonth == 'A': expireMonth = "10月" elif expireMonth == 'B': expireMonth = "11月" elif expireMonth == 'C': expireMonth = "12月" else: expireMonth = expireMonth + '月' # 第12位期初设为“M”,并根据合约调整次数按照“A”至“Z”依序变更,如变更为“A”表示期权合约发生首次调整,变更为“B”表示期权合约发生第二次调整,依此类推; # fix here : M ?? if strName[8:9] == "M": adjust = "未调整" elif strName[8:9] == 'A': adjust = " 第1次调整" elif strName[8:9] == 'B': adjust = " 第2调整" elif strName[8:9] == 'C': adjust = " 第3次调整" elif strName[8:9] == 'D': adjust = " 第4次调整" elif strName[8:9] == 'E': adjust = " 第5次调整" elif strName[8:9] == 'F': adjust = " 第6次调整" elif strName[8:9] == 'G': adjust = " 第7次调整" elif strName[8:9] == 'H': adjust = " 第8次调整" elif strName[8:9] == 'I': adjust = " 第9次调整" elif strName[8:9] == 'J': adjust = " 第10次调整" else: adjust = " 第10次以上的调整,调整代码 %s" + strName[8:9] executePrice = strName[9:] result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % ( putcall, expireMonth, adjust, executePrice) row = result.loc[idx] rows.append(row) return rows
铜期权 CU 开头 上期证 豆粕 M开头 大商所 白糖 SR开头 郑商所 测试中发现,行情不太稳定 ? 是 通达信 IP 的问题 ? def QA_fetch_get_commodity_option_CF_contract_time_to_market(): ''' 铜期权 CU 开头 上期证 豆粕 M开头 大商所 白糖 SR开头 郑商所 测试中发现,行情不太稳定 ? 是 通达信 IP 的问题 ? ''' result = QA_fetch_get_option_list('tdx') # pprint.pprint(result) # category market code name desc code # df = pd.DataFrame() rows = [] result['meaningful_name'] = None for idx in result.index: # pprint.pprint((idx)) strCategory = result.loc[idx, "category"] strMarket = result.loc[idx, "market"] strCode = result.loc[idx, "code"] # strName = result.loc[idx, 'name'] # strDesc = result.loc[idx, 'desc'] # # 如果同时获取, 不同的 期货交易所数据, pytdx会 connection close 连接中断? # if strName.startswith("CU") or strName.startswith("M") or strName.startswith('SR'): if strName.startswith("CF"): # print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, ) row = result.loc[idx] rows.append(row) return rows pass
汇率列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) ## 汇率 EXCHANGERATE 10 4 基本汇率 FE 11 4 交叉汇率 FX def QA_fetch_get_exchangerate_list(ip=None, port=None): """汇率列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) ## 汇率 EXCHANGERATE 10 4 基本汇率 FE 11 4 交叉汇率 FX """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==10 or market==11').query('category==4')
期货数据 日线 def QA_fetch_get_future_day(code, start_date, end_date, frequence='day', ip=None, port=None): '期货数据 日线' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() start_date = str(start_date)[0:10] today_ = datetime.date.today() lens = QA_util_get_trade_gap(start_date, today_) global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list with apix.connect(ip, port): code_market = extension_market_list.query( 'code=="{}"'.format(code)).iloc[0] data = pd.concat( [apix.to_df(apix.get_instrument_bars( _select_type(frequence), int(code_market.market), str(code), (int(lens / 700) - i) * 700, 700)) for i in range(int(lens / 700) + 1)], axis=0) try: # 获取商品期货会报None data = data.assign(date=data['datetime'].apply(lambda x: str(x[0:10]))).assign(code=str(code)) \ .assign(date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(str(x)[0:10]))).set_index('date', drop=False, inplace=False) except Exception as exp: print("code is ", code) print(exp.__str__) return None return data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[start_date:end_date].assign( date=data['date'].apply(lambda x: str(x)[0:10]))
期货数据 分钟线 def QA_fetch_get_future_min(code, start, end, frequence='1min', ip=None, port=None): '期货数据 分钟线' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() type_ = '' start_date = str(start)[0:10] today_ = datetime.date.today() lens = QA_util_get_trade_gap(start_date, today_) global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list if str(frequence) in ['5', '5m', '5min', 'five']: frequence, type_ = 0, '5min' lens = 48 * lens * 2.5 elif str(frequence) in ['1', '1m', '1min', 'one']: frequence, type_ = 8, '1min' lens = 240 * lens * 2.5 elif str(frequence) in ['15', '15m', '15min', 'fifteen']: frequence, type_ = 1, '15min' lens = 16 * lens * 2.5 elif str(frequence) in ['30', '30m', '30min', 'half']: frequence, type_ = 2, '30min' lens = 8 * lens * 2.5 elif str(frequence) in ['60', '60m', '60min', '1h']: frequence, type_ = 3, '60min' lens = 4 * lens * 2.5 if lens > 20800: lens = 20800 # print(lens) with apix.connect(ip, port): code_market = extension_market_list.query( 'code=="{}"'.format(code)).iloc[0] data = pd.concat([apix.to_df(apix.get_instrument_bars(frequence, int(code_market.market), str( code), (int(lens / 700) - i) * 700, 700)) for i in range(int(lens / 700) + 1)], axis=0) # print(data) # print(data.datetime) data = data \ .assign(tradetime=data['datetime'].apply(str), code=str(code)) \ .assign(datetime=pd.to_datetime(data['datetime'].apply(QA_util_future_to_realdatetime, 1))) \ .drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \ .assign(date=data['datetime'].apply(lambda x: str(x)[0:10])) \ .assign(date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(x))) \ .assign(time_stamp=data['datetime'].apply(lambda x: QA_util_time_stamp(x))) \ .assign(type=type_).set_index('datetime', drop=False, inplace=False) return data.assign(datetime=data['datetime'].apply(lambda x: str(x)))[start:end].sort_index()
期货历史成交分笔 def QA_fetch_get_future_transaction(code, start, end, retry=4, ip=None, port=None): '期货历史成交分笔' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list real_start, real_end = QA_util_get_real_datelist(start, end) if real_start is None: return None real_id_range = [] with apix.connect(ip, port): code_market = extension_market_list.query( 'code=="{}"'.format(code)).iloc[0] data = pd.DataFrame() for index_ in range(trade_date_sse.index(real_start), trade_date_sse.index(real_end) + 1): try: data_ = __QA_fetch_get_future_transaction( code, trade_date_sse[index_], retry, int(code_market.market), apix) if len(data_) < 1: return None except Exception as e: print(e) QA_util_log_info('Wrong in Getting {} history transaction data in day {}'.format( code, trade_date_sse[index_])) else: QA_util_log_info('Successfully Getting {} history transaction data in day {}'.format( code, trade_date_sse[index_])) data = data.append(data_) if len(data) > 0: return data.assign(datetime=data['datetime'].apply(lambda x: str(x)[0:19])) else: return None
期货历史成交分笔 def QA_fetch_get_future_transaction_realtime(code, ip=None, port=None): '期货历史成交分笔' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list code_market = extension_market_list.query( 'code=="{}"'.format(code)).iloc[0] with apix.connect(ip, port): data = pd.DataFrame() data = pd.concat([apix.to_df(apix.get_transaction_data( int(code_market.market), code, (30 - i) * 1800)) for i in range(31)], axis=0) return data.assign(datetime=pd.to_datetime(data['date'])).assign(date=lambda x: str(x)[0:10]) \ .assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False, inplace=False)
期货实时价格 def QA_fetch_get_future_realtime(code, ip=None, port=None): '期货实时价格' ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list __data = pd.DataFrame() code_market = extension_market_list.query( 'code=="{}"'.format(code)).iloc[0] with apix.connect(ip, port): __data = apix.to_df(apix.get_instrument_quote( int(code_market.market), code)) __data['datetime'] = datetime.datetime.now() # data = __data[['datetime', 'active1', 'active2', 'last_close', 'code', 'open', 'high', 'low', 'price', 'cur_vol', # 's_vol', 'b_vol', 'vol', 'ask1', 'ask_vol1', 'bid1', 'bid_vol1', 'ask2', 'ask_vol2', # 'bid2', 'bid_vol2', 'ask3', 'ask_vol3', 'bid3', 'bid_vol3', 'ask4', # 'ask_vol4', 'bid4', 'bid_vol4', 'ask5', 'ask_vol5', 'bid5', 'bid_vol5']] return __data.set_index(['datetime', 'code'])
类似于pd.concat 用于合并一个list里面的多个DataStruct,会自动去重 Arguments: lists {[type]} -- [DataStruct1,DataStruct2,....,DataStructN] Returns: [type] -- new DataStruct def concat(lists): """类似于pd.concat 用于合并一个list里面的多个DataStruct,会自动去重 Arguments: lists {[type]} -- [DataStruct1,DataStruct2,....,DataStructN] Returns: [type] -- new DataStruct """ return lists[0].new( pd.concat([lists.data for lists in lists]).drop_duplicates() )
一个任意格式转化为DataStruct的方法 Arguments: data {[type]} -- [description] Keyword Arguments: frequence {[type]} -- [description] (default: {FREQUENCE.DAY}) market_type {[type]} -- [description] (default: {MARKET_TYPE.STOCK_CN}) default_header {list} -- [description] (default: {[]}) Returns: [type] -- [description] def datastruct_formater( data, frequence=FREQUENCE.DAY, market_type=MARKET_TYPE.STOCK_CN, default_header=[] ): """一个任意格式转化为DataStruct的方法 Arguments: data {[type]} -- [description] Keyword Arguments: frequence {[type]} -- [description] (default: {FREQUENCE.DAY}) market_type {[type]} -- [description] (default: {MARKET_TYPE.STOCK_CN}) default_header {list} -- [description] (default: {[]}) Returns: [type] -- [description] """ if isinstance(data, list): try: res = pd.DataFrame(data, columns=default_header) if frequence is FREQUENCE.DAY: if market_type is MARKET_TYPE.STOCK_CN: return QA_DataStruct_Stock_day( res.assign(date=pd.to_datetime(res.date) ).set_index(['date', 'code'], drop=False), dtype='stock_day' ) elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: if market_type is MARKET_TYPE.STOCK_CN: return QA_DataStruct_Stock_min( res.assign(datetime=pd.to_datetime(res.datetime) ).set_index(['datetime', 'code'], drop=False), dtype='stock_min' ) except: pass elif isinstance(data, np.ndarray): try: res = pd.DataFrame(data, columns=default_header) if frequence is FREQUENCE.DAY: if market_type is MARKET_TYPE.STOCK_CN: return QA_DataStruct_Stock_day( res.assign(date=pd.to_datetime(res.date) ).set_index(['date', 'code'], drop=False), dtype='stock_day' ) elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: if market_type is MARKET_TYPE.STOCK_CN: return QA_DataStruct_Stock_min( res.assign(datetime=pd.to_datetime(res.datetime) ).set_index(['datetime', 'code'], drop=False), dtype='stock_min' ) except: pass elif isinstance(data, pd.DataFrame): index = data.index if isinstance(index, pd.MultiIndex): pass elif isinstance(index, pd.DatetimeIndex): pass elif isinstance(index, pd.Index): pass
dataframe from tushare Arguments: dataframe {[type]} -- [description] Returns: [type] -- [description] def from_tushare(dataframe, dtype='day'): """dataframe from tushare Arguments: dataframe {[type]} -- [description] Returns: [type] -- [description] """ if dtype in ['day']: return QA_DataStruct_Stock_day( dataframe.assign(date=pd.to_datetime(dataframe.date) ).set_index(['date', 'code'], drop=False), dtype='stock_day' ) elif dtype in ['min']: return QA_DataStruct_Stock_min( dataframe.assign(datetime=pd.to_datetime(dataframe.datetime) ).set_index(['datetime', 'code'], drop=False), dtype='stock_min' )
日线QDS装饰器 def QDS_StockDayWarpper(func): """ 日线QDS装饰器 """ def warpper(*args, **kwargs): data = func(*args, **kwargs) if isinstance(data.index, pd.MultiIndex): return QA_DataStruct_Stock_day(data) else: return QA_DataStruct_Stock_day( data.assign(date=pd.to_datetime(data.date) ).set_index(['date', 'code'], drop=False), dtype='stock_day' ) return warpper
分钟线QDS装饰器 def QDS_StockMinWarpper(func, *args, **kwargs): """ 分钟线QDS装饰器 """ def warpper(*args, **kwargs): data = func(*args, **kwargs) if isinstance(data.index, pd.MultiIndex): return QA_DataStruct_Stock_min(data) else: return QA_DataStruct_Stock_min( data.assign(datetime=pd.to_datetime(data.datetime) ).set_index(['datetime', 'code'], drop=False), dtype='stock_min' ) return warpper
获取股票的复权因子 Arguments: code {[type]} -- [description] Keyword Arguments: end {str} -- [description] (default: {''}) Returns: [type] -- [description] def QA_fetch_get_stock_adj(code, end=''): """获取股票的复权因子 Arguments: code {[type]} -- [description] Keyword Arguments: end {str} -- [description] (default: {''}) Returns: [type] -- [description] """ pro = get_pro() adj = pro.adj_factor(ts_code=code, trade_date=end) return adj
字符串 '20180101' 转变成 float 类型时间 类似 time.time() 返回的类型 :param date: 字符串str -- 格式必须是 20180101 ,长度8 :return: 类型float def cover_time(date): """ 字符串 '20180101' 转变成 float 类型时间 类似 time.time() 返回的类型 :param date: 字符串str -- 格式必须是 20180101 ,长度8 :return: 类型float """ datestr = str(date)[0:8] date = time.mktime(time.strptime(datestr, '%Y%m%d')) return date
通过data新建一个stock_block Arguments: data {[type]} -- [description] Returns: [type] -- [description] def new(self, data): """通过data新建一个stock_block Arguments: data {[type]} -- [description] Returns: [type] -- [description] """ temp = copy(self) temp.__init__(data) return temp
按股票排列的查看blockname的视图 Returns: [type] -- [description] def view_code(self): """按股票排列的查看blockname的视图 Returns: [type] -- [description] """ return self.data.groupby(level=1).apply( lambda x: [item for item in x.index.remove_unused_levels().levels[0]] )
getcode 获取某一只股票的板块 Arguments: code {str} -- 股票代码 Returns: DataStruct -- [description] def get_code(self, code): """getcode 获取某一只股票的板块 Arguments: code {str} -- 股票代码 Returns: DataStruct -- [description] """ # code= [code] if isinstance(code,str) else return self.new(self.data.loc[(slice(None), code), :])
getblock 获取板块, block_name是list或者是单个str Arguments: block_name {[type]} -- [description] Returns: [type] -- [description] def get_block(self, block_name): """getblock 获取板块, block_name是list或者是单个str Arguments: block_name {[type]} -- [description] Returns: [type] -- [description] """ # block_name = [block_name] if isinstance( # block_name, str) else block_name # return QA_DataStruct_Stock_block(self.data[self.data.blockname.apply(lambda x: x in block_name)]) return self.new(self.data.loc[(block_name, slice(None)), :])
get_both_code 获取几个股票相同的版块 Arguments: code {[type]} -- [description] Returns: [type] -- [description] def get_both_code(self, code): """get_both_code 获取几个股票相同的版块 Arguments: code {[type]} -- [description] Returns: [type] -- [description] """ return self.new(self.data.loc[(slice(None), code), :])
统一的获取期货/股票tick的接口 def QA_get_tick(code, start, end, market): """ 统一的获取期货/股票tick的接口 """ res = None if market == MARKET_TYPE.STOCK_CN: res = QATdx.QA_fetch_get_stock_transaction(code, start, end) elif market == MARKET_TYPE.FUTURE_CN: res = QATdx.QA_fetch_get_future_transaction(code, start, end) return res
统一的获取期货/股票实时行情的接口 def QA_get_realtime(code, market): """ 统一的获取期货/股票实时行情的接口 """ res = None if market == MARKET_TYPE.STOCK_CN: res = QATdx.QA_fetch_get_stock_realtime(code) elif market == MARKET_TYPE.FUTURE_CN: res = QATdx.QA_fetch_get_future_realtime(code) return res
一个统一的获取k线的方法 如果使用mongo,从本地数据库获取,失败则在线获取 Arguments: code {str/list} -- 期货/股票的代码 start {str} -- 开始日期 end {str} -- 结束日期 frequence {enum} -- 频率 QA.FREQUENCE market {enum} -- 市场 QA.MARKET_TYPE source {enum} -- 来源 QA.DATASOURCE output {enum} -- 输出类型 QA.OUTPUT_FORMAT def QA_quotation(code, start, end, frequence, market, source=DATASOURCE.TDX, output=OUTPUT_FORMAT.DATAFRAME): """一个统一的获取k线的方法 如果使用mongo,从本地数据库获取,失败则在线获取 Arguments: code {str/list} -- 期货/股票的代码 start {str} -- 开始日期 end {str} -- 结束日期 frequence {enum} -- 频率 QA.FREQUENCE market {enum} -- 市场 QA.MARKET_TYPE source {enum} -- 来源 QA.DATASOURCE output {enum} -- 输出类型 QA.OUTPUT_FORMAT """ res = None if market == MARKET_TYPE.STOCK_CN: if frequence == FREQUENCE.DAY: if source == DATASOURCE.MONGO: try: res = QAQueryAdv.QA_fetch_stock_day_adv(code, start, end) except: res = None if source == DATASOURCE.TDX or res == None: res = QATdx.QA_fetch_get_stock_day(code, start, end, '00') res = QA_DataStruct_Stock_day(res.set_index(['date', 'code'])) elif source == DATASOURCE.TUSHARE: res = QATushare.QA_fetch_get_stock_day(code, start, end, '00') elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: if source == DATASOURCE.MONGO: try: res = QAQueryAdv.QA_fetch_stock_min_adv( code, start, end, frequence=frequence) except: res = None if source == DATASOURCE.TDX or res == None: res = QATdx.QA_fetch_get_stock_min( code, start, end, frequence=frequence) res = QA_DataStruct_Stock_min( res.set_index(['datetime', 'code'])) elif market == MARKET_TYPE.FUTURE_CN: if frequence == FREQUENCE.DAY: if source == DATASOURCE.MONGO: try: res = QAQueryAdv.QA_fetch_future_day_adv(code, start, end) except: res = None if source == DATASOURCE.TDX or res == None: res = QATdx.QA_fetch_get_future_day(code, start, end) res = QA_DataStruct_Future_day(res.set_index(['date', 'code'])) elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: if source == DATASOURCE.MONGO: try: res = QAQueryAdv.QA_fetch_future_min_adv( code, start, end, frequence=frequence) except: res = None if source == DATASOURCE.TDX or res == None: res = QATdx.QA_fetch_get_future_min( code, start, end, frequence=frequence) res = QA_DataStruct_Future_min( res.set_index(['datetime', 'code'])) # 指数代码和股票代码是冲突重复的, sh000001 上证指数 000001 是不同的 elif market == MARKET_TYPE.INDEX_CN: if frequence == FREQUENCE.DAY: if source == DATASOURCE.MONGO: res = QAQueryAdv.QA_fetch_index_day_adv(code, start, end) elif market == MARKET_TYPE.OPTION_CN: if source == DATASOURCE.MONGO: #res = QAQueryAdv.QA_fetch_option_day_adv(code, start, end) raise NotImplementedError('CURRENT NOT FINISH THIS METHOD') # print(type(res)) if output is OUTPUT_FORMAT.DATAFRAME: return res.data elif output is OUTPUT_FORMAT.DATASTRUCT: return res elif output is OUTPUT_FORMAT.NDARRAY: return res.to_numpy() elif output is OUTPUT_FORMAT.JSON: return res.to_json() elif output is OUTPUT_FORMAT.LIST: return res.to_list()
随机生成股票代码 :param stockNumber: 生成个数 :return: ['60XXXX', '00XXXX', '300XXX'] def QA_util_random_with_zh_stock_code(stockNumber=10): ''' 随机生成股票代码 :param stockNumber: 生成个数 :return: ['60XXXX', '00XXXX', '300XXX'] ''' codeList = [] pt = 0 for i in range(stockNumber): if pt == 0: #print("random 60XXXX") iCode = random.randint(600000, 609999) aCode = "%06d" % iCode elif pt == 1: #print("random 00XXXX") iCode = random.randint(600000, 600999) aCode = "%06d" % iCode elif pt == 2: #print("random 00XXXX") iCode = random.randint(2000, 9999) aCode = "%06d" % iCode elif pt == 3: #print("random 300XXX") iCode = random.randint(300000, 300999) aCode = "%06d" % iCode elif pt == 4: #print("random 00XXXX") iCode = random.randint(2000, 2999) aCode = "%06d" % iCode pt = (pt + 1) % 5 codeList.append(aCode) return codeList
生成account随机值 Acc+4数字id+4位大小写随机 def QA_util_random_with_topic(topic='Acc', lens=8): """ 生成account随机值 Acc+4数字id+4位大小写随机 """ _list = [chr(i) for i in range(65, 91)] + [chr(i) for i in range(97, 123) ] + [str(i) for i in range(10)] num = random.sample(_list, lens) return '{}_{}'.format(topic, ''.join(num))
支持股票/期货的更新仓位 Arguments: price {[type]} -- [description] amount {[type]} -- [description] towards {[type]} -- [description] margin: 30080 margin_long: 0 margin_short: 30080 open_cost_long: 0 open_cost_short: 419100 open_price_long: 4193 open_price_short: 4191 position_cost_long: 0 position_cost_short: 419100 position_price_long: 4193 position_price_short: 4191 position_profit: -200 position_profit_long: 0 position_profit_short: -200 def update_pos(self, price, amount, towards): """支持股票/期货的更新仓位 Arguments: price {[type]} -- [description] amount {[type]} -- [description] towards {[type]} -- [description] margin: 30080 margin_long: 0 margin_short: 30080 open_cost_long: 0 open_cost_short: 419100 open_price_long: 4193 open_price_short: 4191 position_cost_long: 0 position_cost_short: 419100 position_price_long: 4193 position_price_short: 4191 position_profit: -200 position_profit_long: 0 position_profit_short: -200 """ temp_cost = amount*price * \ self.market_preset.get('unit_table', 1) # if towards == ORDER_DIRECTION.SELL_CLOSE: if towards == ORDER_DIRECTION.BUY: # 股票模式/ 期货买入开仓 self.volume_long_today += amount elif towards == ORDER_DIRECTION.SELL: # 股票卖出模式: # 今日买入仓位不能卖出 if self.volume_long_his > amount: self.volume_long_his -= amount elif towards == ORDER_DIRECTION.BUY_OPEN: # 增加保证金 self.margin_long += temp_cost * \ self.market_preset['buy_frozen_coeff'] # 重算开仓均价 self.open_price_long = ( self.open_price_long * self.volume_long + amount*price) / (amount + self.volume_long) # 重算持仓均价 self.position_price_long = ( self.position_price_long * self.volume_long + amount * price) / (amount + self.volume_long) # 增加今仓数量 ==> 会自动增加volume_long self.volume_long_today += amount # self.open_cost_long += temp_cost elif towards == ORDER_DIRECTION.SELL_OPEN: # 增加保证金 self.margin_short += temp_cost * \ self.market_preset['sell_frozen_coeff'] # 重新计算开仓/持仓成本 self.open_price_short = ( self.open_price_short * self.volume_short + amount*price) / (amount + self.volume_short) self.position_price_short = ( self.position_price_short * self.volume_short + amount * price) / (amount + self.volume_short) self.open_cost_short += temp_cost self.volume_short_today += amount elif towards == ORDER_DIRECTION.BUY_CLOSETODAY: if self.volume_short_today > amount: self.position_cost_short = self.position_cost_short * \ (self.volume_short-amount)/self.volume_short self.open_cost_short = self.open_cost_short * \ (self.volume_short-amount)/self.volume_short self.volume_short_today -= amount # close_profit = (self.position_price_short - price) * volume * position->ins->volume_multiple; #self.volume_short_frozen_today += amount # 释放保证金 # TODO # self.margin_short #self.open_cost_short = price* amount elif towards == ORDER_DIRECTION.SELL_CLOSETODAY: if self.volume_long_today > amount: self.position_cost_long = self.position_cost_long * \ (self.volume_long - amount)/self.volume_long self.open_cost_long = self.open_cost_long * \ (self.volume_long-amount)/self.volume_long self.volume_long_today -= amount elif towards == ORDER_DIRECTION.BUY_CLOSE: # 有昨仓先平昨仓 self.position_cost_short = self.position_cost_short * \ (self.volume_short-amount)/self.volume_short self.open_cost_short = self.open_cost_short * \ (self.volume_short-amount)/self.volume_short if self.volume_short_his >= amount: self.volume_short_his -= amount else: self.volume_short_today -= (amount - self.volume_short_his) self.volume_short_his = 0 elif towards == ORDER_DIRECTION.SELL_CLOSE: # 有昨仓先平昨仓 self.position_cost_long = self.position_cost_long * \ (self.volume_long - amount)/self.volume_long self.open_cost_long = self.open_cost_long * \ (self.volume_long-amount)/self.volume_long if self.volume_long_his >= amount: self.volume_long_his -= amount else: self.volume_long_today -= (amount - self.volume_long_his) self.volume_long_his -= amount
收盘后的结算事件 def settle(self): """收盘后的结算事件 """ self.volume_long_his += self.volume_long_today self.volume_long_today = 0 self.volume_long_frozen_today = 0 self.volume_short_his += self.volume_short_today self.volume_short_today = 0 self.volume_short_frozen_today = 0
可平仓数量 Returns: [type] -- [description] def close_available(self): """可平仓数量 Returns: [type] -- [description] """ return { 'volume_long': self.volume_long - self.volume_long_frozen, 'volume_short': self.volume_short - self.volume_short_frozen }
委托回报 def orderAction(self, order:QA_Order): """ 委托回报 """ return self.pms[order.code][order.order_id].receive_order(order)
聚宽实现方式 save current day's stock_min data def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None): """ 聚宽实现方式 save current day's stock_min data """ # 导入聚宽模块且进行登录 try: import jqdatasdk # 请自行将 JQUSERNAME 和 JQUSERPASSWD 修改为自己的账号密码 jqdatasdk.auth("JQUSERNAME", "JQUSERPASSWD") except: raise ModuleNotFoundError # 股票代码格式化 code_list = list( map( lambda x: x + ".XSHG" if x[0] == "6" else x + ".XSHE", QA_fetch_get_stock_list().code.unique().tolist(), )) coll = client.stock_min coll.create_index([ ("code", pymongo.ASCENDING), ("time_stamp", pymongo.ASCENDING), ("date_stamp", pymongo.ASCENDING), ]) err = [] def __transform_jq_to_qa(df, code, type_): """ 处理 jqdata 分钟数据为 qa 格式,并存入数据库 1. jdatasdk 数据格式: open close high low volume money 2018-12-03 09:31:00 10.59 10.61 10.61 10.59 8339100.0 88377836.0 2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配,具体处理详见相应源码 open close high low vol amount ... datetime 2018-12-03 09:31:00 10.99 10.90 10.99 10.90 2.211700e+06 2.425626e+07 ... """ if df is None or len(df) == 0: raise ValueError("没有聚宽数据") df = df.reset_index().rename(columns={ "index": "datetime", "volume": "vol", "money": "amount" }) df["code"] = code df["date"] = df.datetime.map(str).str.slice(0, 10) df = df.set_index("datetime", drop=False) df["date_stamp"] = df["date"].apply(lambda x: QA_util_date_stamp(x)) df["time_stamp"] = ( df["datetime"].map(str).apply(lambda x: QA_util_time_stamp(x))) df["type"] = type_ return df[[ "open", "close", "high", "low", "vol", "amount", "datetime", "code", "date", "date_stamp", "time_stamp", "type", ]] def __saving_work(code, coll): QA_util_log_info( "##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log) try: for type_ in ["1min", "5min", "15min", "30min", "60min"]: col_filter = {"code": str(code)[0:6], "type": type_} ref_ = coll.find(col_filter) end_time = str(now_time())[0:19] if coll.count_documents(col_filter) > 0: start_time = ref_[coll.count_documents( col_filter) - 1]["datetime"] QA_util_log_info( "##JOB03.{} Now Saving {} from {} to {} == {}".format( ["1min", "5min", "15min", "30min", "60min"].index(type_), str(code)[0:6], start_time, end_time, type_, ), ui_log=ui_log, ) if start_time != end_time: df = jqdatasdk.get_price( security=code, start_date=start_time, end_date=end_time, frequency=type_.split("min")[0]+"m", ) __data = __transform_jq_to_qa( df, code=code[:6], type_=type_) if len(__data) > 1: coll.insert_many( QA_util_to_json_from_pandas(__data)[1::]) else: start_time = "2015-01-01 09:30:00" QA_util_log_info( "##JOB03.{} Now Saving {} from {} to {} == {}".format( ["1min", "5min", "15min", "30min", "60min"].index(type_), str(code)[0:6], start_time, end_time, type_, ), ui_log=ui_log, ) if start_time != end_time: __data == __transform_jq_to_qa( jqdatasdk.get_price( security=code, start_date=start_time, end_date=end_time, frequency=type_.split("min")[0]+"m", ), code=code[:6], type_=type_ ) if len(__data) > 1: coll.insert_many( QA_util_to_json_from_pandas(__data)[1::]) except Exception as e: QA_util_log_info(e, ui_log=ui_log) err.append(code) QA_util_log_info(err, ui_log=ui_log) # 聚宽之多允许三个线程连接 executor = ThreadPoolExecutor(max_workers=2) res = { executor.submit(__saving_work, code_list[i_], coll) for i_ in range(len(code_list)) } count = 0 for i_ in concurrent.futures.as_completed(res): QA_util_log_info( 'The {} of Total {}'.format(count, len(code_list)), ui_log=ui_log ) strProgress = "DOWNLOAD PROGRESS {} ".format( str(float(count / len(code_list) * 100))[0:4] + "%") intProgress = int(count / len(code_list) * 10000.0) QA_util_log_info( strProgress, ui_log, ui_progress=ui_progress, ui_progress_int_value=intProgress ) count = count + 1 if len(err) < 1: QA_util_log_info("SUCCESS", ui_log=ui_log) else: QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log) QA_util_log_info(err, ui_log=ui_log)
Execute a command on the command-line. :param str,list command: The command to run :param bool shell: Whether or not to use the shell. This is optional; if ``command`` is a basestring, shell will be set to True, otherwise it will be false. You can override this behavior by setting this parameter directly. :param str working_dir: The directory in which to run the command. :param bool echo: Whether or not to print the output from the command to stdout. :param int echo_indent: Any number of spaces to indent the echo for clarity :returns: tuple: (return code, stdout) Example >>> from executor import execute >>> return_code, text = execute("dir") def execute(command, shell=None, working_dir=".", echo=False, echo_indent=0): """Execute a command on the command-line. :param str,list command: The command to run :param bool shell: Whether or not to use the shell. This is optional; if ``command`` is a basestring, shell will be set to True, otherwise it will be false. You can override this behavior by setting this parameter directly. :param str working_dir: The directory in which to run the command. :param bool echo: Whether or not to print the output from the command to stdout. :param int echo_indent: Any number of spaces to indent the echo for clarity :returns: tuple: (return code, stdout) Example >>> from executor import execute >>> return_code, text = execute("dir") """ if shell is None: shell = True if isinstance(command, str) else False p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=shell, cwd=working_dir) if echo: stdout = "" while p.poll() is None: # This blocks until it receives a newline. line = p.stdout.readline() print(" " * echo_indent, line, end="") stdout += line # Read any last bits line = p.stdout.read() print(" " * echo_indent, line, end="") print() stdout += line else: stdout, _ = p.communicate() return (p.returncode, stdout)
使用数据库数据计算复权 def QA_data_calc_marketvalue(data, xdxr): '使用数据库数据计算复权' mv = xdxr.query('category!=6').loc[:, ['shares_after', 'liquidity_after']].dropna() res = pd.concat([data, mv], axis=1) res = res.assign( shares=res.shares_after.fillna(method='ffill'), lshares=res.liquidity_after.fillna(method='ffill') ) return res.assign(mv=res.close*res.shares*10000, liquidity_mv=res.close*res.lshares*10000).drop(['shares_after', 'liquidity_after'], axis=1)\ .loc[(slice(data.index.remove_unused_levels().levels[0][0],data.index.remove_unused_levels().levels[0][-1]),slice(None)),:]
1.DIF向上突破DEA,买入信号参考。 2.DIF向下跌破DEA,卖出信号参考。 def MACD_JCSC(dataframe, SHORT=12, LONG=26, M=9): """ 1.DIF向上突破DEA,买入信号参考。 2.DIF向下跌破DEA,卖出信号参考。 """ CLOSE = dataframe.close DIFF = QA.EMA(CLOSE, SHORT) - QA.EMA(CLOSE, LONG) DEA = QA.EMA(DIFF, M) MACD = 2*(DIFF-DEA) CROSS_JC = QA.CROSS(DIFF, DEA) CROSS_SC = QA.CROSS(DEA, DIFF) ZERO = 0 return pd.DataFrame({'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD, 'CROSS_JC': CROSS_JC, 'CROSS_SC': CROSS_SC, 'ZERO': ZERO})
Create the tables needed to store the information. def _create(self, cache_file): """Create the tables needed to store the information.""" conn = sqlite3.connect(cache_file) cur = conn.cursor() cur.execute("PRAGMA foreign_keys = ON") cur.execute(''' CREATE TABLE jobs( hash TEXT NOT NULL UNIQUE PRIMARY KEY, description TEXT NOT NULL, last_run REAL, next_run REAL, last_run_result INTEGER)''') cur.execute(''' CREATE TABLE history( hash TEXT, description TEXT, time REAL, result INTEGER, FOREIGN KEY(hash) REFERENCES jobs(hash))''') conn.commit() conn.close()
Retrieves the job with the selected ID. :param str id: The ID of the job :returns: The dictionary of the job if found, None otherwise def get(self, id): """Retrieves the job with the selected ID. :param str id: The ID of the job :returns: The dictionary of the job if found, None otherwise """ self.cur.execute("SELECT * FROM jobs WHERE hash=?", (id,)) item = self.cur.fetchone() if item: return dict(zip( ("id", "description", "last-run", "next-run", "last-run-result"), item)) return None
Update last_run, next_run, and last_run_result for an existing job. :param dict job: The job dictionary :returns: True def update(self, job): """Update last_run, next_run, and last_run_result for an existing job. :param dict job: The job dictionary :returns: True """ self.cur.execute('''UPDATE jobs SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''', ( job["last-run"], job["next-run"], job["last-run-result"], job["id"]))
Adds a new job into the cache. :param dict job: The job dictionary :returns: True def add_job(self, job): """Adds a new job into the cache. :param dict job: The job dictionary :returns: True """ self.cur.execute("INSERT INTO jobs VALUES(?,?,?,?,?)", ( job["id"], job["description"], job["last-run"], job["next-run"], job["last-run-result"])) return True
Adds a job run result to the history table. :param dict job: The job dictionary :returns: True def add_result(self, job): """Adds a job run result to the history table. :param dict job: The job dictionary :returns: True """ self.cur.execute( "INSERT INTO history VALUES(?,?,?,?)", (job["id"], job["description"], job["last-run"], job["last-run-result"])) return True
tick 采样为 分钟数据 1. 仅使用将 tick 采样为 1 分钟数据 2. 仅测试过,与通达信 1 分钟数据达成一致 3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试 demo: df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001', start='2018-08-01 09:25:00', end='2018-08-03 15:00:00') df_min = QA_data_tick_resample_1min(df) def QA_data_tick_resample_1min(tick, type_='1min', if_drop=True): """ tick 采样为 分钟数据 1. 仅使用将 tick 采样为 1 分钟数据 2. 仅测试过,与通达信 1 分钟数据达成一致 3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试 demo: df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001', start='2018-08-01 09:25:00', end='2018-08-03 15:00:00') df_min = QA_data_tick_resample_1min(df) """ tick = tick.assign(amount=tick.price * tick.vol) resx = pd.DataFrame() _dates = set(tick.date) for date in sorted(list(_dates)): _data = tick.loc[tick.date == date] # morning min bar _data1 = _data[time(9, 25):time(11, 30)].resample( type_, closed='left', base=30, loffset=type_ ).apply( { 'price': 'ohlc', 'vol': 'sum', 'code': 'last', 'amount': 'sum' } ) _data1.columns = _data1.columns.droplevel(0) # do fix on the first and last bar # 某些股票某些日期没有集合竞价信息,譬如 002468 在 2017 年 6 月 5 日的数据 if len(_data.loc[time(9, 25):time(9, 25)]) > 0: _data1.loc[time(9, 31):time(9, 31), 'open'] = _data1.loc[time(9, 26):time(9, 26), 'open'].values _data1.loc[time(9, 31):time(9, 31), 'high'] = _data1.loc[time(9, 26):time(9, 31), 'high'].max() _data1.loc[time(9, 31):time(9, 31), 'low'] = _data1.loc[time(9, 26):time(9, 31), 'low'].min() _data1.loc[time(9, 31):time(9, 31), 'vol'] = _data1.loc[time(9, 26):time(9, 31), 'vol'].sum() _data1.loc[time(9, 31):time(9, 31), 'amount'] = _data1.loc[time(9, 26):time(9, 31), 'amount'].sum() # 通达信分笔数据有的有 11:30 数据,有的没有 if len(_data.loc[time(11, 30):time(11, 30)]) > 0: _data1.loc[time(11, 30):time(11, 30), 'high'] = _data1.loc[time(11, 30):time(11, 31), 'high'].max() _data1.loc[time(11, 30):time(11, 30), 'low'] = _data1.loc[time(11, 30):time(11, 31), 'low'].min() _data1.loc[time(11, 30):time(11, 30), 'close'] = _data1.loc[time(11, 31):time(11, 31), 'close'].values _data1.loc[time(11, 30):time(11, 30), 'vol'] = _data1.loc[time(11, 30):time(11, 31), 'vol'].sum() _data1.loc[time(11, 30):time(11, 30), 'amount'] = _data1.loc[time(11, 30):time(11, 31), 'amount'].sum() _data1 = _data1.loc[time(9, 31):time(11, 30)] # afternoon min bar _data2 = _data[time(13, 0):time(15, 0)].resample( type_, closed='left', base=30, loffset=type_ ).apply( { 'price': 'ohlc', 'vol': 'sum', 'code': 'last', 'amount': 'sum' } ) _data2.columns = _data2.columns.droplevel(0) # 沪市股票在 2018-08-20 起,尾盘 3 分钟集合竞价 if (pd.Timestamp(date) < pd.Timestamp('2018-08-20')) and (tick.code.iloc[0][0] == '6'): # 避免出现 tick 数据没有 1:00 的值 if len(_data.loc[time(13, 0):time(13, 0)]) > 0: _data2.loc[time(15, 0):time(15, 0), 'high'] = _data2.loc[time(15, 0):time(15, 1), 'high'].max() _data2.loc[time(15, 0):time(15, 0), 'low'] = _data2.loc[time(15, 0):time(15, 1), 'low'].min() _data2.loc[time(15, 0):time(15, 0), 'close'] = _data2.loc[time(15, 1):time(15, 1), 'close'].values else: # 避免出现 tick 数据没有 15:00 的值 if len(_data.loc[time(13, 0):time(13, 0)]) > 0: _data2.loc[time(15, 0):time(15, 0)] = _data2.loc[time(15, 1):time(15, 1)].values _data2 = _data2.loc[time(13, 1):time(15, 0)] resx = resx.append(_data1).append(_data2) resx['vol'] = resx['vol'] * 100.0 resx['volume'] = resx['vol'] resx['type'] = '1min' if if_drop: resx = resx.dropna() return resx.reset_index().drop_duplicates().set_index(['datetime', 'code'])
tick采样成任意级别分钟线 Arguments: tick {[type]} -- transaction Returns: [type] -- [description] def QA_data_tick_resample(tick, type_='1min'): """tick采样成任意级别分钟线 Arguments: tick {[type]} -- transaction Returns: [type] -- [description] """ tick = tick.assign(amount=tick.price * tick.vol) resx = pd.DataFrame() _temp = set(tick.index.date) for item in _temp: _data = tick.loc[str(item)] _data1 = _data[time(9, 31):time(11, 30)].resample( type_, closed='right', base=30, loffset=type_ ).apply( { 'price': 'ohlc', 'vol': 'sum', 'code': 'last', 'amount': 'sum' } ) _data2 = _data[time(13, 1):time(15, 0)].resample( type_, closed='right', loffset=type_ ).apply( { 'price': 'ohlc', 'vol': 'sum', 'code': 'last', 'amount': 'sum' } ) resx = resx.append(_data1).append(_data2) resx.columns = resx.columns.droplevel(0) return resx.reset_index().drop_duplicates().set_index(['datetime', 'code'])
tick采样成任意级别分钟线 Arguments: tick {[type]} -- transaction Returns: [type] -- [description] def QA_data_ctptick_resample(tick, type_='1min'): """tick采样成任意级别分钟线 Arguments: tick {[type]} -- transaction Returns: [type] -- [description] """ resx = pd.DataFrame() _temp = set(tick.TradingDay) for item in _temp: _data = tick.query('TradingDay=="{}"'.format(item)) try: _data.loc[time(20, 0):time(21, 0), 'volume'] = 0 except: pass _data.volume = _data.volume.diff() _data = _data.assign(amount=_data.LastPrice * _data.volume) _data0 = _data[time(0, 0):time(2, 30)].resample( type_, closed='right', base=30, loffset=type_ ).apply( { 'LastPrice': 'ohlc', 'volume': 'sum', 'code': 'last', 'amount': 'sum' } ) _data1 = _data[time(9, 0):time(11, 30)].resample( type_, closed='right', base=30, loffset=type_ ).apply( { 'LastPrice': 'ohlc', 'volume': 'sum', 'code': 'last', 'amount': 'sum' } ) _data2 = _data[time(13, 1):time(15, 0)].resample( type_, closed='right', base=30, loffset=type_ ).apply( { 'LastPrice': 'ohlc', 'volume': 'sum', 'code': 'last', 'amount': 'sum' } ) _data3 = _data[time(21, 0):time(23, 59)].resample( type_, closed='left', loffset=type_ ).apply( { 'LastPrice': 'ohlc', 'volume': 'sum', 'code': 'last', 'amount': 'sum' } ) resx = resx.append(_data0).append(_data1).append(_data2).append(_data3) resx.columns = resx.columns.droplevel(0) return resx.reset_index().drop_duplicates().set_index(['datetime', 'code']).sort_index()
分钟线采样成大周期 分钟线采样成子级别的分钟线 time+ OHLC==> resample Arguments: min {[type]} -- [description] raw_type {[type]} -- [description] new_type {[type]} -- [description] def QA_data_min_resample(min_data, type_='5min'): """分钟线采样成大周期 分钟线采样成子级别的分钟线 time+ OHLC==> resample Arguments: min {[type]} -- [description] raw_type {[type]} -- [description] new_type {[type]} -- [description] """ try: min_data = min_data.reset_index().set_index('datetime', drop=False) except: min_data = min_data.set_index('datetime', drop=False) CONVERSION = { 'code': 'first', 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'vol': 'sum', 'amount': 'sum' } if 'vol' in min_data.columns else { 'code': 'first', 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum', 'amount': 'sum' } resx = pd.DataFrame() for item in set(min_data.index.date): min_data_p = min_data.loc[str(item)] n = min_data_p['{} 21:00:00'.format(item):].resample( type_, base=30, closed='right', loffset=type_ ).apply(CONVERSION) d = min_data_p[:'{} 11:30:00'.format(item)].resample( type_, base=30, closed='right', loffset=type_ ).apply(CONVERSION) f = min_data_p['{} 13:00:00'.format(item):].resample( type_, closed='right', loffset=type_ ).apply(CONVERSION) resx = resx.append(d).append(f) return resx.dropna().reset_index().set_index(['datetime', 'code'])
期货分钟线采样成大周期 分钟线采样成子级别的分钟线 future: vol ==> trade amount X def QA_data_futuremin_resample(min_data, type_='5min'): """期货分钟线采样成大周期 分钟线采样成子级别的分钟线 future: vol ==> trade amount X """ min_data.tradeime = pd.to_datetime(min_data.tradetime) CONVERSION = { 'code': 'first', 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'trade': 'sum', 'tradetime': 'last', 'date': 'last' } resx = min_data.resample( type_, closed='right', loffset=type_ ).apply(CONVERSION) return resx.dropna().reset_index().set_index(['datetime', 'code'])
日线降采样 Arguments: day_data {[type]} -- [description] Keyword Arguments: type_ {str} -- [description] (default: {'w'}) Returns: [type] -- [description] def QA_data_day_resample(day_data, type_='w'): """日线降采样 Arguments: day_data {[type]} -- [description] Keyword Arguments: type_ {str} -- [description] (default: {'w'}) Returns: [type] -- [description] """ # return day_data_p.assign(open=day_data.open.resample(type_).first(),high=day_data.high.resample(type_).max(),low=day_data.low.resample(type_).min(),\ # vol=day_data.vol.resample(type_).sum() if 'vol' in day_data.columns else day_data.volume.resample(type_).sum(),\ # amount=day_data.amount.resample(type_).sum()).dropna().set_index('date') try: day_data = day_data.reset_index().set_index('date', drop=False) except: day_data = day_data.set_index('date', drop=False) CONVERSION = { 'code': 'first', 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'vol': 'sum', 'amount': 'sum' } if 'vol' in day_data.columns else { 'code': 'first', 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum', 'amount': 'sum' } return day_data.resample( type_, closed='right' ).apply(CONVERSION).dropna().reset_index().set_index(['date', 'code'])
save stock info Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_stock_info(engine, client=DATABASE): """save stock info Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_stock_info(client=client)
save stock_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_stock_list(engine, client=DATABASE): """save stock_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_stock_list(client=client)
save index_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_index_list(engine, client=DATABASE): """save index_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_index_list(client=client)
save etf_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_etf_list(engine, client=DATABASE): """save etf_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_etf_list(client=client)
save future_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_future_list(engine, client=DATABASE): """save future_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_future_list(client=client)
save future_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_future_day(engine, client=DATABASE): """save future_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_future_day(client=client)
save future_day_all Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_future_day_all(engine, client=DATABASE): """save future_day_all Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_future_day_all(client=client)
save future_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_future_min(engine, client=DATABASE): """save future_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_future_min(client=client)
[summary] Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_future_min_all(engine, client=DATABASE): """[summary] Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_future_min_all(client=client)
save stock_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_stock_day(engine, client=DATABASE, paralleled=False): """save stock_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine, paralleled=paralleled) engine.QA_SU_save_stock_day(client=client)
:param engine: :param client: :return: def QA_SU_save_option_commodity_min(engine, client=DATABASE): ''' :param engine: :param client: :return: ''' engine = select_save_engine(engine) engine.QA_SU_save_option_commodity_min(client=client)
:param engine: :param client: :return: def QA_SU_save_option_commodity_day(engine, client=DATABASE): ''' :param engine: :param client: :return: ''' engine = select_save_engine(engine) engine.QA_SU_save_option_commodity_day(client=client)
save stock_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_stock_min(engine, client=DATABASE): """save stock_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_stock_min(client=client)
save index_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_index_day(engine, client=DATABASE): """save index_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_index_day(client=client)
save index_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_index_min(engine, client=DATABASE): """save index_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_index_min(client=client)
save etf_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_etf_day(engine, client=DATABASE): """save etf_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_etf_day(client=client)
save etf_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) def QA_SU_save_etf_min(engine, client=DATABASE): """save etf_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_etf_min(client=client)