partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
QA_Account.get_history
返回历史成交 Arguments: start {str} -- [description] end {str]} -- [description]
QUANTAXIS/QAARP/QAAccount.py
def get_history(self, start, end): """返回历史成交 Arguments: start {str} -- [description] end {str]} -- [description] """ return self.history_table.set_index( 'datetime', drop=False ).loc[slice(pd.Timestamp(start), pd.Timestamp(end))]
def get_history(self, start, end): """返回历史成交 Arguments: start {str} -- [description] end {str]} -- [description] """ return self.history_table.set_index( 'datetime', drop=False ).loc[slice(pd.Timestamp(start), pd.Timestamp(end))]
[ "返回历史成交" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAAccount.py#L1868-L1879
[ "def", "get_history", "(", "self", ",", "start", ",", "end", ")", ":", "return", "self", ".", "history_table", ".", "set_index", "(", "'datetime'", ",", "drop", "=", "False", ")", ".", "loc", "[", "slice", "(", "pd", ".", "Timestamp", "(", "start", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SU_save_order
存储order_handler的order_status Arguments: orderlist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
QUANTAXIS/QASU/save_orderhandler.py
def QA_SU_save_order(orderlist, client=DATABASE): """存储order_handler的order_status Arguments: orderlist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ if isinstance(orderlist, pd.DataFrame): collection = client.order collection.create_index( [('account_cookie', ASCENDING), ('realorder_id', ASCENDING)], unique=True ) try: orderlist = QA_util_to_json_from_pandas(orderlist.reset_index()) for item in orderlist: if item: #item['date']= QA_util_get_order_day() collection.update_one( { 'account_cookie': item.get('account_cookie'), 'realorder_id': item.get('realorder_id') }, {'$set': item}, upsert=True ) except Exception as e: print(e) pass
def QA_SU_save_order(orderlist, client=DATABASE): """存储order_handler的order_status Arguments: orderlist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ if isinstance(orderlist, pd.DataFrame): collection = client.order collection.create_index( [('account_cookie', ASCENDING), ('realorder_id', ASCENDING)], unique=True ) try: orderlist = QA_util_to_json_from_pandas(orderlist.reset_index()) for item in orderlist: if item: #item['date']= QA_util_get_order_day() collection.update_one( { 'account_cookie': item.get('account_cookie'), 'realorder_id': item.get('realorder_id') }, {'$set': item}, upsert=True ) except Exception as e: print(e) pass
[ "存储order_handler的order_status" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_orderhandler.py#L31-L67
[ "def", "QA_SU_save_order", "(", "orderlist", ",", "client", "=", "DATABASE", ")", ":", "if", "isinstance", "(", "orderlist", ",", "pd", ".", "DataFrame", ")", ":", "collection", "=", "client", ".", "order", "collection", ".", "create_index", "(", "[", "(",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SU_save_deal
存储order_handler的deal_status Arguments: dealist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
QUANTAXIS/QASU/save_orderhandler.py
def QA_SU_save_deal(dealist, client=DATABASE): """存储order_handler的deal_status Arguments: dealist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ if isinstance(dealist, pd.DataFrame): collection = client.deal collection.create_index( [('account_cookie', ASCENDING), ('trade_id', ASCENDING)], unique=True ) try: dealist = QA_util_to_json_from_pandas(dealist.reset_index()) collection.insert_many(dealist, ordered=False) except Exception as e: pass
def QA_SU_save_deal(dealist, client=DATABASE): """存储order_handler的deal_status Arguments: dealist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ if isinstance(dealist, pd.DataFrame): collection = client.deal collection.create_index( [('account_cookie', ASCENDING), ('trade_id', ASCENDING)], unique=True ) try: dealist = QA_util_to_json_from_pandas(dealist.reset_index()) collection.insert_many(dealist, ordered=False) except Exception as e: pass
[ "存储order_handler的deal_status" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_orderhandler.py#L70-L96
[ "def", "QA_SU_save_deal", "(", "dealist", ",", "client", "=", "DATABASE", ")", ":", "if", "isinstance", "(", "dealist", ",", "pd", ".", "DataFrame", ")", ":", "collection", "=", "client", ".", "deal", "collection", ".", "create_index", "(", "[", "(", "'a...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SU_save_order_queue
增量存储order_queue Arguments: order_queue {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
QUANTAXIS/QASU/save_orderhandler.py
def QA_SU_save_order_queue(order_queue, client=DATABASE): """增量存储order_queue Arguments: order_queue {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ collection = client.order_queue collection.create_index( [('account_cookie', ASCENDING), ('order_id', ASCENDING)], unique=True ) for order in order_queue.values(): order_json = order.to_dict() try: collection.update_one( { 'account_cookie': order_json.get('account_cookie'), 'order_id': order_json.get('order_id') }, {'$set': order_json}, upsert=True ) except Exception as e: print(e)
def QA_SU_save_order_queue(order_queue, client=DATABASE): """增量存储order_queue Arguments: order_queue {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ collection = client.order_queue collection.create_index( [('account_cookie', ASCENDING), ('order_id', ASCENDING)], unique=True ) for order in order_queue.values(): order_json = order.to_dict() try: collection.update_one( { 'account_cookie': order_json.get('account_cookie'), 'order_id': order_json.get('order_id') }, {'$set': order_json}, upsert=True ) except Exception as e: print(e)
[ "增量存储order_queue" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_orderhandler.py#L99-L128
[ "def", "QA_SU_save_order_queue", "(", "order_queue", ",", "client", "=", "DATABASE", ")", ":", "collection", "=", "client", ".", "order_queue", "collection", ".", "create_index", "(", "[", "(", "'account_cookie'", ",", "ASCENDING", ")", ",", "(", "'order_id'", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
SMA
威廉SMA算法 本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index 2018/5/3 @yutiansut
QUANTAXIS/QAIndicator/base.py
def SMA(Series, N, M=1): """ 威廉SMA算法 本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index 2018/5/3 @yutiansut """ ret = [] i = 1 length = len(Series) # 跳过X中前面几个 nan 值 while i < length: if np.isnan(Series.iloc[i]): i += 1 else: break preY = Series.iloc[i] # Y' ret.append(preY) while i < length: Y = (M * Series.iloc[i] + (N - M) * preY) / float(N) ret.append(Y) preY = Y i += 1 return pd.Series(ret, index=Series.tail(len(ret)).index)
def SMA(Series, N, M=1): """ 威廉SMA算法 本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index 2018/5/3 @yutiansut """ ret = [] i = 1 length = len(Series) # 跳过X中前面几个 nan 值 while i < length: if np.isnan(Series.iloc[i]): i += 1 else: break preY = Series.iloc[i] # Y' ret.append(preY) while i < length: Y = (M * Series.iloc[i] + (N - M) * preY) / float(N) ret.append(Y) preY = Y i += 1 return pd.Series(ret, index=Series.tail(len(ret)).index)
[ "威廉SMA算法" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L50-L74
[ "def", "SMA", "(", "Series", ",", "N", ",", "M", "=", "1", ")", ":", "ret", "=", "[", "]", "i", "=", "1", "length", "=", "len", "(", "Series", ")", "# 跳过X中前面几个 nan 值", "while", "i", "<", "length", ":", "if", "np", ".", "isnan", "(", "Series", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
CROSS
A<B then A>B A上穿B B下穿A Arguments: A {[type]} -- [description] B {[type]} -- [description] Returns: [type] -- [description]
QUANTAXIS/QAIndicator/base.py
def CROSS(A, B): """A<B then A>B A上穿B B下穿A Arguments: A {[type]} -- [description] B {[type]} -- [description] Returns: [type] -- [description] """ var = np.where(A < B, 1, 0) return (pd.Series(var, index=A.index).diff() < 0).apply(int)
def CROSS(A, B): """A<B then A>B A上穿B B下穿A Arguments: A {[type]} -- [description] B {[type]} -- [description] Returns: [type] -- [description] """ var = np.where(A < B, 1, 0) return (pd.Series(var, index=A.index).diff() < 0).apply(int)
[ "A<B", "then", "A", ">", "B", "A上穿B", "B下穿A" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L114-L126
[ "def", "CROSS", "(", "A", ",", "B", ")", ":", "var", "=", "np", ".", "where", "(", "A", "<", "B", ",", "1", ",", "0", ")", "return", "(", "pd", ".", "Series", "(", "var", ",", "index", "=", "A", ".", "index", ")", ".", "diff", "(", ")", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
COUNT
2018/05/23 修改 参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429 现在返回的是series
QUANTAXIS/QAIndicator/base.py
def COUNT(COND, N): """ 2018/05/23 修改 参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429 现在返回的是series """ return pd.Series(np.where(COND, 1, 0), index=COND.index).rolling(N).sum()
def COUNT(COND, N): """ 2018/05/23 修改 参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429 现在返回的是series """ return pd.Series(np.where(COND, 1, 0), index=COND.index).rolling(N).sum()
[ "2018", "/", "05", "/", "23", "修改" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L129-L137
[ "def", "COUNT", "(", "COND", ",", "N", ")", ":", "return", "pd", ".", "Series", "(", "np", ".", "where", "(", "COND", ",", "1", ",", "0", ")", ",", "index", "=", "COND", ".", "index", ")", ".", "rolling", "(", "N", ")", ".", "sum", "(", ")"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
LAST
表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description]
QUANTAXIS/QAIndicator/base.py
def LAST(COND, N1, N2): """表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description] """ N2 = 1 if N2 == 0 else N2 assert N2 > 0 assert N1 > N2 return COND.iloc[-N1:-N2].all()
def LAST(COND, N1, N2): """表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description] """ N2 = 1 if N2 == 0 else N2 assert N2 > 0 assert N1 > N2 return COND.iloc[-N1:-N2].all()
[ "表达持续性", "从前N1日到前N2日一直满足COND条件" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L160-L172
[ "def", "LAST", "(", "COND", ",", "N1", ",", "N2", ")", ":", "N2", "=", "1", "if", "N2", "==", "0", "else", "N2", "assert", "N2", ">", "0", "assert", "N1", ">", "N2", "return", "COND", ".", "iloc", "[", "-", "N1", ":", "-", "N2", "]", ".", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
AVEDEV
平均绝对偏差 mean absolute deviation 修正: 2018-05-25 之前用mad的计算模式依然返回的是单值
QUANTAXIS/QAIndicator/base.py
def AVEDEV(Series, N): """ 平均绝对偏差 mean absolute deviation 修正: 2018-05-25 之前用mad的计算模式依然返回的是单值 """ return Series.rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True)
def AVEDEV(Series, N): """ 平均绝对偏差 mean absolute deviation 修正: 2018-05-25 之前用mad的计算模式依然返回的是单值 """ return Series.rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True)
[ "平均绝对偏差", "mean", "absolute", "deviation", "修正", ":", "2018", "-", "05", "-", "25" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L179-L186
[ "def", "AVEDEV", "(", "Series", ",", "N", ")", ":", "return", "Series", ".", "rolling", "(", "N", ")", ".", "apply", "(", "lambda", "x", ":", "(", "np", ".", "abs", "(", "x", "-", "x", ".", "mean", "(", ")", ")", ")", ".", "mean", "(", ")",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
MACD
macd指标 仅适用于Series 对于DATAFRAME的应用请使用QA_indicator_macd
QUANTAXIS/QAIndicator/base.py
def MACD(Series, FAST, SLOW, MID): """macd指标 仅适用于Series 对于DATAFRAME的应用请使用QA_indicator_macd """ EMAFAST = EMA(Series, FAST) EMASLOW = EMA(Series, SLOW) DIFF = EMAFAST - EMASLOW DEA = EMA(DIFF, MID) MACD = (DIFF - DEA) * 2 DICT = {'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD} VAR = pd.DataFrame(DICT) return VAR
def MACD(Series, FAST, SLOW, MID): """macd指标 仅适用于Series 对于DATAFRAME的应用请使用QA_indicator_macd """ EMAFAST = EMA(Series, FAST) EMASLOW = EMA(Series, SLOW) DIFF = EMAFAST - EMASLOW DEA = EMA(DIFF, MID) MACD = (DIFF - DEA) * 2 DICT = {'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD} VAR = pd.DataFrame(DICT) return VAR
[ "macd指标", "仅适用于Series", "对于DATAFRAME的应用请使用QA_indicator_macd" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L189-L200
[ "def", "MACD", "(", "Series", ",", "FAST", ",", "SLOW", ",", "MID", ")", ":", "EMAFAST", "=", "EMA", "(", "Series", ",", "FAST", ")", "EMASLOW", "=", "EMA", "(", "Series", ",", "SLOW", ")", "DIFF", "=", "EMAFAST", "-", "EMASLOW", "DEA", "=", "EMA...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
BBI
多空指标
QUANTAXIS/QAIndicator/base.py
def BBI(Series, N1, N2, N3, N4): '多空指标' bbi = (MA(Series, N1) + MA(Series, N2) + MA(Series, N3) + MA(Series, N4)) / 4 DICT = {'BBI': bbi} VAR = pd.DataFrame(DICT) return VAR
def BBI(Series, N1, N2, N3, N4): '多空指标' bbi = (MA(Series, N1) + MA(Series, N2) + MA(Series, N3) + MA(Series, N4)) / 4 DICT = {'BBI': bbi} VAR = pd.DataFrame(DICT) return VAR
[ "多空指标" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L213-L220
[ "def", "BBI", "(", "Series", ",", "N1", ",", "N2", ",", "N3", ",", "N4", ")", ":", "bbi", "=", "(", "MA", "(", "Series", ",", "N1", ")", "+", "MA", "(", "Series", ",", "N2", ")", "+", "MA", "(", "Series", ",", "N3", ")", "+", "MA", "(", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
BARLAST
支持MultiIndex的cond和DateTimeIndex的cond 条件成立 yes= True 或者 yes=1 根据不同的指标自己定 Arguments: cond {[type]} -- [description]
QUANTAXIS/QAIndicator/base.py
def BARLAST(cond, yes=True): """支持MultiIndex的cond和DateTimeIndex的cond 条件成立 yes= True 或者 yes=1 根据不同的指标自己定 Arguments: cond {[type]} -- [description] """ if isinstance(cond.index, pd.MultiIndex): return len(cond)-cond.index.levels[0].tolist().index(cond[cond != yes].index[-1][0])-1 elif isinstance(cond.index, pd.DatetimeIndex): return len(cond)-cond.index.tolist().index(cond[cond != yes].index[-1])-1
def BARLAST(cond, yes=True): """支持MultiIndex的cond和DateTimeIndex的cond 条件成立 yes= True 或者 yes=1 根据不同的指标自己定 Arguments: cond {[type]} -- [description] """ if isinstance(cond.index, pd.MultiIndex): return len(cond)-cond.index.levels[0].tolist().index(cond[cond != yes].index[-1][0])-1 elif isinstance(cond.index, pd.DatetimeIndex): return len(cond)-cond.index.tolist().index(cond[cond != yes].index[-1])-1
[ "支持MultiIndex的cond和DateTimeIndex的cond", "条件成立", "yes", "=", "True", "或者", "yes", "=", "1", "根据不同的指标自己定" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L223-L233
[ "def", "BARLAST", "(", "cond", ",", "yes", "=", "True", ")", ":", "if", "isinstance", "(", "cond", ".", "index", ",", "pd", ".", "MultiIndex", ")", ":", "return", "len", "(", "cond", ")", "-", "cond", ".", "index", ".", "levels", "[", "0", "]", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
get_today_all
today all Returns: [type] -- [description]
QUANTAXIS/QAFetch/realtime.py
def get_today_all(output='pd'): """today all Returns: [type] -- [description] """ data = [] today = str(datetime.date.today()) codes = QA_fetch_get_stock_list('stock').code.tolist() bestip = select_best_ip()['stock'] for code in codes: try: l = QA_fetch_get_stock_day( code, today, today, '00', ip=bestip) except: bestip = select_best_ip()['stock'] l = QA_fetch_get_stock_day( code, today, today, '00', ip=bestip) if l is not None: data.append(l) res = pd.concat(data) if output in ['pd']: return res elif output in ['QAD']: return QA_DataStruct_Stock_day(res.set_index(['date', 'code'], drop=False))
def get_today_all(output='pd'): """today all Returns: [type] -- [description] """ data = [] today = str(datetime.date.today()) codes = QA_fetch_get_stock_list('stock').code.tolist() bestip = select_best_ip()['stock'] for code in codes: try: l = QA_fetch_get_stock_day( code, today, today, '00', ip=bestip) except: bestip = select_best_ip()['stock'] l = QA_fetch_get_stock_day( code, today, today, '00', ip=bestip) if l is not None: data.append(l) res = pd.concat(data) if output in ['pd']: return res elif output in ['QAD']: return QA_DataStruct_Stock_day(res.set_index(['date', 'code'], drop=False))
[ "today", "all" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/realtime.py#L35-L61
[ "def", "get_today_all", "(", "output", "=", "'pd'", ")", ":", "data", "=", "[", "]", "today", "=", "str", "(", "datetime", ".", "date", ".", "today", "(", ")", ")", "codes", "=", "QA_fetch_get_stock_list", "(", "'stock'", ")", ".", "code", ".", "toli...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SU_save_stock_day
save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用
QUANTAXIS/QASU/save_tdx_parallelism.py
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None): ''' save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用 ''' stock_list = QA_fetch_get_stock_list().code.unique().tolist() coll_stock_day = client.stock_day coll_stock_day.create_index( [("code", pymongo.ASCENDING), ("date_stamp", pymongo.ASCENDING)] ) err = [] # saveing result def __gen_param(stock_list, coll_stock_day, ip_list=[]): results = [] count = len(ip_list) total = len(stock_list) for item in range(len(stock_list)): try: code = stock_list[item] QA_util_log_info( '##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)), ui_log ) # 首选查找数据库 是否 有 这个代码的数据 search_cond = {'code': str(code)[0:6]} ref = coll_stock_day.find(search_cond) end_date = str(now_time())[0:10] ref_count = coll_stock_day.count_documents(search_cond) # 当前数据库已经包含了这个代码的数据, 继续增量更新 # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现 if ref_count > 0: # 接着上次获取的日期继续更新 start_date = ref[ref_count - 1]['date'] # print("ref[ref.count() - 1]['date'] {} {}".format(ref.count(), coll_stock_day.count_documents({'code': str(code)[0:6]}))) else: # 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据 start_date = '1990-01-01' QA_util_log_info( 'UPDATE_STOCK_DAY \n Trying updating {} from {} to {}' .format(code, start_date, end_date), ui_log ) if start_date != end_date: # 更新过的,不更新 results.extend([(code, start_date, end_date, '00', 'day', ip_list[item % count]['ip'], ip_list[item % count]['port'], item, total, ui_log, ui_progress)]) except Exception as error0: print('Exception:{}'.format(error0)) err.append(code) return results ips = get_ip_list_by_multi_process_ping(stock_ip_list, _type='stock')[:cpu_count() * 2 + 1] param = __gen_param(stock_list, coll_stock_day, ips) ps = QA_SU_save_stock_day_parallelism(processes=cpu_count() if len(ips) >= cpu_count() else len(ips), client=client, ui_log=ui_log) ps.add(do_saving_work, param) ps.run() if len(err) < 1: QA_util_log_info('SUCCESS save stock day ^_^', ui_log) else: QA_util_log_info('ERROR CODE \n ', ui_log) QA_util_log_info(err, ui_log)
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None): ''' save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用 ''' stock_list = QA_fetch_get_stock_list().code.unique().tolist() coll_stock_day = client.stock_day coll_stock_day.create_index( [("code", pymongo.ASCENDING), ("date_stamp", pymongo.ASCENDING)] ) err = [] # saveing result def __gen_param(stock_list, coll_stock_day, ip_list=[]): results = [] count = len(ip_list) total = len(stock_list) for item in range(len(stock_list)): try: code = stock_list[item] QA_util_log_info( '##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)), ui_log ) # 首选查找数据库 是否 有 这个代码的数据 search_cond = {'code': str(code)[0:6]} ref = coll_stock_day.find(search_cond) end_date = str(now_time())[0:10] ref_count = coll_stock_day.count_documents(search_cond) # 当前数据库已经包含了这个代码的数据, 继续增量更新 # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现 if ref_count > 0: # 接着上次获取的日期继续更新 start_date = ref[ref_count - 1]['date'] # print("ref[ref.count() - 1]['date'] {} {}".format(ref.count(), coll_stock_day.count_documents({'code': str(code)[0:6]}))) else: # 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据 start_date = '1990-01-01' QA_util_log_info( 'UPDATE_STOCK_DAY \n Trying updating {} from {} to {}' .format(code, start_date, end_date), ui_log ) if start_date != end_date: # 更新过的,不更新 results.extend([(code, start_date, end_date, '00', 'day', ip_list[item % count]['ip'], ip_list[item % count]['port'], item, total, ui_log, ui_progress)]) except Exception as error0: print('Exception:{}'.format(error0)) err.append(code) return results ips = get_ip_list_by_multi_process_ping(stock_ip_list, _type='stock')[:cpu_count() * 2 + 1] param = __gen_param(stock_list, coll_stock_day, ips) ps = QA_SU_save_stock_day_parallelism(processes=cpu_count() if len(ips) >= cpu_count() else len(ips), client=client, ui_log=ui_log) ps.add(do_saving_work, param) ps.run() if len(err) < 1: QA_util_log_info('SUCCESS save stock day ^_^', ui_log) else: QA_util_log_info('ERROR CODE \n ', ui_log) QA_util_log_info(err, ui_log)
[ "save", "stock_day", "保存日线数据", ":", "param", "client", ":", ":", "param", "ui_log", ":", "给GUI", "qt", "界面使用", ":", "param", "ui_progress", ":", "给GUI", "qt", "界面使用", ":", "param", "ui_progress_int_value", ":", "给GUI", "qt", "界面使用" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_tdx_parallelism.py#L118-L193
[ "def", "QA_SU_save_stock_day", "(", "client", "=", "DATABASE", ",", "ui_log", "=", "None", ",", "ui_progress", "=", "None", ")", ":", "stock_list", "=", "QA_fetch_get_stock_list", "(", ")", ".", "code", ".", "unique", "(", ")", ".", "tolist", "(", ")", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_user_sign_in
用户登陆 不使用 QAUSER库 只返回 TRUE/FALSE
QUANTAXIS/QASU/user.py
def QA_user_sign_in(username, password): """用户登陆 不使用 QAUSER库 只返回 TRUE/FALSE """ #user = QA_User(name= name, password=password) cursor = DATABASE.user.find_one( {'username': username, 'password': password}) if cursor is None: QA_util_log_info('SOMETHING WRONG') return False else: return True
def QA_user_sign_in(username, password): """用户登陆 不使用 QAUSER库 只返回 TRUE/FALSE """ #user = QA_User(name= name, password=password) cursor = DATABASE.user.find_one( {'username': username, 'password': password}) if cursor is None: QA_util_log_info('SOMETHING WRONG') return False else: return True
[ "用户登陆", "不使用", "QAUSER库", "只返回", "TRUE", "/", "FALSE" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/user.py#L31-L43
[ "def", "QA_user_sign_in", "(", "username", ",", "password", ")", ":", "#user = QA_User(name= name, password=password)", "cursor", "=", "DATABASE", ".", "user", ".", "find_one", "(", "{", "'username'", ":", "username", ",", "'password'", ":", "password", "}", ")", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_user_sign_up
只做check! 具体逻辑需要在自己的函数中实现 参见:QAWEBSERVER中的实现 Arguments: name {[type]} -- [description] password {[type]} -- [description] client {[type]} -- [description] Returns: [type] -- [description]
QUANTAXIS/QASU/user.py
def QA_user_sign_up(name, password, client): """只做check! 具体逻辑需要在自己的函数中实现 参见:QAWEBSERVER中的实现 Arguments: name {[type]} -- [description] password {[type]} -- [description] client {[type]} -- [description] Returns: [type] -- [description] """ coll = client.user if (coll.find({'username': name}).count() > 0): print(name) QA_util_log_info('user name is already exist') return False else: return True
def QA_user_sign_up(name, password, client): """只做check! 具体逻辑需要在自己的函数中实现 参见:QAWEBSERVER中的实现 Arguments: name {[type]} -- [description] password {[type]} -- [description] client {[type]} -- [description] Returns: [type] -- [description] """ coll = client.user if (coll.find({'username': name}).count() > 0): print(name) QA_util_log_info('user name is already exist') return False else: return True
[ "只做check!", "具体逻辑需要在自己的函数中实现" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/user.py#L46-L66
[ "def", "QA_user_sign_up", "(", "name", ",", "password", ",", "client", ")", ":", "coll", "=", "client", ".", "user", "if", "(", "coll", ".", "find", "(", "{", "'username'", ":", "name", "}", ")", ".", "count", "(", ")", ">", "0", ")", ":", "print...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Broker.warp
对order/market的封装 [description] Arguments: order {[type]} -- [description] Returns: [type] -- [description]
QUANTAXIS/QAMarket/QABroker.py
def warp(self, order): """对order/market的封装 [description] Arguments: order {[type]} -- [description] Returns: [type] -- [description] """ # 因为成交模式对时间的封装 if order.order_model == ORDER_MODEL.MARKET: if order.frequence is FREQUENCE.DAY: # exact_time = str(datetime.datetime.strptime( # str(order.datetime), '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1)) order.date = order.datetime[0:10] order.datetime = '{} 09:30:00'.format(order.date) elif order.frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: exact_time = str( datetime.datetime .strptime(str(order.datetime), '%Y-%m-%d %H:%M:%S') + datetime.timedelta(minutes=1) ) order.date = exact_time[0:10] order.datetime = exact_time self.market_data = self.get_market(order) if self.market_data is None: return order order.price = ( float(self.market_data["high"]) + float(self.market_data["low"]) ) * 0.5 elif order.order_model == ORDER_MODEL.NEXT_OPEN: try: exact_time = str( datetime.datetime .strptime(str(order.datetime), '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1) ) order.date = exact_time[0:10] order.datetime = '{} 09:30:00'.format(order.date) except: order.datetime = '{} 15:00:00'.format(order.date) self.market_data = self.get_market(order) if self.market_data is None: return order order.price = float(self.market_data["close"]) elif order.order_model == ORDER_MODEL.CLOSE: try: order.datetime = self.market_data.datetime except: if len(str(order.datetime)) == 19: pass else: order.datetime = '{} 15:00:00'.format(order.date) self.market_data = self.get_market(order) if self.market_data is None: return order order.price = float(self.market_data["close"]) elif order.order_model == ORDER_MODEL.STRICT: '加入严格模式' if order.frequence is FREQUENCE.DAY: exact_time = str( datetime.datetime .strptime(order.datetime, '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1) ) order.date = exact_time[0:10] order.datetime = '{} 09:30:00'.format(order.date) elif order.frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: exact_time = str( datetime.datetime .strptime(order.datetime, '%Y-%m-%d %H-%M-%S') + datetime.timedelta(minute=1) ) order.date = exact_time[0:10] order.datetime = exact_time self.market_data = self.get_market(order) if self.market_data is None: return order if order.towards == 1: order.price = float(self.market_data["high"]) else: order.price = float(self.market_data["low"]) return order
def warp(self, order): """对order/market的封装 [description] Arguments: order {[type]} -- [description] Returns: [type] -- [description] """ # 因为成交模式对时间的封装 if order.order_model == ORDER_MODEL.MARKET: if order.frequence is FREQUENCE.DAY: # exact_time = str(datetime.datetime.strptime( # str(order.datetime), '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1)) order.date = order.datetime[0:10] order.datetime = '{} 09:30:00'.format(order.date) elif order.frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: exact_time = str( datetime.datetime .strptime(str(order.datetime), '%Y-%m-%d %H:%M:%S') + datetime.timedelta(minutes=1) ) order.date = exact_time[0:10] order.datetime = exact_time self.market_data = self.get_market(order) if self.market_data is None: return order order.price = ( float(self.market_data["high"]) + float(self.market_data["low"]) ) * 0.5 elif order.order_model == ORDER_MODEL.NEXT_OPEN: try: exact_time = str( datetime.datetime .strptime(str(order.datetime), '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1) ) order.date = exact_time[0:10] order.datetime = '{} 09:30:00'.format(order.date) except: order.datetime = '{} 15:00:00'.format(order.date) self.market_data = self.get_market(order) if self.market_data is None: return order order.price = float(self.market_data["close"]) elif order.order_model == ORDER_MODEL.CLOSE: try: order.datetime = self.market_data.datetime except: if len(str(order.datetime)) == 19: pass else: order.datetime = '{} 15:00:00'.format(order.date) self.market_data = self.get_market(order) if self.market_data is None: return order order.price = float(self.market_data["close"]) elif order.order_model == ORDER_MODEL.STRICT: '加入严格模式' if order.frequence is FREQUENCE.DAY: exact_time = str( datetime.datetime .strptime(order.datetime, '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1) ) order.date = exact_time[0:10] order.datetime = '{} 09:30:00'.format(order.date) elif order.frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]: exact_time = str( datetime.datetime .strptime(order.datetime, '%Y-%m-%d %H-%M-%S') + datetime.timedelta(minute=1) ) order.date = exact_time[0:10] order.datetime = exact_time self.market_data = self.get_market(order) if self.market_data is None: return order if order.towards == 1: order.price = float(self.market_data["high"]) else: order.price = float(self.market_data["low"]) return order
[ "对order", "/", "market的封装" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QABroker.py#L191-L294
[ "def", "warp", "(", "self", ",", "order", ")", ":", "# 因为成交模式对时间的封装", "if", "order", ".", "order_model", "==", "ORDER_MODEL", ".", "MARKET", ":", "if", "order", ".", "frequence", "is", "FREQUENCE", ".", "DAY", ":", "# exact_time = str(datetime.datetime.strptime(...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
get_filename
get_filename
QUANTAXIS/QAFetch/QAfinancial.py
def get_filename(): """ get_filename """ return [(l[0],l[1]) for l in [line.strip().split(",") for line in requests.get(FINANCIAL_URL).text.strip().split('\n')]]
def get_filename(): """ get_filename """ return [(l[0],l[1]) for l in [line.strip().split(",") for line in requests.get(FINANCIAL_URL).text.strip().split('\n')]]
[ "get_filename" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAfinancial.py#L78-L82
[ "def", "get_filename", "(", ")", ":", "return", "[", "(", "l", "[", "0", "]", ",", "l", "[", "1", "]", ")", "for", "l", "in", "[", "line", ".", "strip", "(", ")", ".", "split", "(", "\",\"", ")", "for", "line", "in", "requests", ".", "get", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
download_financialzip
会创建一个download/文件夹
QUANTAXIS/QAFetch/QAfinancial.py
def download_financialzip(): """ 会创建一个download/文件夹 """ result = get_filename() res = [] for item, md5 in result: if item in os.listdir(download_path) and md5==QA_util_file_md5('{}{}{}'.format(download_path,os.sep,item)): print('FILE {} is already in {}'.format(item, download_path)) else: print('CURRENTLY GET/UPDATE {}'.format(item[0:12])) r = requests.get('http://down.tdx.com.cn:8001/fin/{}'.format(item)) file = '{}{}{}'.format(download_path, os.sep, item) with open(file, "wb") as code: code.write(r.content) res.append(item) return res
def download_financialzip(): """ 会创建一个download/文件夹 """ result = get_filename() res = [] for item, md5 in result: if item in os.listdir(download_path) and md5==QA_util_file_md5('{}{}{}'.format(download_path,os.sep,item)): print('FILE {} is already in {}'.format(item, download_path)) else: print('CURRENTLY GET/UPDATE {}'.format(item[0:12])) r = requests.get('http://down.tdx.com.cn:8001/fin/{}'.format(item)) file = '{}{}{}'.format(download_path, os.sep, item) with open(file, "wb") as code: code.write(r.content) res.append(item) return res
[ "会创建一个download", "/", "文件夹" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAfinancial.py#L89-L108
[ "def", "download_financialzip", "(", ")", ":", "result", "=", "get_filename", "(", ")", "res", "=", "[", "]", "for", "item", ",", "md5", "in", "result", ":", "if", "item", "in", "os", ".", "listdir", "(", "download_path", ")", "and", "md5", "==", "QA...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QAHistoryFinancialReader.get_df
读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考 https://github.com/rainx/pytdx/issues/133 :param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat :return: pandas DataFrame格式的历史财务数据
QUANTAXIS/QAFetch/QAfinancial.py
def get_df(self, data_file): """ 读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考 https://github.com/rainx/pytdx/issues/133 :param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat :return: pandas DataFrame格式的历史财务数据 """ crawler = QAHistoryFinancialCrawler() with open(data_file, 'rb') as df: data = crawler.parse(download_file=df) return crawler.to_df(data)
def get_df(self, data_file): """ 读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考 https://github.com/rainx/pytdx/issues/133 :param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat :return: pandas DataFrame格式的历史财务数据 """ crawler = QAHistoryFinancialCrawler() with open(data_file, 'rb') as df: data = crawler.parse(download_file=df) return crawler.to_df(data)
[ "读取历史财务数据文件,并返回pandas结果", ",", "类似gpcw20171231", ".", "zip格式,具体字段含义参考" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAfinancial.py#L60-L75
[ "def", "get_df", "(", "self", ",", "data_file", ")", ":", "crawler", "=", "QAHistoryFinancialCrawler", "(", ")", "with", "open", "(", "data_file", ",", "'rb'", ")", "as", "df", ":", "data", "=", "crawler", ".", "parse", "(", "download_file", "=", "df", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_fetch_get_sh_margin
return shanghai margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data
QUANTAXIS/QAFetch/QACrawler.py
def QA_fetch_get_sh_margin(date): """return shanghai margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data """ if date in trade_date_sse: data= pd.read_excel(_sh_url.format(QA_util_date_str2int (date)), 1).assign(date=date).assign(sse='sh') data.columns=['code','name','leveraged_balance','leveraged_buyout','leveraged_payoff','margin_left','margin_sell','margin_repay','date','sse'] return data else: pass
def QA_fetch_get_sh_margin(date): """return shanghai margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data """ if date in trade_date_sse: data= pd.read_excel(_sh_url.format(QA_util_date_str2int (date)), 1).assign(date=date).assign(sse='sh') data.columns=['code','name','leveraged_balance','leveraged_buyout','leveraged_payoff','margin_left','margin_sell','margin_repay','date','sse'] return data else: pass
[ "return", "shanghai", "margin", "data" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QACrawler.py#L34-L49
[ "def", "QA_fetch_get_sh_margin", "(", "date", ")", ":", "if", "date", "in", "trade_date_sse", ":", "data", "=", "pd", ".", "read_excel", "(", "_sh_url", ".", "format", "(", "QA_util_date_str2int", "(", "date", ")", ")", ",", "1", ")", ".", "assign", "(",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_fetch_get_sz_margin
return shenzhen margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data
QUANTAXIS/QAFetch/QACrawler.py
def QA_fetch_get_sz_margin(date): """return shenzhen margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data """ if date in trade_date_sse: return pd.read_excel(_sz_url.format(date)).assign(date=date).assign(sse='sz')
def QA_fetch_get_sz_margin(date): """return shenzhen margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data """ if date in trade_date_sse: return pd.read_excel(_sz_url.format(date)).assign(date=date).assign(sse='sz')
[ "return", "shenzhen", "margin", "data" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QACrawler.py#L52-L63
[ "def", "QA_fetch_get_sz_margin", "(", "date", ")", ":", "if", "date", "in", "trade_date_sse", ":", "return", "pd", ".", "read_excel", "(", "_sz_url", ".", "format", "(", "date", ")", ")", ".", "assign", "(", "date", "=", "date", ")", ".", "assign", "("...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Market.upcoming_data
更新市场数据 broker 为名字, data 是市场数据 被 QABacktest 中run 方法调用 upcoming_data
QUANTAXIS/QAMarket/QAMarket.py
def upcoming_data(self, broker, data): ''' 更新市场数据 broker 为名字, data 是市场数据 被 QABacktest 中run 方法调用 upcoming_data ''' # main thread' # if self.running_time is not None and self.running_time!= data.datetime[0]: # for item in self.broker.keys(): # self._settle(item) self.running_time = data.datetime[0] for account in self.session.values(): account.run(QA_Event( event_type=ENGINE_EVENT.UPCOMING_DATA, # args 附加的参数 market_data=data, broker_name=broker, send_order=self.insert_order, # 🛠todo insert_order = insert_order query_data=self.query_data_no_wait, query_order=self.query_order, query_assets=self.query_assets, query_trade=self.query_trade ))
def upcoming_data(self, broker, data): ''' 更新市场数据 broker 为名字, data 是市场数据 被 QABacktest 中run 方法调用 upcoming_data ''' # main thread' # if self.running_time is not None and self.running_time!= data.datetime[0]: # for item in self.broker.keys(): # self._settle(item) self.running_time = data.datetime[0] for account in self.session.values(): account.run(QA_Event( event_type=ENGINE_EVENT.UPCOMING_DATA, # args 附加的参数 market_data=data, broker_name=broker, send_order=self.insert_order, # 🛠todo insert_order = insert_order query_data=self.query_data_no_wait, query_order=self.query_order, query_assets=self.query_assets, query_trade=self.query_trade ))
[ "更新市场数据", "broker", "为名字,", "data", "是市场数据", "被", "QABacktest", "中run", "方法调用", "upcoming_data" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAMarket.py#L103-L126
[ "def", "upcoming_data", "(", "self", ",", "broker", ",", "data", ")", ":", "# main thread'", "# if self.running_time is not None and self.running_time!= data.datetime[0]:", "# for item in self.broker.keys():", "# self._settle(item)", "self", ".", "running_time", "=", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Market.start_order_threading
开启查询子线程(实盘中用)
QUANTAXIS/QAMarket/QAMarket.py
def start_order_threading(self): """开启查询子线程(实盘中用) """ self.if_start_orderthreading = True self.order_handler.if_start_orderquery = True self.trade_engine.create_kernel('ORDER', daemon=True) self.trade_engine.start_kernel('ORDER') self.sync_order_and_deal()
def start_order_threading(self): """开启查询子线程(实盘中用) """ self.if_start_orderthreading = True self.order_handler.if_start_orderquery = True self.trade_engine.create_kernel('ORDER', daemon=True) self.trade_engine.start_kernel('ORDER') self.sync_order_and_deal()
[ "开启查询子线程", "(", "实盘中用", ")" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAMarket.py#L172-L181
[ "def", "start_order_threading", "(", "self", ")", ":", "self", ".", "if_start_orderthreading", "=", "True", "self", ".", "order_handler", ".", "if_start_orderquery", "=", "True", "self", ".", "trade_engine", ".", "create_kernel", "(", "'ORDER'", ",", "daemon", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Market.login
login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [description] (default: {None}) Returns: [type] -- [description]
QUANTAXIS/QAMarket/QAMarket.py
def login(self, broker_name, account_cookie, account=None): """login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ res = False if account is None: if account_cookie not in self.session.keys(): self.session[account_cookie] = QA_Account( account_cookie=account_cookie, broker=broker_name ) if self.sync_account(broker_name, account_cookie): res = True if self.if_start_orderthreading and res: # self.order_handler.subscribe( self.session[account_cookie], self.broker[broker_name] ) else: if account_cookie not in self.session.keys(): account.broker = broker_name self.session[account_cookie] = account if self.sync_account(broker_name, account_cookie): res = True if self.if_start_orderthreading and res: # self.order_handler.subscribe( account, self.broker[broker_name] ) if res: return res else: try: self.session.pop(account_cookie) except: pass return False
def login(self, broker_name, account_cookie, account=None): """login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ res = False if account is None: if account_cookie not in self.session.keys(): self.session[account_cookie] = QA_Account( account_cookie=account_cookie, broker=broker_name ) if self.sync_account(broker_name, account_cookie): res = True if self.if_start_orderthreading and res: # self.order_handler.subscribe( self.session[account_cookie], self.broker[broker_name] ) else: if account_cookie not in self.session.keys(): account.broker = broker_name self.session[account_cookie] = account if self.sync_account(broker_name, account_cookie): res = True if self.if_start_orderthreading and res: # self.order_handler.subscribe( account, self.broker[broker_name] ) if res: return res else: try: self.session.pop(account_cookie) except: pass return False
[ "login", "登录到交易前置" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAMarket.py#L193-L245
[ "def", "login", "(", "self", ",", "broker_name", ",", "account_cookie", ",", "account", "=", "None", ")", ":", "res", "=", "False", "if", "account", "is", "None", ":", "if", "account_cookie", "not", "in", "self", ".", "session", ".", "keys", "(", ")", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Market.sync_account
同步账户信息 Arguments: broker_id {[type]} -- [description] account_cookie {[type]} -- [description]
QUANTAXIS/QAMarket/QAMarket.py
def sync_account(self, broker_name, account_cookie): """同步账户信息 Arguments: broker_id {[type]} -- [description] account_cookie {[type]} -- [description] """ try: if isinstance(self.broker[broker_name], QA_BacktestBroker): pass else: self.session[account_cookie].sync_account( self.broker[broker_name].query_positions(account_cookie) ) return True except Exception as e: print(e) return False
def sync_account(self, broker_name, account_cookie): """同步账户信息 Arguments: broker_id {[type]} -- [description] account_cookie {[type]} -- [description] """ try: if isinstance(self.broker[broker_name], QA_BacktestBroker): pass else: self.session[account_cookie].sync_account( self.broker[broker_name].query_positions(account_cookie) ) return True except Exception as e: print(e) return False
[ "同步账户信息" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAMarket.py#L254-L271
[ "def", "sync_account", "(", "self", ",", "broker_name", ",", "account_cookie", ")", ":", "try", ":", "if", "isinstance", "(", "self", ".", "broker", "[", "broker_name", "]", ",", "QA_BacktestBroker", ")", ":", "pass", "else", ":", "self", ".", "session", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Market._trade
内部函数
QUANTAXIS/QAMarket/QAMarket.py
def _trade(self, event): "内部函数" print('==================================market enging: trade') print(self.order_handler.order_queue.pending) print('==================================') self.order_handler._trade() print('done')
def _trade(self, event): "内部函数" print('==================================market enging: trade') print(self.order_handler.order_queue.pending) print('==================================') self.order_handler._trade() print('done')
[ "内部函数" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAMarket.py#L585-L591
[ "def", "_trade", "(", "self", ",", "event", ")", ":", "print", "(", "'==================================market enging: trade'", ")", "print", "(", "self", ".", "order_handler", ".", "order_queue", ".", "pending", ")", "print", "(", "'==================================...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Market.settle_order
交易前置结算 1. 回测: 交易队列清空,待交易队列标记SETTLE 2. 账户每日结算 3. broker结算更新
QUANTAXIS/QAMarket/QAMarket.py
def settle_order(self): """交易前置结算 1. 回测: 交易队列清空,待交易队列标记SETTLE 2. 账户每日结算 3. broker结算更新 """ if self.if_start_orderthreading: self.order_handler.run( QA_Event( event_type=BROKER_EVENT.SETTLE, event_queue=self.trade_engine.kernels_dict['ORDER'].queue ) )
def settle_order(self): """交易前置结算 1. 回测: 交易队列清空,待交易队列标记SETTLE 2. 账户每日结算 3. broker结算更新 """ if self.if_start_orderthreading: self.order_handler.run( QA_Event( event_type=BROKER_EVENT.SETTLE, event_queue=self.trade_engine.kernels_dict['ORDER'].queue ) )
[ "交易前置结算" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAMarket.py#L644-L659
[ "def", "settle_order", "(", "self", ")", ":", "if", "self", ".", "if_start_orderthreading", ":", "self", ".", "order_handler", ".", "run", "(", "QA_Event", "(", "event_type", "=", "BROKER_EVENT", ".", "SETTLE", ",", "event_queue", "=", "self", ".", "trade_en...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_to_json_from_pandas
需要对于datetime 和date 进行转换, 以免直接被变成了时间戳
QUANTAXIS/QAUtil/QATransform.py
def QA_util_to_json_from_pandas(data): """需要对于datetime 和date 进行转换, 以免直接被变成了时间戳""" if 'datetime' in data.columns: data.datetime = data.datetime.apply(str) if 'date' in data.columns: data.date = data.date.apply(str) return json.loads(data.to_json(orient='records'))
def QA_util_to_json_from_pandas(data): """需要对于datetime 和date 进行转换, 以免直接被变成了时间戳""" if 'datetime' in data.columns: data.datetime = data.datetime.apply(str) if 'date' in data.columns: data.date = data.date.apply(str) return json.loads(data.to_json(orient='records'))
[ "需要对于datetime", "和date", "进行转换", "以免直接被变成了时间戳" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QATransform.py#L32-L38
[ "def", "QA_util_to_json_from_pandas", "(", "data", ")", ":", "if", "'datetime'", "in", "data", ".", "columns", ":", "data", ".", "datetime", "=", "data", ".", "datetime", ".", "apply", "(", "str", ")", "if", "'date'", "in", "data", ".", "columns", ":", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_code_tostr
将所有沪深股票从数字转化到6位的代码 因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1
QUANTAXIS/QAUtil/QACode.py
def QA_util_code_tostr(code): """ 将所有沪深股票从数字转化到6位的代码 因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1 """ if isinstance(code, int): return "{:>06d}".format(code) if isinstance(code, str): # 聚宽股票代码格式 '600000.XSHG' # 掘金股票代码格式 'SHSE.600000' # Wind股票代码格式 '600000.SH' # 天软股票代码格式 'SH600000' if len(code) == 6: return code if len(code) == 8: # 天软数据 return code[-6:] if len(code) == 9: return code[:6] if len(code) == 11: if code[0] in ["S"]: return code.split(".")[1] return code.split(".")[0] raise ValueError("错误的股票代码格式") if isinstance(code, list): return QA_util_code_to_str(code[0])
def QA_util_code_tostr(code): """ 将所有沪深股票从数字转化到6位的代码 因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1 """ if isinstance(code, int): return "{:>06d}".format(code) if isinstance(code, str): # 聚宽股票代码格式 '600000.XSHG' # 掘金股票代码格式 'SHSE.600000' # Wind股票代码格式 '600000.SH' # 天软股票代码格式 'SH600000' if len(code) == 6: return code if len(code) == 8: # 天软数据 return code[-6:] if len(code) == 9: return code[:6] if len(code) == 11: if code[0] in ["S"]: return code.split(".")[1] return code.split(".")[0] raise ValueError("错误的股票代码格式") if isinstance(code, list): return QA_util_code_to_str(code[0])
[ "将所有沪深股票从数字转化到6位的代码" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QACode.py#L29-L56
[ "def", "QA_util_code_tostr", "(", "code", ")", ":", "if", "isinstance", "(", "code", ",", "int", ")", ":", "return", "\"{:>06d}\"", ".", "format", "(", "code", ")", "if", "isinstance", "(", "code", ",", "str", ")", ":", "# 聚宽股票代码格式 '600000.XSHG'", "# 掘金股票代...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_code_tolist
转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description]
QUANTAXIS/QAUtil/QACode.py
def QA_util_code_tolist(code, auto_fill=True): """转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description] """ if isinstance(code, str): if auto_fill: return [QA_util_code_tostr(code)] else: return [code] elif isinstance(code, list): if auto_fill: return [QA_util_code_tostr(item) for item in code] else: return [item for item in code]
def QA_util_code_tolist(code, auto_fill=True): """转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description] """ if isinstance(code, str): if auto_fill: return [QA_util_code_tostr(code)] else: return [code] elif isinstance(code, list): if auto_fill: return [QA_util_code_tostr(item) for item in code] else: return [item for item in code]
[ "转换code", "==", ">", "list" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QACode.py#L59-L82
[ "def", "QA_util_code_tolist", "(", "code", ",", "auto_fill", "=", "True", ")", ":", "if", "isinstance", "(", "code", ",", "str", ")", ":", "if", "auto_fill", ":", "return", "[", "QA_util_code_tostr", "(", "code", ")", "]", "else", ":", "return", "[", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.subscribe_strategy
订阅一个策略 会扣减你的积分 Arguments: strategy_id {str} -- [description] last {int} -- [description] Keyword Arguments: today {[type]} -- [description] (default: {datetime.date.today()}) cost_coins {int} -- [description] (default: {10})
QUANTAXIS/QAARP/QAUser.py
def subscribe_strategy( self, strategy_id: str, last: int, today=datetime.date.today(), cost_coins=10 ): """订阅一个策略 会扣减你的积分 Arguments: strategy_id {str} -- [description] last {int} -- [description] Keyword Arguments: today {[type]} -- [description] (default: {datetime.date.today()}) cost_coins {int} -- [description] (default: {10}) """ if self.coins > cost_coins: order_id = str(uuid.uuid1()) self._subscribed_strategy[strategy_id] = { 'lasttime': last, 'start': str(today), 'strategy_id': strategy_id, 'end': QA_util_get_next_day( QA_util_get_real_date(str(today), towards=1), last ), 'status': 'running', 'uuid': order_id } self.coins -= cost_coins self.coins_history.append( [ cost_coins, strategy_id, str(today), last, order_id, 'subscribe' ] ) return True, order_id else: # return QAERROR. return False, 'Not Enough Coins'
def subscribe_strategy( self, strategy_id: str, last: int, today=datetime.date.today(), cost_coins=10 ): """订阅一个策略 会扣减你的积分 Arguments: strategy_id {str} -- [description] last {int} -- [description] Keyword Arguments: today {[type]} -- [description] (default: {datetime.date.today()}) cost_coins {int} -- [description] (default: {10}) """ if self.coins > cost_coins: order_id = str(uuid.uuid1()) self._subscribed_strategy[strategy_id] = { 'lasttime': last, 'start': str(today), 'strategy_id': strategy_id, 'end': QA_util_get_next_day( QA_util_get_real_date(str(today), towards=1), last ), 'status': 'running', 'uuid': order_id } self.coins -= cost_coins self.coins_history.append( [ cost_coins, strategy_id, str(today), last, order_id, 'subscribe' ] ) return True, order_id else: # return QAERROR. return False, 'Not Enough Coins'
[ "订阅一个策略" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L213-L267
[ "def", "subscribe_strategy", "(", "self", ",", "strategy_id", ":", "str", ",", "last", ":", "int", ",", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", ",", "cost_coins", "=", "10", ")", ":", "if", "self", ".", "coins", ">", "cost_coin...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.unsubscribe_stratgy
取消订阅某一个策略 Arguments: strategy_id {[type]} -- [description]
QUANTAXIS/QAARP/QAUser.py
def unsubscribe_stratgy(self, strategy_id): """取消订阅某一个策略 Arguments: strategy_id {[type]} -- [description] """ today = datetime.date.today() order_id = str(uuid.uuid1()) if strategy_id in self._subscribed_strategy.keys(): self._subscribed_strategy[strategy_id]['status'] = 'canceled' self.coins_history.append( [0, strategy_id, str(today), 0, order_id, 'unsubscribe'] )
def unsubscribe_stratgy(self, strategy_id): """取消订阅某一个策略 Arguments: strategy_id {[type]} -- [description] """ today = datetime.date.today() order_id = str(uuid.uuid1()) if strategy_id in self._subscribed_strategy.keys(): self._subscribed_strategy[strategy_id]['status'] = 'canceled' self.coins_history.append( [0, strategy_id, str(today), 0, order_id, 'unsubscribe'] )
[ "取消订阅某一个策略" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L269-L288
[ "def", "unsubscribe_stratgy", "(", "self", ",", "strategy_id", ")", ":", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "order_id", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "if", "strategy_id", "in", "self", ".", "_subscrib...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.subscribing_strategy
订阅一个策略 Returns: [type] -- [description]
QUANTAXIS/QAARP/QAUser.py
def subscribing_strategy(self): """订阅一个策略 Returns: [type] -- [description] """ res = self.subscribed_strategy.assign( remains=self.subscribed_strategy.end.apply( lambda x: pd.Timestamp(x) - pd.Timestamp(datetime.date.today()) ) ) #res['left'] = res['end_time'] # res['remains'] res.assign( status=res['remains'].apply( lambda x: 'running' if x > datetime.timedelta(days=0) else 'timeout' ) ) return res.query('status=="running"')
def subscribing_strategy(self): """订阅一个策略 Returns: [type] -- [description] """ res = self.subscribed_strategy.assign( remains=self.subscribed_strategy.end.apply( lambda x: pd.Timestamp(x) - pd.Timestamp(datetime.date.today()) ) ) #res['left'] = res['end_time'] # res['remains'] res.assign( status=res['remains'].apply( lambda x: 'running' if x > datetime.timedelta(days=0) else 'timeout' ) ) return res.query('status=="running"')
[ "订阅一个策略" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L301-L321
[ "def", "subscribing_strategy", "(", "self", ")", ":", "res", "=", "self", ".", "subscribed_strategy", ".", "assign", "(", "remains", "=", "self", ".", "subscribed_strategy", ".", "end", ".", "apply", "(", "lambda", "x", ":", "pd", ".", "Timestamp", "(", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.new_portfolio
根据 self.user_cookie 创建一个 portfolio :return: 如果存在 返回 新建的 QA_Portfolio 如果已经存在 返回 这个portfolio
QUANTAXIS/QAARP/QAUser.py
def new_portfolio(self, portfolio_cookie=None): ''' 根据 self.user_cookie 创建一个 portfolio :return: 如果存在 返回 新建的 QA_Portfolio 如果已经存在 返回 这个portfolio ''' _portfolio = QA_Portfolio( user_cookie=self.user_cookie, portfolio_cookie=portfolio_cookie ) if _portfolio.portfolio_cookie not in self.portfolio_list.keys(): self.portfolio_list[_portfolio.portfolio_cookie] = _portfolio return _portfolio else: print( " prortfolio with user_cookie ", self.user_cookie, " already exist!!" ) return self.portfolio_list[portfolio_cookie]
def new_portfolio(self, portfolio_cookie=None): ''' 根据 self.user_cookie 创建一个 portfolio :return: 如果存在 返回 新建的 QA_Portfolio 如果已经存在 返回 这个portfolio ''' _portfolio = QA_Portfolio( user_cookie=self.user_cookie, portfolio_cookie=portfolio_cookie ) if _portfolio.portfolio_cookie not in self.portfolio_list.keys(): self.portfolio_list[_portfolio.portfolio_cookie] = _portfolio return _portfolio else: print( " prortfolio with user_cookie ", self.user_cookie, " already exist!!" ) return self.portfolio_list[portfolio_cookie]
[ "根据", "self", ".", "user_cookie", "创建一个", "portfolio", ":", "return", ":", "如果存在", "返回", "新建的", "QA_Portfolio", "如果已经存在", "返回", "这个portfolio" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L347-L367
[ "def", "new_portfolio", "(", "self", ",", "portfolio_cookie", "=", "None", ")", ":", "_portfolio", "=", "QA_Portfolio", "(", "user_cookie", "=", "self", ".", "user_cookie", ",", "portfolio_cookie", "=", "portfolio_cookie", ")", "if", "_portfolio", ".", "portfoli...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.get_account
直接从二级目录拿到account Arguments: portfolio_cookie {str} -- [description] account_cookie {str} -- [description] Returns: [type] -- [description]
QUANTAXIS/QAARP/QAUser.py
def get_account(self, portfolio_cookie: str, account_cookie: str): """直接从二级目录拿到account Arguments: portfolio_cookie {str} -- [description] account_cookie {str} -- [description] Returns: [type] -- [description] """ try: return self.portfolio_list[portfolio_cookie][account_cookie] except: return None
def get_account(self, portfolio_cookie: str, account_cookie: str): """直接从二级目录拿到account Arguments: portfolio_cookie {str} -- [description] account_cookie {str} -- [description] Returns: [type] -- [description] """ try: return self.portfolio_list[portfolio_cookie][account_cookie] except: return None
[ "直接从二级目录拿到account" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L369-L383
[ "def", "get_account", "(", "self", ",", "portfolio_cookie", ":", "str", ",", "account_cookie", ":", "str", ")", ":", "try", ":", "return", "self", ".", "portfolio_list", "[", "portfolio_cookie", "]", "[", "account_cookie", "]", "except", ":", "return", "None...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.generate_simpleaccount
make a simple account with a easier way 如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account 如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account
QUANTAXIS/QAARP/QAUser.py
def generate_simpleaccount(self): """make a simple account with a easier way 如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account 如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account """ if len(self.portfolio_list.keys()) < 1: po = self.new_portfolio() else: po = list(self.portfolio_list.values())[0] ac = po.new_account() return ac, po
def generate_simpleaccount(self): """make a simple account with a easier way 如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account 如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account """ if len(self.portfolio_list.keys()) < 1: po = self.new_portfolio() else: po = list(self.portfolio_list.values())[0] ac = po.new_account() return ac, po
[ "make", "a", "simple", "account", "with", "a", "easier", "way", "如果当前user中没有创建portfolio", "则创建一个portfolio", "并用此portfolio创建一个account", "如果已有一个或多个portfolio", "则使用第一个portfolio来创建一个account" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L396-L406
[ "def", "generate_simpleaccount", "(", "self", ")", ":", "if", "len", "(", "self", ".", "portfolio_list", ".", "keys", "(", ")", ")", "<", "1", ":", "po", "=", "self", ".", "new_portfolio", "(", ")", "else", ":", "po", "=", "list", "(", "self", ".",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.register_account
注册一个account到portfolio组合中 account 也可以是一个策略类,实现其 on_bar 方法 :param account: 被注册的account :return:
QUANTAXIS/QAARP/QAUser.py
def register_account(self, account, portfolio_cookie=None): ''' 注册一个account到portfolio组合中 account 也可以是一个策略类,实现其 on_bar 方法 :param account: 被注册的account :return: ''' # 查找 portfolio if len(self.portfolio_list.keys()) < 1: po = self.new_portfolio() elif portfolio_cookie is not None: po = self.portfolio_list[portfolio_cookie] else: po = list(self.portfolio_list.values())[0] # 把account 添加到 portfolio中去 po.add_account(account) return (po, account)
def register_account(self, account, portfolio_cookie=None): ''' 注册一个account到portfolio组合中 account 也可以是一个策略类,实现其 on_bar 方法 :param account: 被注册的account :return: ''' # 查找 portfolio if len(self.portfolio_list.keys()) < 1: po = self.new_portfolio() elif portfolio_cookie is not None: po = self.portfolio_list[portfolio_cookie] else: po = list(self.portfolio_list.values())[0] # 把account 添加到 portfolio中去 po.add_account(account) return (po, account)
[ "注册一个account到portfolio组合中", "account", "也可以是一个策略类,实现其", "on_bar", "方法", ":", "param", "account", ":", "被注册的account", ":", "return", ":" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L408-L424
[ "def", "register_account", "(", "self", ",", "account", ",", "portfolio_cookie", "=", "None", ")", ":", "# 查找 portfolio", "if", "len", "(", "self", ".", "portfolio_list", ".", "keys", "(", ")", ")", "<", "1", ":", "po", "=", "self", ".", "new_portfolio",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.save
将QA_USER的信息存入数据库 ATTENTION: 在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save
QUANTAXIS/QAARP/QAUser.py
def save(self): """ 将QA_USER的信息存入数据库 ATTENTION: 在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save """ if self.wechat_id is not None: self.client.update( {'wechat_id': self.wechat_id}, {'$set': self.message}, upsert=True ) else: self.client.update( { 'username': self.username, 'password': self.password }, {'$set': self.message}, upsert=True ) # user ==> portfolio 的存储 # account的存储在 portfolio.save ==> account.save 中 for portfolio in list(self.portfolio_list.values()): portfolio.save()
def save(self): """ 将QA_USER的信息存入数据库 ATTENTION: 在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save """ if self.wechat_id is not None: self.client.update( {'wechat_id': self.wechat_id}, {'$set': self.message}, upsert=True ) else: self.client.update( { 'username': self.username, 'password': self.password }, {'$set': self.message}, upsert=True ) # user ==> portfolio 的存储 # account的存储在 portfolio.save ==> account.save 中 for portfolio in list(self.portfolio_list.values()): portfolio.save()
[ "将QA_USER的信息存入数据库" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L445-L473
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "wechat_id", "is", "not", "None", ":", "self", ".", "client", ".", "update", "(", "{", "'wechat_id'", ":", "self", ".", "wechat_id", "}", ",", "{", "'$set'", ":", "self", ".", "message", "}",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.sync
基于账户/密码去sync数据库
QUANTAXIS/QAARP/QAUser.py
def sync(self): """基于账户/密码去sync数据库 """ if self.wechat_id is not None: res = self.client.find_one({'wechat_id': self.wechat_id}) else: res = self.client.find_one( { 'username': self.username, 'password': self.password } ) if res is None: if self.client.find_one({'username': self.username}) is None: self.client.insert_one(self.message) return self else: raise RuntimeError('账户名已存在且账户密码不匹配') else: self.reload(res) return self
def sync(self): """基于账户/密码去sync数据库 """ if self.wechat_id is not None: res = self.client.find_one({'wechat_id': self.wechat_id}) else: res = self.client.find_one( { 'username': self.username, 'password': self.password } ) if res is None: if self.client.find_one({'username': self.username}) is None: self.client.insert_one(self.message) return self else: raise RuntimeError('账户名已存在且账户密码不匹配') else: self.reload(res) return self
[ "基于账户", "/", "密码去sync数据库" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L475-L499
[ "def", "sync", "(", "self", ")", ":", "if", "self", ".", "wechat_id", "is", "not", "None", ":", "res", "=", "self", ".", "client", ".", "find_one", "(", "{", "'wechat_id'", ":", "self", ".", "wechat_id", "}", ")", "else", ":", "res", "=", "self", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_User.reload
恢复方法 Arguments: message {[type]} -- [description]
QUANTAXIS/QAARP/QAUser.py
def reload(self, message): """恢复方法 Arguments: message {[type]} -- [description] """ self.phone = message.get('phone') self.level = message.get('level') self.utype = message.get('utype') self.coins = message.get('coins') self.wechat_id = message.get('wechat_id') self.coins_history = message.get('coins_history') self.money = message.get('money') self._subscribed_strategy = message.get('subuscribed_strategy') self._subscribed_code = message.get('subscribed_code') self.username = message.get('username') self.password = message.get('password') self.user_cookie = message.get('user_cookie') # portfolio_list = [item['portfolio_cookie'] for item in DATABASE.portfolio.find( {'user_cookie': self.user_cookie}, {'portfolio_cookie': 1, '_id': 0})] # portfolio_list = message.get('portfolio_list') if len(portfolio_list) > 0: self.portfolio_list = dict( zip( portfolio_list, [ QA_Portfolio( user_cookie=self.user_cookie, portfolio_cookie=item ) for item in portfolio_list ] ) ) else: self.portfolio_list = {}
def reload(self, message): """恢复方法 Arguments: message {[type]} -- [description] """ self.phone = message.get('phone') self.level = message.get('level') self.utype = message.get('utype') self.coins = message.get('coins') self.wechat_id = message.get('wechat_id') self.coins_history = message.get('coins_history') self.money = message.get('money') self._subscribed_strategy = message.get('subuscribed_strategy') self._subscribed_code = message.get('subscribed_code') self.username = message.get('username') self.password = message.get('password') self.user_cookie = message.get('user_cookie') # portfolio_list = [item['portfolio_cookie'] for item in DATABASE.portfolio.find( {'user_cookie': self.user_cookie}, {'portfolio_cookie': 1, '_id': 0})] # portfolio_list = message.get('portfolio_list') if len(portfolio_list) > 0: self.portfolio_list = dict( zip( portfolio_list, [ QA_Portfolio( user_cookie=self.user_cookie, portfolio_cookie=item ) for item in portfolio_list ] ) ) else: self.portfolio_list = {}
[ "恢复方法" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L540-L577
[ "def", "reload", "(", "self", ",", "message", ")", ":", "self", ".", "phone", "=", "message", ".", "get", "(", "'phone'", ")", "self", ".", "level", "=", "message", ".", "get", "(", "'level'", ")", "self", ".", "utype", "=", "message", ".", "get", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_format_date2str
对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串 支持格式包括: 1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S" 2. datetime.datetime 3. pd.Timestamp 4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019-03-02" :param cursor_date: str/datetime.datetime/int 日期或时间 :return: str 返回字符串格式日期
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_format_date2str(cursor_date): """ 对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串 支持格式包括: 1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S" 2. datetime.datetime 3. pd.Timestamp 4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019-03-02" :param cursor_date: str/datetime.datetime/int 日期或时间 :return: str 返回字符串格式日期 """ if isinstance(cursor_date, datetime.datetime): cursor_date = str(cursor_date)[:10] elif isinstance(cursor_date, str): try: cursor_date = str(pd.Timestamp(cursor_date))[:10] except: raise ValueError('请输入正确的日期格式, 建议 "%Y-%m-%d"') elif isinstance(cursor_date, int): cursor_date = str(pd.Timestamp("{:<014d}".format(cursor_date)))[:10] else: raise ValueError('请输入正确的日期格式,建议 "%Y-%m-%d"') return cursor_date
def QA_util_format_date2str(cursor_date): """ 对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串 支持格式包括: 1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S" 2. datetime.datetime 3. pd.Timestamp 4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019-03-02" :param cursor_date: str/datetime.datetime/int 日期或时间 :return: str 返回字符串格式日期 """ if isinstance(cursor_date, datetime.datetime): cursor_date = str(cursor_date)[:10] elif isinstance(cursor_date, str): try: cursor_date = str(pd.Timestamp(cursor_date))[:10] except: raise ValueError('请输入正确的日期格式, 建议 "%Y-%m-%d"') elif isinstance(cursor_date, int): cursor_date = str(pd.Timestamp("{:<014d}".format(cursor_date)))[:10] else: raise ValueError('请输入正确的日期格式,建议 "%Y-%m-%d"') return cursor_date
[ "对输入日期进行格式化处理,返回格式为", "%Y", "-", "%m", "-", "%d", "格式字符串", "支持格式包括", ":", "1", ".", "str", ":", "%Y%m%d", "%Y%m%d%H%M%S", "%Y%m%d", "%H", ":", "%M", ":", "%S", "%Y", "-", "%m", "-", "%d", "%Y", "-", "%m", "-", "%d", "%H", ":", "%M", ":", "%S", ...
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7135-L7159
[ "def", "QA_util_format_date2str", "(", "cursor_date", ")", ":", "if", "isinstance", "(", "cursor_date", ",", "datetime", ".", "datetime", ")", ":", "cursor_date", "=", "str", "(", "cursor_date", ")", "[", ":", "10", "]", "elif", "isinstance", "(", "cursor_da...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_next_trade_date
得到下 n 个交易日 (不包含当前交易日) :param date: :param n:
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_next_trade_date(cursor_date, n=1): """ 得到下 n 个交易日 (不包含当前交易日) :param date: :param n: """ cursor_date = QA_util_format_date2str(cursor_date) if cursor_date in trade_date_sse: # 如果指定日期为交易日 return QA_util_date_gap(cursor_date, n, "gt") real_pre_trade_date = QA_util_get_real_date(cursor_date) return QA_util_date_gap(real_pre_trade_date, n, "gt")
def QA_util_get_next_trade_date(cursor_date, n=1): """ 得到下 n 个交易日 (不包含当前交易日) :param date: :param n: """ cursor_date = QA_util_format_date2str(cursor_date) if cursor_date in trade_date_sse: # 如果指定日期为交易日 return QA_util_date_gap(cursor_date, n, "gt") real_pre_trade_date = QA_util_get_real_date(cursor_date) return QA_util_date_gap(real_pre_trade_date, n, "gt")
[ "得到下", "n", "个交易日", "(", "不包含当前交易日", ")", ":", "param", "date", ":", ":", "param", "n", ":" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7162-L7174
[ "def", "QA_util_get_next_trade_date", "(", "cursor_date", ",", "n", "=", "1", ")", ":", "cursor_date", "=", "QA_util_format_date2str", "(", "cursor_date", ")", "if", "cursor_date", "in", "trade_date_sse", ":", "# 如果指定日期为交易日", "return", "QA_util_date_gap", "(", "curs...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_pre_trade_date
得到前 n 个交易日 (不包含当前交易日) :param date: :param n:
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_pre_trade_date(cursor_date, n=1): """ 得到前 n 个交易日 (不包含当前交易日) :param date: :param n: """ cursor_date = QA_util_format_date2str(cursor_date) if cursor_date in trade_date_sse: return QA_util_date_gap(cursor_date, n, "lt") real_aft_trade_date = QA_util_get_real_date(cursor_date) return QA_util_date_gap(real_aft_trade_date, n, "lt")
def QA_util_get_pre_trade_date(cursor_date, n=1): """ 得到前 n 个交易日 (不包含当前交易日) :param date: :param n: """ cursor_date = QA_util_format_date2str(cursor_date) if cursor_date in trade_date_sse: return QA_util_date_gap(cursor_date, n, "lt") real_aft_trade_date = QA_util_get_real_date(cursor_date) return QA_util_date_gap(real_aft_trade_date, n, "lt")
[ "得到前", "n", "个交易日", "(", "不包含当前交易日", ")", ":", "param", "date", ":", ":", "param", "n", ":" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7177-L7188
[ "def", "QA_util_get_pre_trade_date", "(", "cursor_date", ",", "n", "=", "1", ")", ":", "cursor_date", "=", "QA_util_format_date2str", "(", "cursor_date", ")", "if", "cursor_date", "in", "trade_date_sse", ":", "return", "QA_util_date_gap", "(", "cursor_date", ",", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_if_tradetime
时间是否交易
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_if_tradetime( _time=datetime.datetime.now(), market=MARKET_TYPE.STOCK_CN, code=None ): '时间是否交易' _time = datetime.datetime.strptime(str(_time)[0:19], '%Y-%m-%d %H:%M:%S') if market is MARKET_TYPE.STOCK_CN: if QA_util_if_trade(str(_time.date())[0:10]): if _time.hour in [10, 13, 14]: return True elif _time.hour in [ 9 ] and _time.minute >= 15: # 修改成9:15 加入 9:15-9:30的盘前竞价时间 return True elif _time.hour in [11] and _time.minute <= 30: return True else: return False else: return False elif market is MARKET_TYPE.FUTURE_CN: date_today=str(_time.date()) date_yesterday=str((_time-datetime.timedelta(days=1)).date()) is_today_open=QA_util_if_trade(date_today) is_yesterday_open=QA_util_if_trade(date_yesterday) #考虑周六日的期货夜盘情况 if is_today_open==False: #可能是周六或者周日 if is_yesterday_open==False or (_time.hour > 2 or _time.hour == 2 and _time.minute > 30): return False shortName = "" # i , p for i in range(len(code)): ch = code[i] if ch.isdigit(): # ch >= 48 and ch <= 57: break shortName += code[i].upper() period = [ [9, 0, 10, 15], [10, 30, 11, 30], [13, 30, 15, 0] ] if (shortName in ["IH", 'IF', 'IC']): period = [ [9, 30, 11, 30], [13, 0, 15, 0] ] elif (shortName in ["T", "TF"]): period = [ [9, 15, 11, 30], [13, 0, 15, 15] ] if 0<=_time.weekday<=4: for i in range(len(period)): p = period[i] if ((_time.hour > p[0] or (_time.hour == p[0] and _time.minute >= p[1])) and (_time.hour < p[2] or (_time.hour == p[2] and _time.minute < p[3]))): return True #最新夜盘时间表_2019.03.29 nperiod = [ [ ['AU', 'AG', 'SC'], [21, 0, 2, 30] ], [ ['CU', 'AL', 'ZN', 'PB', 'SN', 'NI'], [21, 0, 1, 0] ], [ ['RU', 'RB', 'HC', 'BU','FU','SP'], [21, 0, 23, 0] ], [ ['A', 'B', 'Y', 'M', 'JM', 'J', 'P', 'I', 'L', 'V', 'PP', 'EG', 'C', 'CS'], [21, 0, 23, 0] ], [ ['SR', 'CF', 'RM', 'MA', 'TA', 'ZC', 'FG', 'IO', 'CY'], [21, 0, 23, 30] ], ] for i in range(len(nperiod)): for j in range(len(nperiod[i][0])): if nperiod[i][0][j] == shortName: p = nperiod[i][1] condA = _time.hour > p[0] or (_time.hour == p[0] and _time.minute >= p[1]) condB = _time.hour < p[2] or (_time.hour == p[2] and _time.minute < p[3]) # in one day if p[2] >= p[0]: if ((_time.weekday >= 0 and _time.weekday <= 4) and condA and condB): return True else: if (((_time.weekday >= 0 and _time.weekday <= 4) and condA) or ((_time.weekday >= 1 and _time.weekday <= 5) and condB)): return True return False return False
def QA_util_if_tradetime( _time=datetime.datetime.now(), market=MARKET_TYPE.STOCK_CN, code=None ): '时间是否交易' _time = datetime.datetime.strptime(str(_time)[0:19], '%Y-%m-%d %H:%M:%S') if market is MARKET_TYPE.STOCK_CN: if QA_util_if_trade(str(_time.date())[0:10]): if _time.hour in [10, 13, 14]: return True elif _time.hour in [ 9 ] and _time.minute >= 15: # 修改成9:15 加入 9:15-9:30的盘前竞价时间 return True elif _time.hour in [11] and _time.minute <= 30: return True else: return False else: return False elif market is MARKET_TYPE.FUTURE_CN: date_today=str(_time.date()) date_yesterday=str((_time-datetime.timedelta(days=1)).date()) is_today_open=QA_util_if_trade(date_today) is_yesterday_open=QA_util_if_trade(date_yesterday) #考虑周六日的期货夜盘情况 if is_today_open==False: #可能是周六或者周日 if is_yesterday_open==False or (_time.hour > 2 or _time.hour == 2 and _time.minute > 30): return False shortName = "" # i , p for i in range(len(code)): ch = code[i] if ch.isdigit(): # ch >= 48 and ch <= 57: break shortName += code[i].upper() period = [ [9, 0, 10, 15], [10, 30, 11, 30], [13, 30, 15, 0] ] if (shortName in ["IH", 'IF', 'IC']): period = [ [9, 30, 11, 30], [13, 0, 15, 0] ] elif (shortName in ["T", "TF"]): period = [ [9, 15, 11, 30], [13, 0, 15, 15] ] if 0<=_time.weekday<=4: for i in range(len(period)): p = period[i] if ((_time.hour > p[0] or (_time.hour == p[0] and _time.minute >= p[1])) and (_time.hour < p[2] or (_time.hour == p[2] and _time.minute < p[3]))): return True #最新夜盘时间表_2019.03.29 nperiod = [ [ ['AU', 'AG', 'SC'], [21, 0, 2, 30] ], [ ['CU', 'AL', 'ZN', 'PB', 'SN', 'NI'], [21, 0, 1, 0] ], [ ['RU', 'RB', 'HC', 'BU','FU','SP'], [21, 0, 23, 0] ], [ ['A', 'B', 'Y', 'M', 'JM', 'J', 'P', 'I', 'L', 'V', 'PP', 'EG', 'C', 'CS'], [21, 0, 23, 0] ], [ ['SR', 'CF', 'RM', 'MA', 'TA', 'ZC', 'FG', 'IO', 'CY'], [21, 0, 23, 30] ], ] for i in range(len(nperiod)): for j in range(len(nperiod[i][0])): if nperiod[i][0][j] == shortName: p = nperiod[i][1] condA = _time.hour > p[0] or (_time.hour == p[0] and _time.minute >= p[1]) condB = _time.hour < p[2] or (_time.hour == p[2] and _time.minute < p[3]) # in one day if p[2] >= p[0]: if ((_time.weekday >= 0 and _time.weekday <= 4) and condA and condB): return True else: if (((_time.weekday >= 0 and _time.weekday <= 4) and condA) or ((_time.weekday >= 1 and _time.weekday <= 5) and condB)): return True return False return False
[ "时间是否交易" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7205-L7306
[ "def", "QA_util_if_tradetime", "(", "_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "market", "=", "MARKET_TYPE", ".", "STOCK_CN", ",", "code", "=", "None", ")", ":", "_time", "=", "datetime", ".", "datetime", ".", "strptime", "(", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_real_date
获取真实的交易日期,其中,第三个参数towards是表示向前/向后推 towards=1 日期向后迭代 towards=-1 日期向前迭代 @ yutiansut
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_real_date(date, trade_list=trade_date_sse, towards=-1): """ 获取真实的交易日期,其中,第三个参数towards是表示向前/向后推 towards=1 日期向后迭代 towards=-1 日期向前迭代 @ yutiansut """ date = str(date)[0:10] if towards == 1: while date not in trade_list: date = str( datetime.datetime.strptime(str(date)[0:10], '%Y-%m-%d') + datetime.timedelta(days=1) )[0:10] else: return str(date)[0:10] elif towards == -1: while date not in trade_list: date = str( datetime.datetime.strptime(str(date)[0:10], '%Y-%m-%d') - datetime.timedelta(days=1) )[0:10] else: return str(date)[0:10]
def QA_util_get_real_date(date, trade_list=trade_date_sse, towards=-1): """ 获取真实的交易日期,其中,第三个参数towards是表示向前/向后推 towards=1 日期向后迭代 towards=-1 日期向前迭代 @ yutiansut """ date = str(date)[0:10] if towards == 1: while date not in trade_list: date = str( datetime.datetime.strptime(str(date)[0:10], '%Y-%m-%d') + datetime.timedelta(days=1) )[0:10] else: return str(date)[0:10] elif towards == -1: while date not in trade_list: date = str( datetime.datetime.strptime(str(date)[0:10], '%Y-%m-%d') - datetime.timedelta(days=1) )[0:10] else: return str(date)[0:10]
[ "获取真实的交易日期", "其中", "第三个参数towards是表示向前", "/", "向后推", "towards", "=", "1", "日期向后迭代", "towards", "=", "-", "1", "日期向前迭代", "@", "yutiansut" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7341-L7367
[ "def", "QA_util_get_real_date", "(", "date", ",", "trade_list", "=", "trade_date_sse", ",", "towards", "=", "-", "1", ")", ":", "date", "=", "str", "(", "date", ")", "[", "0", ":", "10", "]", "if", "towards", "==", "1", ":", "while", "date", "not", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_real_datelist
取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist @yutiansut 2017/8/10 当start end中间没有交易日 返回None, None @yutiansut/ 2017-12-19
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_real_datelist(start, end): """ 取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist @yutiansut 2017/8/10 当start end中间没有交易日 返回None, None @yutiansut/ 2017-12-19 """ real_start = QA_util_get_real_date(start, trade_date_sse, 1) real_end = QA_util_get_real_date(end, trade_date_sse, -1) if trade_date_sse.index(real_start) > trade_date_sse.index(real_end): return None, None else: return (real_start, real_end)
def QA_util_get_real_datelist(start, end): """ 取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist @yutiansut 2017/8/10 当start end中间没有交易日 返回None, None @yutiansut/ 2017-12-19 """ real_start = QA_util_get_real_date(start, trade_date_sse, 1) real_end = QA_util_get_real_date(end, trade_date_sse, -1) if trade_date_sse.index(real_start) > trade_date_sse.index(real_end): return None, None else: return (real_start, real_end)
[ "取数据的真实区间", "返回的时候用", "start", "end", "=", "QA_util_get_real_datelist", "@yutiansut", "2017", "/", "8", "/", "10" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7370-L7384
[ "def", "QA_util_get_real_datelist", "(", "start", ",", "end", ")", ":", "real_start", "=", "QA_util_get_real_date", "(", "start", ",", "trade_date_sse", ",", "1", ")", "real_end", "=", "QA_util_get_real_date", "(", "end", ",", "trade_date_sse", ",", "-", "1", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_trade_range
给出交易具体时间
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_trade_range(start, end): '给出交易具体时间' start, end = QA_util_get_real_datelist(start, end) if start is not None: return trade_date_sse[trade_date_sse .index(start):trade_date_sse.index(end) + 1:1] else: return None
def QA_util_get_trade_range(start, end): '给出交易具体时间' start, end = QA_util_get_real_datelist(start, end) if start is not None: return trade_date_sse[trade_date_sse .index(start):trade_date_sse.index(end) + 1:1] else: return None
[ "给出交易具体时间" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7387-L7394
[ "def", "QA_util_get_trade_range", "(", "start", ",", "end", ")", ":", "start", ",", "end", "=", "QA_util_get_real_datelist", "(", "start", ",", "end", ")", "if", "start", "is", "not", "None", ":", "return", "trade_date_sse", "[", "trade_date_sse", ".", "inde...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_trade_gap
返回start_day到end_day中间有多少个交易天 算首尾
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_trade_gap(start, end): '返回start_day到end_day中间有多少个交易天 算首尾' start, end = QA_util_get_real_datelist(start, end) if start is not None: return trade_date_sse.index(end) + 1 - trade_date_sse.index(start) else: return 0
def QA_util_get_trade_gap(start, end): '返回start_day到end_day中间有多少个交易天 算首尾' start, end = QA_util_get_real_datelist(start, end) if start is not None: return trade_date_sse.index(end) + 1 - trade_date_sse.index(start) else: return 0
[ "返回start_day到end_day中间有多少个交易天", "算首尾" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7397-L7403
[ "def", "QA_util_get_trade_gap", "(", "start", ",", "end", ")", ":", "start", ",", "end", "=", "QA_util_get_real_datelist", "(", "start", ",", "end", ")", "if", "start", "is", "not", "None", ":", "return", "trade_date_sse", ".", "index", "(", "end", ")", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_date_gap
:param date: 字符串起始日 类型 str eg: 2018-11-11 :param gap: 整数 间隔多数个交易日 :param methods: gt大于 ,gte 大于等于, 小于lt ,小于等于lte , 等于=== :return: 字符串 eg:2000-01-01
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_date_gap(date, gap, methods): ''' :param date: 字符串起始日 类型 str eg: 2018-11-11 :param gap: 整数 间隔多数个交易日 :param methods: gt大于 ,gte 大于等于, 小于lt ,小于等于lte , 等于=== :return: 字符串 eg:2000-01-01 ''' try: if methods in ['>', 'gt']: return trade_date_sse[trade_date_sse.index(date) + gap] elif methods in ['>=', 'gte']: return trade_date_sse[trade_date_sse.index(date) + gap - 1] elif methods in ['<', 'lt']: return trade_date_sse[trade_date_sse.index(date) - gap] elif methods in ['<=', 'lte']: return trade_date_sse[trade_date_sse.index(date) - gap + 1] elif methods in ['==', '=', 'eq']: return date except: return 'wrong date'
def QA_util_date_gap(date, gap, methods): ''' :param date: 字符串起始日 类型 str eg: 2018-11-11 :param gap: 整数 间隔多数个交易日 :param methods: gt大于 ,gte 大于等于, 小于lt ,小于等于lte , 等于=== :return: 字符串 eg:2000-01-01 ''' try: if methods in ['>', 'gt']: return trade_date_sse[trade_date_sse.index(date) + gap] elif methods in ['>=', 'gte']: return trade_date_sse[trade_date_sse.index(date) + gap - 1] elif methods in ['<', 'lt']: return trade_date_sse[trade_date_sse.index(date) - gap] elif methods in ['<=', 'lte']: return trade_date_sse[trade_date_sse.index(date) - gap + 1] elif methods in ['==', '=', 'eq']: return date except: return 'wrong date'
[ ":", "param", "date", ":", "字符串起始日", "类型", "str", "eg", ":", "2018", "-", "11", "-", "11", ":", "param", "gap", ":", "整数", "间隔多数个交易日", ":", "param", "methods", ":", "gt大于", ",gte", "大于等于,", "小于lt", ",小于等于lte", ",", "等于", "===", ":", "return", ":", ...
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7406-L7426
[ "def", "QA_util_date_gap", "(", "date", ",", "gap", ",", "methods", ")", ":", "try", ":", "if", "methods", "in", "[", "'>'", ",", "'gt'", "]", ":", "return", "trade_date_sse", "[", "trade_date_sse", ".", "index", "(", "date", ")", "+", "gap", "]", "e...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_trade_datetime
交易的真实日期 Returns: [type] -- [description]
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_trade_datetime(dt=datetime.datetime.now()): """交易的真实日期 Returns: [type] -- [description] """ #dt= datetime.datetime.now() if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0): return str(dt.date()) else: return QA_util_get_real_date(str(dt.date()), trade_date_sse, 1)
def QA_util_get_trade_datetime(dt=datetime.datetime.now()): """交易的真实日期 Returns: [type] -- [description] """ #dt= datetime.datetime.now() if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0): return str(dt.date()) else: return QA_util_get_real_date(str(dt.date()), trade_date_sse, 1)
[ "交易的真实日期" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7429-L7441
[ "def", "QA_util_get_trade_datetime", "(", "dt", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", ":", "#dt= datetime.datetime.now()", "if", "QA_util_if_trade", "(", "str", "(", "dt", ".", "date", "(", ")", ")", ")", "and", "dt", ".", "time", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_get_order_datetime
委托的真实日期 Returns: [type] -- [description]
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_get_order_datetime(dt): """委托的真实日期 Returns: [type] -- [description] """ #dt= datetime.datetime.now() dt = datetime.datetime.strptime(str(dt)[0:19], '%Y-%m-%d %H:%M:%S') if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0): return str(dt) else: # print('before') # print(QA_util_date_gap(str(dt.date()),1,'lt')) return '{} {}'.format( QA_util_date_gap(str(dt.date()), 1, 'lt'), dt.time() )
def QA_util_get_order_datetime(dt): """委托的真实日期 Returns: [type] -- [description] """ #dt= datetime.datetime.now() dt = datetime.datetime.strptime(str(dt)[0:19], '%Y-%m-%d %H:%M:%S') if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0): return str(dt) else: # print('before') # print(QA_util_date_gap(str(dt.date()),1,'lt')) return '{} {}'.format( QA_util_date_gap(str(dt.date()), 1, 'lt'), dt.time() )
[ "委托的真实日期" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7444-L7464
[ "def", "QA_util_get_order_datetime", "(", "dt", ")", ":", "#dt= datetime.datetime.now()", "dt", "=", "datetime", ".", "datetime", ".", "strptime", "(", "str", "(", "dt", ")", "[", "0", ":", "19", "]", ",", "'%Y-%m-%d %H:%M:%S'", ")", "if", "QA_util_if_trade", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_future_to_tradedatetime
输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换 Arguments: real_datetime {[type]} -- [description] Returns: [type] -- [description]
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_future_to_tradedatetime(real_datetime): """输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换 Arguments: real_datetime {[type]} -- [description] Returns: [type] -- [description] """ if len(str(real_datetime)) >= 19: dt = datetime.datetime.strptime( str(real_datetime)[0:19], '%Y-%m-%d %H:%M:%S' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_next_datetime(dt, 1) elif len(str(real_datetime)) == 16: dt = datetime.datetime.strptime( str(real_datetime)[0:16], '%Y-%m-%d %H:%M' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_next_datetime(dt, 1)
def QA_util_future_to_tradedatetime(real_datetime): """输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换 Arguments: real_datetime {[type]} -- [description] Returns: [type] -- [description] """ if len(str(real_datetime)) >= 19: dt = datetime.datetime.strptime( str(real_datetime)[0:19], '%Y-%m-%d %H:%M:%S' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_next_datetime(dt, 1) elif len(str(real_datetime)) == 16: dt = datetime.datetime.strptime( str(real_datetime)[0:16], '%Y-%m-%d %H:%M' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_next_datetime(dt, 1)
[ "输入是真实交易时间", "返回按期货交易所规定的时间", "*", "适用于tb", "/", "文华", "/", "博弈的转换" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7467-L7493
[ "def", "QA_util_future_to_tradedatetime", "(", "real_datetime", ")", ":", "if", "len", "(", "str", "(", "real_datetime", ")", ")", ">=", "19", ":", "dt", "=", "datetime", ".", "datetime", ".", "strptime", "(", "str", "(", "real_datetime", ")", "[", "0", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_future_to_realdatetime
输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换 Arguments: trade_datetime {[type]} -- [description] Returns: [type] -- [description]
QUANTAXIS/QAUtil/QADate_trade.py
def QA_util_future_to_realdatetime(trade_datetime): """输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换 Arguments: trade_datetime {[type]} -- [description] Returns: [type] -- [description] """ if len(str(trade_datetime)) == 19: dt = datetime.datetime.strptime( str(trade_datetime)[0:19], '%Y-%m-%d %H:%M:%S' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_last_datetime(dt, 1) elif len(str(trade_datetime)) == 16: dt = datetime.datetime.strptime( str(trade_datetime)[0:16], '%Y-%m-%d %H:%M' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_last_datetime(dt, 1)
def QA_util_future_to_realdatetime(trade_datetime): """输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换 Arguments: trade_datetime {[type]} -- [description] Returns: [type] -- [description] """ if len(str(trade_datetime)) == 19: dt = datetime.datetime.strptime( str(trade_datetime)[0:19], '%Y-%m-%d %H:%M:%S' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_last_datetime(dt, 1) elif len(str(trade_datetime)) == 16: dt = datetime.datetime.strptime( str(trade_datetime)[0:16], '%Y-%m-%d %H:%M' ) return dt if dt.time( ) < datetime.time(21, 0) else QA_util_get_last_datetime(dt, 1)
[ "输入是交易所规定的时间", "返回真实时间", "*", "适用于通达信的时间转换" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate_trade.py#L7496-L7522
[ "def", "QA_util_future_to_realdatetime", "(", "trade_datetime", ")", ":", "if", "len", "(", "str", "(", "trade_datetime", ")", ")", "==", "19", ":", "dt", "=", "datetime", ".", "datetime", ".", "strptime", "(", "str", "(", "trade_datetime", ")", "[", "0", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_make_hour_index
创建股票的小时线的index Arguments: day {[type]} -- [description] Returns: [type] -- [description]
QUANTAXIS/QAUtil/QABar.py
def QA_util_make_hour_index(day, type_='1h'): """创建股票的小时线的index Arguments: day {[type]} -- [description] Returns: [type] -- [description] """ if QA_util_if_trade(day) is True: return pd.date_range( str(day) + ' 09:30:00', str(day) + ' 11:30:00', freq=type_, closed='right' ).append( pd.date_range( str(day) + ' 13:00:00', str(day) + ' 15:00:00', freq=type_, closed='right' ) ) else: return pd.DataFrame(['No trade'])
def QA_util_make_hour_index(day, type_='1h'): """创建股票的小时线的index Arguments: day {[type]} -- [description] Returns: [type] -- [description] """ if QA_util_if_trade(day) is True: return pd.date_range( str(day) + ' 09:30:00', str(day) + ' 11:30:00', freq=type_, closed='right' ).append( pd.date_range( str(day) + ' 13:00:00', str(day) + ' 15:00:00', freq=type_, closed='right' ) ) else: return pd.DataFrame(['No trade'])
[ "创建股票的小时线的index" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QABar.py#L96-L121
[ "def", "QA_util_make_hour_index", "(", "day", ",", "type_", "=", "'1h'", ")", ":", "if", "QA_util_if_trade", "(", "day", ")", "is", "True", ":", "return", "pd", ".", "date_range", "(", "str", "(", "day", ")", "+", "' 09:30:00'", ",", "str", "(", "day",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_time_gap
分钟线回测的时候的gap
QUANTAXIS/QAUtil/QABar.py
def QA_util_time_gap(time, gap, methods, type_): '分钟线回测的时候的gap' min_len = int(240 / int(str(type_).split('min')[0])) day_gap = math.ceil(gap / min_len) if methods in ['>', 'gt']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ):trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + day_gap + 1] ] ).reset_index() return np.asarray( data[data[0] > time].head(gap)[0].apply(lambda x: str(x)) ).tolist()[-1] elif methods in ['>=', 'gte']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ):trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + day_gap + 1] ] ).reset_index() return np.asarray( data[data[0] >= time].head(gap)[0].apply(lambda x: str(x)) ).tolist()[-1] elif methods in ['<', 'lt']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) - day_gap:trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + 1] ] ).reset_index() return np.asarray( data[data[0] < time].tail(gap)[0].apply(lambda x: str(x)) ).tolist()[0] elif methods in ['<=', 'lte']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) - day_gap:trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + 1] ] ).reset_index() return np.asarray( data[data[0] <= time].tail(gap)[0].apply(lambda x: str(x)) ).tolist()[0] elif methods in ['==', '=', 'eq']: return time
def QA_util_time_gap(time, gap, methods, type_): '分钟线回测的时候的gap' min_len = int(240 / int(str(type_).split('min')[0])) day_gap = math.ceil(gap / min_len) if methods in ['>', 'gt']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ):trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + day_gap + 1] ] ).reset_index() return np.asarray( data[data[0] > time].head(gap)[0].apply(lambda x: str(x)) ).tolist()[-1] elif methods in ['>=', 'gte']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ):trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + day_gap + 1] ] ).reset_index() return np.asarray( data[data[0] >= time].head(gap)[0].apply(lambda x: str(x)) ).tolist()[-1] elif methods in ['<', 'lt']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) - day_gap:trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + 1] ] ).reset_index() return np.asarray( data[data[0] < time].tail(gap)[0].apply(lambda x: str(x)) ).tolist()[0] elif methods in ['<=', 'lte']: data = pd.concat( [ pd.DataFrame(QA_util_make_min_index(day, type_)) for day in trade_date_sse[trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) - day_gap:trade_date_sse.index( str( datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date() ) ) + 1] ] ).reset_index() return np.asarray( data[data[0] <= time].tail(gap)[0].apply(lambda x: str(x)) ).tolist()[0] elif methods in ['==', '=', 'eq']: return time
[ "分钟线回测的时候的gap" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QABar.py#L124-L217
[ "def", "QA_util_time_gap", "(", "time", ",", "gap", ",", "methods", ",", "type_", ")", ":", "min_len", "=", "int", "(", "240", "/", "int", "(", "str", "(", "type_", ")", ".", "split", "(", "'min'", ")", "[", "0", "]", ")", ")", "day_gap", "=", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_save_csv
QA_util_save_csv(data,name,column,location) 将list保存成csv 第一个参数是list 第二个参数是要保存的名字 第三个参数是行的名称(可选) 第四个是保存位置(可选) @yutiansut
QUANTAXIS/QAUtil/QACsv.py
def QA_util_save_csv(data, name, column=None, location=None): # 重写了一下保存的模式 # 增加了对于可迭代对象的判断 2017/8/10 """ QA_util_save_csv(data,name,column,location) 将list保存成csv 第一个参数是list 第二个参数是要保存的名字 第三个参数是行的名称(可选) 第四个是保存位置(可选) @yutiansut """ assert isinstance(data, list) if location is None: path = './' + str(name) + '.csv' else: path = location + str(name) + '.csv' with open(path, 'w', newline='') as f: csvwriter = csv.writer(f) if column is None: pass else: csvwriter.writerow(column) for item in data: if isinstance(item, list): csvwriter.writerow(item) else: csvwriter.writerow([item])
def QA_util_save_csv(data, name, column=None, location=None): # 重写了一下保存的模式 # 增加了对于可迭代对象的判断 2017/8/10 """ QA_util_save_csv(data,name,column,location) 将list保存成csv 第一个参数是list 第二个参数是要保存的名字 第三个参数是行的名称(可选) 第四个是保存位置(可选) @yutiansut """ assert isinstance(data, list) if location is None: path = './' + str(name) + '.csv' else: path = location + str(name) + '.csv' with open(path, 'w', newline='') as f: csvwriter = csv.writer(f) if column is None: pass else: csvwriter.writerow(column) for item in data: if isinstance(item, list): csvwriter.writerow(item) else: csvwriter.writerow([item])
[ "QA_util_save_csv", "(", "data", "name", "column", "location", ")" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QACsv.py#L28-L59
[ "def", "QA_util_save_csv", "(", "data", ",", "name", ",", "column", "=", "None", ",", "location", "=", "None", ")", ":", "# 重写了一下保存的模式", "# 增加了对于可迭代对象的判断 2017/8/10", "assert", "isinstance", "(", "data", ",", "list", ")", "if", "location", "is", "None", ":", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SPEBroker.query_positions
查询现金和持仓 Arguments: accounts {[type]} -- [description] Returns: dict-- {'cash_available':xxx,'hold_available':xxx}
QUANTAXIS/QAMarket/QAShipaneBroker.py
def query_positions(self, accounts): """查询现金和持仓 Arguments: accounts {[type]} -- [description] Returns: dict-- {'cash_available':xxx,'hold_available':xxx} """ try: data = self.call("positions", {'client': accounts}) if data is not None: cash_part = data.get('subAccounts', {}).get('人民币', False) if cash_part: cash_available = cash_part.get('可用金额', cash_part.get('可用')) position_part = data.get('dataTable', False) if position_part: res = data.get('dataTable', False) if res: hold_headers = res['columns'] hold_headers = [ cn_en_compare[item] for item in hold_headers ] hold_available = pd.DataFrame( res['rows'], columns=hold_headers ) if len(hold_available) == 1 and hold_available.amount[0] in [ None, '', 0 ]: hold_available = pd.DataFrame( data=None, columns=hold_headers ) return { 'cash_available': cash_available, 'hold_available': hold_available.assign( amount=hold_available.amount.apply(float) ).loc[:, ['code', 'amount']].set_index('code').amount } else: print(data) return False, 'None ACCOUNT' except: return False
def query_positions(self, accounts): """查询现金和持仓 Arguments: accounts {[type]} -- [description] Returns: dict-- {'cash_available':xxx,'hold_available':xxx} """ try: data = self.call("positions", {'client': accounts}) if data is not None: cash_part = data.get('subAccounts', {}).get('人民币', False) if cash_part: cash_available = cash_part.get('可用金额', cash_part.get('可用')) position_part = data.get('dataTable', False) if position_part: res = data.get('dataTable', False) if res: hold_headers = res['columns'] hold_headers = [ cn_en_compare[item] for item in hold_headers ] hold_available = pd.DataFrame( res['rows'], columns=hold_headers ) if len(hold_available) == 1 and hold_available.amount[0] in [ None, '', 0 ]: hold_available = pd.DataFrame( data=None, columns=hold_headers ) return { 'cash_available': cash_available, 'hold_available': hold_available.assign( amount=hold_available.amount.apply(float) ).loc[:, ['code', 'amount']].set_index('code').amount } else: print(data) return False, 'None ACCOUNT' except: return False
[ "查询现金和持仓" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAShipaneBroker.py#L215-L266
[ "def", "query_positions", "(", "self", ",", "accounts", ")", ":", "try", ":", "data", "=", "self", ".", "call", "(", "\"positions\"", ",", "{", "'client'", ":", "accounts", "}", ")", "if", "data", "is", "not", "None", ":", "cash_part", "=", "data", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SPEBroker.query_clients
查询clients Returns: [type] -- [description]
QUANTAXIS/QAMarket/QAShipaneBroker.py
def query_clients(self): """查询clients Returns: [type] -- [description] """ try: data = self.call("clients", {'client': 'None'}) if len(data) > 0: return pd.DataFrame(data).drop( ['commandLine', 'processId'], axis=1 ) else: return pd.DataFrame( None, columns=[ 'id', 'name', 'windowsTitle', 'accountInfo', 'status' ] ) except Exception as e: return False, e
def query_clients(self): """查询clients Returns: [type] -- [description] """ try: data = self.call("clients", {'client': 'None'}) if len(data) > 0: return pd.DataFrame(data).drop( ['commandLine', 'processId'], axis=1 ) else: return pd.DataFrame( None, columns=[ 'id', 'name', 'windowsTitle', 'accountInfo', 'status' ] ) except Exception as e: return False, e
[ "查询clients" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAShipaneBroker.py#L268-L295
[ "def", "query_clients", "(", "self", ")", ":", "try", ":", "data", "=", "self", ".", "call", "(", "\"clients\"", ",", "{", "'client'", ":", "'None'", "}", ")", "if", "len", "(", "data", ")", ">", "0", ":", "return", "pd", ".", "DataFrame", "(", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SPEBroker.query_orders
查询订单 Arguments: accounts {[type]} -- [description] Keyword Arguments: status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'}) Returns: [type] -- [description]
QUANTAXIS/QAMarket/QAShipaneBroker.py
def query_orders(self, accounts, status='filled'): """查询订单 Arguments: accounts {[type]} -- [description] Keyword Arguments: status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'}) Returns: [type] -- [description] """ try: data = self.call("orders", {'client': accounts, 'status': status}) if data is not None: orders = data.get('dataTable', False) order_headers = orders['columns'] if ('成交状态' in order_headers or '状态说明' in order_headers) and ('备注' in order_headers): order_headers[order_headers.index('备注')] = '废弃' order_headers = [cn_en_compare[item] for item in order_headers] order_all = pd.DataFrame( orders['rows'], columns=order_headers ).assign(account_cookie=accounts) order_all.towards = order_all.towards.apply( lambda x: trade_towards_cn_en[x] ) if 'order_time' in order_headers: # 这是order_status order_all['status'] = order_all.status.apply( lambda x: order_status_cn_en[x] ) if 'order_date' not in order_headers: order_all.order_time = order_all.order_time.apply( lambda x: QA_util_get_order_datetime( dt='{} {}'.format(datetime.date.today(), x) ) ) else: order_all = order_all.assign( order_time=order_all.order_date .apply(QA_util_date_int2str) + ' ' + order_all.order_time ) if 'trade_time' in order_headers: order_all.trade_time = order_all.trade_time.apply( lambda x: '{} {}'.format(datetime.date.today(), x) ) if status is 'filled': return order_all.loc[:, self.dealstatus_headers].set_index( ['account_cookie', 'realorder_id'] ).sort_index() else: return order_all.loc[:, self.orderstatus_headers].set_index( ['account_cookie', 'realorder_id'] ).sort_index() else: print('response is None') return False except Exception as e: print(e) return False
def query_orders(self, accounts, status='filled'): """查询订单 Arguments: accounts {[type]} -- [description] Keyword Arguments: status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'}) Returns: [type] -- [description] """ try: data = self.call("orders", {'client': accounts, 'status': status}) if data is not None: orders = data.get('dataTable', False) order_headers = orders['columns'] if ('成交状态' in order_headers or '状态说明' in order_headers) and ('备注' in order_headers): order_headers[order_headers.index('备注')] = '废弃' order_headers = [cn_en_compare[item] for item in order_headers] order_all = pd.DataFrame( orders['rows'], columns=order_headers ).assign(account_cookie=accounts) order_all.towards = order_all.towards.apply( lambda x: trade_towards_cn_en[x] ) if 'order_time' in order_headers: # 这是order_status order_all['status'] = order_all.status.apply( lambda x: order_status_cn_en[x] ) if 'order_date' not in order_headers: order_all.order_time = order_all.order_time.apply( lambda x: QA_util_get_order_datetime( dt='{} {}'.format(datetime.date.today(), x) ) ) else: order_all = order_all.assign( order_time=order_all.order_date .apply(QA_util_date_int2str) + ' ' + order_all.order_time ) if 'trade_time' in order_headers: order_all.trade_time = order_all.trade_time.apply( lambda x: '{} {}'.format(datetime.date.today(), x) ) if status is 'filled': return order_all.loc[:, self.dealstatus_headers].set_index( ['account_cookie', 'realorder_id'] ).sort_index() else: return order_all.loc[:, self.orderstatus_headers].set_index( ['account_cookie', 'realorder_id'] ).sort_index() else: print('response is None') return False except Exception as e: print(e) return False
[ "查询订单" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAShipaneBroker.py#L297-L372
[ "def", "query_orders", "(", "self", ",", "accounts", ",", "status", "=", "'filled'", ")", ":", "try", ":", "data", "=", "self", ".", "call", "(", "\"orders\"", ",", "{", "'client'", ":", "accounts", ",", "'status'", ":", "status", "}", ")", "if", "da...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SPEBroker.send_order
[summary] Arguments: accounts {[type]} -- [description] code {[type]} -- [description] price {[type]} -- [description] amount {[type]} -- [description] Keyword Arguments: order_direction {[type]} -- [description] (default: {ORDER_DIRECTION.BUY}) order_model {[type]} -- [description] (default: {ORDER_MODEL.LIMIT}) priceType 可选择: 上海交易所: 0 - 限价委托 4 - 五档即时成交剩余撤销 6 - 五档即时成交剩余转限 深圳交易所: 0 - 限价委托 1 - 对手方最优价格委托 2 - 本方最优价格委托 3 - 即时成交剩余撤销委托 4 - 五档即时成交剩余撤销 5 - 全额成交或撤销委托 Returns: [type] -- [description]
QUANTAXIS/QAMarket/QAShipaneBroker.py
def send_order( self, accounts, code='000001', price=9, amount=100, order_direction=ORDER_DIRECTION.BUY, order_model=ORDER_MODEL.LIMIT ): """[summary] Arguments: accounts {[type]} -- [description] code {[type]} -- [description] price {[type]} -- [description] amount {[type]} -- [description] Keyword Arguments: order_direction {[type]} -- [description] (default: {ORDER_DIRECTION.BUY}) order_model {[type]} -- [description] (default: {ORDER_MODEL.LIMIT}) priceType 可选择: 上海交易所: 0 - 限价委托 4 - 五档即时成交剩余撤销 6 - 五档即时成交剩余转限 深圳交易所: 0 - 限价委托 1 - 对手方最优价格委托 2 - 本方最优价格委托 3 - 即时成交剩余撤销委托 4 - 五档即时成交剩余撤销 5 - 全额成交或撤销委托 Returns: [type] -- [description] """ try: #print(code, price, amount) return self.call_post( 'orders', { 'client': accounts, "action": 'BUY' if order_direction == 1 else 'SELL', "symbol": code, "type": order_model, "priceType": 0 if order_model == ORDER_MODEL.LIMIT else 4, "price": price, "amount": amount } ) except json.decoder.JSONDecodeError: print(RuntimeError('TRADE ERROR')) return None
def send_order( self, accounts, code='000001', price=9, amount=100, order_direction=ORDER_DIRECTION.BUY, order_model=ORDER_MODEL.LIMIT ): """[summary] Arguments: accounts {[type]} -- [description] code {[type]} -- [description] price {[type]} -- [description] amount {[type]} -- [description] Keyword Arguments: order_direction {[type]} -- [description] (default: {ORDER_DIRECTION.BUY}) order_model {[type]} -- [description] (default: {ORDER_MODEL.LIMIT}) priceType 可选择: 上海交易所: 0 - 限价委托 4 - 五档即时成交剩余撤销 6 - 五档即时成交剩余转限 深圳交易所: 0 - 限价委托 1 - 对手方最优价格委托 2 - 本方最优价格委托 3 - 即时成交剩余撤销委托 4 - 五档即时成交剩余撤销 5 - 全额成交或撤销委托 Returns: [type] -- [description] """ try: #print(code, price, amount) return self.call_post( 'orders', { 'client': accounts, "action": 'BUY' if order_direction == 1 else 'SELL', "symbol": code, "type": order_model, "priceType": 0 if order_model == ORDER_MODEL.LIMIT else 4, "price": price, "amount": amount } ) except json.decoder.JSONDecodeError: print(RuntimeError('TRADE ERROR')) return None
[ "[", "summary", "]" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAShipaneBroker.py#L374-L431
[ "def", "send_order", "(", "self", ",", "accounts", ",", "code", "=", "'000001'", ",", "price", "=", "9", ",", "amount", "=", "100", ",", "order_direction", "=", "ORDER_DIRECTION", ".", "BUY", ",", "order_model", "=", "ORDER_MODEL", ".", "LIMIT", ")", ":"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_DataStruct_Indicators.get_indicator
获取某一时间的某一只股票的指标
QUANTAXIS/QAData/QAIndicatorStruct.py
def get_indicator(self, time, code, indicator_name=None): """ 获取某一时间的某一只股票的指标 """ try: return self.data.loc[(pd.Timestamp(time), code), indicator_name] except: raise ValueError('CANNOT FOUND THIS DATE&CODE')
def get_indicator(self, time, code, indicator_name=None): """ 获取某一时间的某一只股票的指标 """ try: return self.data.loc[(pd.Timestamp(time), code), indicator_name] except: raise ValueError('CANNOT FOUND THIS DATE&CODE')
[ "获取某一时间的某一只股票的指标" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QAIndicatorStruct.py#L47-L54
[ "def", "get_indicator", "(", "self", ",", "time", ",", "code", ",", "indicator_name", "=", "None", ")", ":", "try", ":", "return", "self", ".", "data", ".", "loc", "[", "(", "pd", ".", "Timestamp", "(", "time", ")", ",", "code", ")", ",", "indicato...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_DataStruct_Indicators.get_timerange
获取某一段时间的某一只股票的指标
QUANTAXIS/QAData/QAIndicatorStruct.py
def get_timerange(self, start, end, code=None): """ 获取某一段时间的某一只股票的指标 """ try: return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(code)), :] except: return ValueError('CANNOT FOUND THIS TIME RANGE')
def get_timerange(self, start, end, code=None): """ 获取某一段时间的某一只股票的指标 """ try: return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(code)), :] except: return ValueError('CANNOT FOUND THIS TIME RANGE')
[ "获取某一段时间的某一只股票的指标" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QAIndicatorStruct.py#L65-L72
[ "def", "get_timerange", "(", "self", ",", "start", ",", "end", ",", "code", "=", "None", ")", ":", "try", ":", "return", "self", ".", "data", ".", "loc", "[", "(", "slice", "(", "pd", ".", "Timestamp", "(", "start", ")", ",", "pd", ".", "Timestam...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SU_save_stock_terminated
获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。 collection: code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期 :param client: :return: None
QUANTAXIS/QASU/save_tushare.py
def QA_SU_save_stock_terminated(client=DATABASE): ''' 获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。 collection: code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期 :param client: :return: None ''' # 🛠todo 已经失效从wind 资讯里获取 # 这个函数已经失效 print("!!! tushare 这个函数已经失效!!!") df = QATs.get_terminated() #df = QATs.get_suspended() print( " Get stock terminated from tushare,stock count is %d (终止上市股票列表)" % len(df) ) coll = client.stock_terminated client.drop_collection(coll) json_data = json.loads(df.reset_index().to_json(orient='records')) coll.insert(json_data) print(" 保存终止上市股票列表 到 stock_terminated collection, OK")
def QA_SU_save_stock_terminated(client=DATABASE): ''' 获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。 collection: code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期 :param client: :return: None ''' # 🛠todo 已经失效从wind 资讯里获取 # 这个函数已经失效 print("!!! tushare 这个函数已经失效!!!") df = QATs.get_terminated() #df = QATs.get_suspended() print( " Get stock terminated from tushare,stock count is %d (终止上市股票列表)" % len(df) ) coll = client.stock_terminated client.drop_collection(coll) json_data = json.loads(df.reset_index().to_json(orient='records')) coll.insert(json_data) print(" 保存终止上市股票列表 到 stock_terminated collection, OK")
[ "获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。", "collection:", "code:股票代码", "name:股票名称", "oDate", ":", "上市日期", "tDate", ":", "终止上市日期", ":", "param", "client", ":", ":", "return", ":", "None" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_tushare.py#L118-L140
[ "def", "QA_SU_save_stock_terminated", "(", "client", "=", "DATABASE", ")", ":", "# 🛠todo 已经失效从wind 资讯里获取", "# 这个函数已经失效", "print", "(", "\"!!! tushare 这个函数已经失效!!!\")", "", "df", "=", "QATs", ".", "get_terminated", "(", ")", "#df = QATs.get_suspended()", "print", "(", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SU_save_stock_info_tushare
获取 股票的 基本信息,包含股票的如下信息 code,代码 name,名称 industry,所属行业 area,地区 pe,市盈率 outstanding,流通股本(亿) totals,总股本(亿) totalAssets,总资产(万) liquidAssets,流动资产 fixedAssets,固定资产 reserved,公积金 reservedPerShare,每股公积金 esp,每股收益 bvps,每股净资 pb,市净率 timeToMarket,上市日期 undp,未分利润 perundp, 每股未分配 rev,收入同比(%) profit,利润同比(%) gpr,毛利率(%) npr,净利润率(%) holders,股东人数 add by tauruswang 在命令行工具 quantaxis 中输入 save stock_info_tushare 中的命令 :param client: :return:
QUANTAXIS/QASU/save_tushare.py
def QA_SU_save_stock_info_tushare(client=DATABASE): ''' 获取 股票的 基本信息,包含股票的如下信息 code,代码 name,名称 industry,所属行业 area,地区 pe,市盈率 outstanding,流通股本(亿) totals,总股本(亿) totalAssets,总资产(万) liquidAssets,流动资产 fixedAssets,固定资产 reserved,公积金 reservedPerShare,每股公积金 esp,每股收益 bvps,每股净资 pb,市净率 timeToMarket,上市日期 undp,未分利润 perundp, 每股未分配 rev,收入同比(%) profit,利润同比(%) gpr,毛利率(%) npr,净利润率(%) holders,股东人数 add by tauruswang 在命令行工具 quantaxis 中输入 save stock_info_tushare 中的命令 :param client: :return: ''' df = QATs.get_stock_basics() print(" Get stock info from tushare,stock count is %d" % len(df)) coll = client.stock_info_tushare client.drop_collection(coll) json_data = json.loads(df.reset_index().to_json(orient='records')) coll.insert(json_data) print(" Save data to stock_info_tushare collection, OK")
def QA_SU_save_stock_info_tushare(client=DATABASE): ''' 获取 股票的 基本信息,包含股票的如下信息 code,代码 name,名称 industry,所属行业 area,地区 pe,市盈率 outstanding,流通股本(亿) totals,总股本(亿) totalAssets,总资产(万) liquidAssets,流动资产 fixedAssets,固定资产 reserved,公积金 reservedPerShare,每股公积金 esp,每股收益 bvps,每股净资 pb,市净率 timeToMarket,上市日期 undp,未分利润 perundp, 每股未分配 rev,收入同比(%) profit,利润同比(%) gpr,毛利率(%) npr,净利润率(%) holders,股东人数 add by tauruswang 在命令行工具 quantaxis 中输入 save stock_info_tushare 中的命令 :param client: :return: ''' df = QATs.get_stock_basics() print(" Get stock info from tushare,stock count is %d" % len(df)) coll = client.stock_info_tushare client.drop_collection(coll) json_data = json.loads(df.reset_index().to_json(orient='records')) coll.insert(json_data) print(" Save data to stock_info_tushare collection, OK")
[ "获取", "股票的", "基本信息,包含股票的如下信息" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_tushare.py#L143-L183
[ "def", "QA_SU_save_stock_info_tushare", "(", "client", "=", "DATABASE", ")", ":", "df", "=", "QATs", ".", "get_stock_basics", "(", ")", "print", "(", "\" Get stock info from tushare,stock count is %d\"", "%", "len", "(", "df", ")", ")", "coll", "=", "client", "....
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_SU_save_stock_day
save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用
QUANTAXIS/QASU/save_tushare.py
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None): ''' save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用 ''' stock_list = QA_fetch_get_stock_list() # TODO: 重命名stock_day_ts coll_stock_day = client.stock_day_ts coll_stock_day.create_index( [("code", pymongo.ASCENDING), ("date_stamp", pymongo.ASCENDING)] ) err = [] num_stocks = len(stock_list) for index, ts_code in enumerate(stock_list): QA_util_log_info('The {} of Total {}'.format(index, num_stocks)) strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format( str(float(index / num_stocks * 100))[0:4] + '%', ui_log ) intProgressToLog = int(float(index / num_stocks * 100)) QA_util_log_info( strProgressToLog, ui_log=ui_log, ui_progress=ui_progress, ui_progress_int_value=intProgressToLog ) _saving_work(ts_code, coll_stock_day, ui_log=ui_log, err=err) # 日线行情每分钟内最多调取200次,超过5000积分无限制 time.sleep(0.005) if len(err) < 1: QA_util_log_info('SUCCESS save stock day ^_^', ui_log) else: QA_util_log_info('ERROR CODE \n ', ui_log) QA_util_log_info(err, ui_log)
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None): ''' save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用 ''' stock_list = QA_fetch_get_stock_list() # TODO: 重命名stock_day_ts coll_stock_day = client.stock_day_ts coll_stock_day.create_index( [("code", pymongo.ASCENDING), ("date_stamp", pymongo.ASCENDING)] ) err = [] num_stocks = len(stock_list) for index, ts_code in enumerate(stock_list): QA_util_log_info('The {} of Total {}'.format(index, num_stocks)) strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format( str(float(index / num_stocks * 100))[0:4] + '%', ui_log ) intProgressToLog = int(float(index / num_stocks * 100)) QA_util_log_info( strProgressToLog, ui_log=ui_log, ui_progress=ui_progress, ui_progress_int_value=intProgressToLog ) _saving_work(ts_code, coll_stock_day, ui_log=ui_log, err=err) # 日线行情每分钟内最多调取200次,超过5000积分无限制 time.sleep(0.005) if len(err) < 1: QA_util_log_info('SUCCESS save stock day ^_^', ui_log) else: QA_util_log_info('ERROR CODE \n ', ui_log) QA_util_log_info(err, ui_log)
[ "save", "stock_day", "保存日线数据", ":", "param", "client", ":", ":", "param", "ui_log", ":", "给GUI", "qt", "界面使用", ":", "param", "ui_progress", ":", "给GUI", "qt", "界面使用", ":", "param", "ui_progress_int_value", ":", "给GUI", "qt", "界面使用" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_tushare.py#L368-L414
[ "def", "QA_SU_save_stock_day", "(", "client", "=", "DATABASE", ",", "ui_log", "=", "None", ",", "ui_progress", "=", "None", ")", ":", "stock_list", "=", "QA_fetch_get_stock_list", "(", ")", "# TODO: 重命名stock_day_ts", "coll_stock_day", "=", "client", ".", "stock_da...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_dict_remove_key
输入一个dict 返回删除后的
QUANTAXIS/QAUtil/QADict.py
def QA_util_dict_remove_key(dicts, key): """ 输入一个dict 返回删除后的 """ if isinstance(key, list): for item in key: try: dicts.pop(item) except: pass else: try: dicts.pop(key) except: pass return dicts
def QA_util_dict_remove_key(dicts, key): """ 输入一个dict 返回删除后的 """ if isinstance(key, list): for item in key: try: dicts.pop(item) except: pass else: try: dicts.pop(key) except: pass return dicts
[ "输入一个dict", "返回删除后的" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADict.py#L26-L42
[ "def", "QA_util_dict_remove_key", "(", "dicts", ",", "key", ")", ":", "if", "isinstance", "(", "key", ",", "list", ")", ":", "for", "item", "in", "key", ":", "try", ":", "dicts", ".", "pop", "(", "item", ")", "except", ":", "pass", "else", ":", "tr...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_util_sql_async_mongo_setting
异步mongo示例 Keyword Arguments: uri {str} -- [description] (default: {'mongodb://localhost:27017/quantaxis'}) Returns: [type] -- [description]
QUANTAXIS/QAUtil/QASql.py
def QA_util_sql_async_mongo_setting(uri='mongodb://localhost:27017/quantaxis'): """异步mongo示例 Keyword Arguments: uri {str} -- [description] (default: {'mongodb://localhost:27017/quantaxis'}) Returns: [type] -- [description] """ # loop = asyncio.new_event_loop() # asyncio.set_event_loop(loop) try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # async def client(): return AsyncIOMotorClient(uri, io_loop=loop)
def QA_util_sql_async_mongo_setting(uri='mongodb://localhost:27017/quantaxis'): """异步mongo示例 Keyword Arguments: uri {str} -- [description] (default: {'mongodb://localhost:27017/quantaxis'}) Returns: [type] -- [description] """ # loop = asyncio.new_event_loop() # asyncio.set_event_loop(loop) try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # async def client(): return AsyncIOMotorClient(uri, io_loop=loop)
[ "异步mongo示例" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QASql.py#L41-L59
[ "def", "QA_util_sql_async_mongo_setting", "(", "uri", "=", "'mongodb://localhost:27017/quantaxis'", ")", ":", "# loop = asyncio.new_event_loop()", "# asyncio.set_event_loop(loop)", "try", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "except", "RuntimeError", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.add_account
portfolio add a account/stratetgy
QUANTAXIS/QAARP/QAPortfolio.py
def add_account(self, account): 'portfolio add a account/stratetgy' if account.account_cookie not in self.account_list: if self.cash_available > account.init_cash: account.portfolio_cookie = self.portfolio_cookie account.user_cookie = self.user_cookie self.cash.append(self.cash_available - account.init_cash) self.account_list.append(account.account_cookie) account.save() return account else: pass
def add_account(self, account): 'portfolio add a account/stratetgy' if account.account_cookie not in self.account_list: if self.cash_available > account.init_cash: account.portfolio_cookie = self.portfolio_cookie account.user_cookie = self.user_cookie self.cash.append(self.cash_available - account.init_cash) self.account_list.append(account.account_cookie) account.save() return account else: pass
[ "portfolio", "add", "a", "account", "/", "stratetgy" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L196-L207
[ "def", "add_account", "(", "self", ",", "account", ")", ":", "if", "account", ".", "account_cookie", "not", "in", "self", ".", "account_list", ":", "if", "self", ".", "cash_available", ">", "account", ".", "init_cash", ":", "account", ".", "portfolio_cookie"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.drop_account
删除一个account Arguments: account_cookie {[type]} -- [description] Raises: RuntimeError -- [description]
QUANTAXIS/QAARP/QAPortfolio.py
def drop_account(self, account_cookie): """删除一个account Arguments: account_cookie {[type]} -- [description] Raises: RuntimeError -- [description] """ if account_cookie in self.account_list: res = self.account_list.remove(account_cookie) self.cash.append( self.cash[-1] + self.get_account_by_cookie(res).init_cash) return True else: raise RuntimeError( 'account {} is not in the portfolio'.format(account_cookie) )
def drop_account(self, account_cookie): """删除一个account Arguments: account_cookie {[type]} -- [description] Raises: RuntimeError -- [description] """ if account_cookie in self.account_list: res = self.account_list.remove(account_cookie) self.cash.append( self.cash[-1] + self.get_account_by_cookie(res).init_cash) return True else: raise RuntimeError( 'account {} is not in the portfolio'.format(account_cookie) )
[ "删除一个account" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L209-L227
[ "def", "drop_account", "(", "self", ",", "account_cookie", ")", ":", "if", "account_cookie", "in", "self", ".", "account_list", ":", "res", "=", "self", ".", "account_list", ".", "remove", "(", "account_cookie", ")", "self", ".", "cash", ".", "append", "("...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.new_account
创建一个新的Account Keyword Arguments: account_cookie {[type]} -- [description] (default: {None}) Returns: [type] -- [description]
QUANTAXIS/QAARP/QAPortfolio.py
def new_account( self, account_cookie=None, init_cash=1000000, market_type=MARKET_TYPE.STOCK_CN, *args, **kwargs ): """创建一个新的Account Keyword Arguments: account_cookie {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ if account_cookie is None: """创建新的account Returns: [type] -- [description] """ # 如果组合的cash_available>创建新的account所需cash if self.cash_available >= init_cash: temp = QA_Account( user_cookie=self.user_cookie, portfolio_cookie=self.portfolio_cookie, init_cash=init_cash, market_type=market_type, *args, **kwargs ) if temp.account_cookie not in self.account_list: #self.accounts[temp.account_cookie] = temp self.account_list.append(temp.account_cookie) temp.save() self.cash.append(self.cash_available - init_cash) return temp else: return self.new_account() else: if self.cash_available >= init_cash: if account_cookie not in self.account_list: acc = QA_Account( portfolio_cookie=self.portfolio_cookie, user_cookie=self.user_cookie, init_cash=init_cash, market_type=market_type, account_cookie=account_cookie, *args, **kwargs ) acc.save() self.account_list.append(acc.account_cookie) self.cash.append(self.cash_available - init_cash) return acc else: return self.get_account_by_cookie(account_cookie)
def new_account( self, account_cookie=None, init_cash=1000000, market_type=MARKET_TYPE.STOCK_CN, *args, **kwargs ): """创建一个新的Account Keyword Arguments: account_cookie {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ if account_cookie is None: """创建新的account Returns: [type] -- [description] """ # 如果组合的cash_available>创建新的account所需cash if self.cash_available >= init_cash: temp = QA_Account( user_cookie=self.user_cookie, portfolio_cookie=self.portfolio_cookie, init_cash=init_cash, market_type=market_type, *args, **kwargs ) if temp.account_cookie not in self.account_list: #self.accounts[temp.account_cookie] = temp self.account_list.append(temp.account_cookie) temp.save() self.cash.append(self.cash_available - init_cash) return temp else: return self.new_account() else: if self.cash_available >= init_cash: if account_cookie not in self.account_list: acc = QA_Account( portfolio_cookie=self.portfolio_cookie, user_cookie=self.user_cookie, init_cash=init_cash, market_type=market_type, account_cookie=account_cookie, *args, **kwargs ) acc.save() self.account_list.append(acc.account_cookie) self.cash.append(self.cash_available - init_cash) return acc else: return self.get_account_by_cookie(account_cookie)
[ "创建一个新的Account" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L229-L290
[ "def", "new_account", "(", "self", ",", "account_cookie", "=", "None", ",", "init_cash", "=", "1000000", ",", "market_type", "=", "MARKET_TYPE", ".", "STOCK_CN", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "account_cookie", "is", "None", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.get_account_by_cookie
'give the account_cookie and return the account/strategy back' :param cookie: :return: QA_Account with cookie if in dict None not in list
QUANTAXIS/QAARP/QAPortfolio.py
def get_account_by_cookie(self, cookie): ''' 'give the account_cookie and return the account/strategy back' :param cookie: :return: QA_Account with cookie if in dict None not in list ''' try: return QA_Account( account_cookie=cookie, user_cookie=self.user_cookie, portfolio_cookie=self.portfolio_cookie, auto_reload=True ) except: QA_util_log_info('Can not find this account') return None
def get_account_by_cookie(self, cookie): ''' 'give the account_cookie and return the account/strategy back' :param cookie: :return: QA_Account with cookie if in dict None not in list ''' try: return QA_Account( account_cookie=cookie, user_cookie=self.user_cookie, portfolio_cookie=self.portfolio_cookie, auto_reload=True ) except: QA_util_log_info('Can not find this account') return None
[ "give", "the", "account_cookie", "and", "return", "the", "account", "/", "strategy", "back", ":", "param", "cookie", ":", ":", "return", ":", "QA_Account", "with", "cookie", "if", "in", "dict", "None", "not", "in", "list" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L292-L308
[ "def", "get_account_by_cookie", "(", "self", ",", "cookie", ")", ":", "try", ":", "return", "QA_Account", "(", "account_cookie", "=", "cookie", ",", "user_cookie", "=", "self", ".", "user_cookie", ",", "portfolio_cookie", "=", "self", ".", "portfolio_cookie", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.get_account
check the account whether in the protfolio dict or not :param account: QA_Account :return: QA_Account if in dict None not in list
QUANTAXIS/QAARP/QAPortfolio.py
def get_account(self, account): ''' check the account whether in the protfolio dict or not :param account: QA_Account :return: QA_Account if in dict None not in list ''' try: return self.get_account_by_cookie(account.account_cookie) except: QA_util_log_info( 'Can not find this account with cookies %s' % account.account_cookie ) return None
def get_account(self, account): ''' check the account whether in the protfolio dict or not :param account: QA_Account :return: QA_Account if in dict None not in list ''' try: return self.get_account_by_cookie(account.account_cookie) except: QA_util_log_info( 'Can not find this account with cookies %s' % account.account_cookie ) return None
[ "check", "the", "account", "whether", "in", "the", "protfolio", "dict", "or", "not", ":", "param", "account", ":", "QA_Account", ":", "return", ":", "QA_Account", "if", "in", "dict", "None", "not", "in", "list" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L310-L324
[ "def", "get_account", "(", "self", ",", "account", ")", ":", "try", ":", "return", "self", ".", "get_account_by_cookie", "(", "account", ".", "account_cookie", ")", "except", ":", "QA_util_log_info", "(", "'Can not find this account with cookies %s'", "%", "account"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.message
portfolio 的cookie
QUANTAXIS/QAARP/QAPortfolio.py
def message(self): """portfolio 的cookie """ return { 'user_cookie': self.user_cookie, 'portfolio_cookie': self.portfolio_cookie, 'account_list': list(self.account_list), 'init_cash': self.init_cash, 'cash': self.cash, 'history': self.history }
def message(self): """portfolio 的cookie """ return { 'user_cookie': self.user_cookie, 'portfolio_cookie': self.portfolio_cookie, 'account_list': list(self.account_list), 'init_cash': self.init_cash, 'cash': self.cash, 'history': self.history }
[ "portfolio", "的cookie" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L330-L340
[ "def", "message", "(", "self", ")", ":", "return", "{", "'user_cookie'", ":", "self", ".", "user_cookie", ",", "'portfolio_cookie'", ":", "self", ".", "portfolio_cookie", ",", "'account_list'", ":", "list", "(", "self", ".", "account_list", ")", ",", "'init_...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.send_order
基于portfolio对子账户下单 Arguments: account_cookie {str} -- [description] Keyword Arguments: code {[type]} -- [description] (default: {None}) amount {[type]} -- [description] (default: {None}) time {[type]} -- [description] (default: {None}) towards {[type]} -- [description] (default: {None}) price {[type]} -- [description] (default: {None}) money {[type]} -- [description] (default: {None}) order_model {[type]} -- [description] (default: {None}) amount_model {[type]} -- [description] (default: {None}) Returns: [type] -- [description]
QUANTAXIS/QAARP/QAPortfolio.py
def send_order( self, account_cookie: str, code=None, amount=None, time=None, towards=None, price=None, money=None, order_model=None, amount_model=None, *args, **kwargs ): """基于portfolio对子账户下单 Arguments: account_cookie {str} -- [description] Keyword Arguments: code {[type]} -- [description] (default: {None}) amount {[type]} -- [description] (default: {None}) time {[type]} -- [description] (default: {None}) towards {[type]} -- [description] (default: {None}) price {[type]} -- [description] (default: {None}) money {[type]} -- [description] (default: {None}) order_model {[type]} -- [description] (default: {None}) amount_model {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ return self.get_account_by_cookie(account_cookie).send_order( code=code, amount=amount, time=time, towards=towards, price=price, money=money, order_model=order_model, amount_model=amount_model )
def send_order( self, account_cookie: str, code=None, amount=None, time=None, towards=None, price=None, money=None, order_model=None, amount_model=None, *args, **kwargs ): """基于portfolio对子账户下单 Arguments: account_cookie {str} -- [description] Keyword Arguments: code {[type]} -- [description] (default: {None}) amount {[type]} -- [description] (default: {None}) time {[type]} -- [description] (default: {None}) towards {[type]} -- [description] (default: {None}) price {[type]} -- [description] (default: {None}) money {[type]} -- [description] (default: {None}) order_model {[type]} -- [description] (default: {None}) amount_model {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ return self.get_account_by_cookie(account_cookie).send_order( code=code, amount=amount, time=time, towards=towards, price=price, money=money, order_model=order_model, amount_model=amount_model )
[ "基于portfolio对子账户下单" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L342-L384
[ "def", "send_order", "(", "self", ",", "account_cookie", ":", "str", ",", "code", "=", "None", ",", "amount", "=", "None", ",", "time", "=", "None", ",", "towards", "=", "None", ",", "price", "=", "None", ",", "money", "=", "None", ",", "order_model"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Portfolio.save
存储过程
QUANTAXIS/QAARP/QAPortfolio.py
def save(self): """存储过程 """ self.client.update( { 'portfolio_cookie': self.portfolio_cookie, 'user_cookie': self.user_cookie }, {'$set': self.message}, upsert=True )
def save(self): """存储过程 """ self.client.update( { 'portfolio_cookie': self.portfolio_cookie, 'user_cookie': self.user_cookie }, {'$set': self.message}, upsert=True )
[ "存储过程" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAPortfolio.py#L527-L537
[ "def", "save", "(", "self", ")", ":", "self", ".", "client", ".", "update", "(", "{", "'portfolio_cookie'", ":", "self", ".", "portfolio_cookie", ",", "'user_cookie'", ":", "self", ".", "user_cookie", "}", ",", "{", "'$set'", ":", "self", ".", "message",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.market_value
每日每个股票持仓市值表 Returns: pd.DataFrame -- 市值表
QUANTAXIS/QAARP/QARisk.py
def market_value(self): """每日每个股票持仓市值表 Returns: pd.DataFrame -- 市值表 """ if self.account.daily_hold is not None: if self.if_fq: return ( self.market_data.to_qfq().pivot('close').fillna( method='ffill' ) * self.account.daily_hold.apply(abs) ).fillna(method='ffill') else: return ( self.market_data.pivot('close').fillna(method='ffill') * self.account.daily_hold.apply(abs) ).fillna(method='ffill') else: return None
def market_value(self): """每日每个股票持仓市值表 Returns: pd.DataFrame -- 市值表 """ if self.account.daily_hold is not None: if self.if_fq: return ( self.market_data.to_qfq().pivot('close').fillna( method='ffill' ) * self.account.daily_hold.apply(abs) ).fillna(method='ffill') else: return ( self.market_data.pivot('close').fillna(method='ffill') * self.account.daily_hold.apply(abs) ).fillna(method='ffill') else: return None
[ "每日每个股票持仓市值表" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L212-L232
[ "def", "market_value", "(", "self", ")", ":", "if", "self", ".", "account", ".", "daily_hold", "is", "not", "None", ":", "if", "self", ".", "if_fq", ":", "return", "(", "self", ".", "market_data", ".", "to_qfq", "(", ")", ".", "pivot", "(", "'close'"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.max_dropback
最大回撤
QUANTAXIS/QAARP/QARisk.py
def max_dropback(self): """最大回撤 """ return round( float( max( [ (self.assets.iloc[idx] - self.assets.iloc[idx::].min()) / self.assets.iloc[idx] for idx in range(len(self.assets)) ] ) ), 2 )
def max_dropback(self): """最大回撤 """ return round( float( max( [ (self.assets.iloc[idx] - self.assets.iloc[idx::].min()) / self.assets.iloc[idx] for idx in range(len(self.assets)) ] ) ), 2 )
[ "最大回撤" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L252-L266
[ "def", "max_dropback", "(", "self", ")", ":", "return", "round", "(", "float", "(", "max", "(", "[", "(", "self", ".", "assets", ".", "iloc", "[", "idx", "]", "-", "self", ".", "assets", ".", "iloc", "[", "idx", ":", ":", "]", ".", "min", "(", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.total_commission
总手续费
QUANTAXIS/QAARP/QARisk.py
def total_commission(self): """总手续费 """ return float( -abs(round(self.account.history_table.commission.sum(), 2)) )
def total_commission(self): """总手续费 """ return float( -abs(round(self.account.history_table.commission.sum(), 2)) )
[ "总手续费" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L269-L275
[ "def", "total_commission", "(", "self", ")", ":", "return", "float", "(", "-", "abs", "(", "round", "(", "self", ".", "account", ".", "history_table", ".", "commission", ".", "sum", "(", ")", ",", "2", ")", ")", ")" ]
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.total_tax
总印花税
QUANTAXIS/QAARP/QARisk.py
def total_tax(self): """总印花税 """ return float(-abs(round(self.account.history_table.tax.sum(), 2)))
def total_tax(self): """总印花税 """ return float(-abs(round(self.account.history_table.tax.sum(), 2)))
[ "总印花税" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L278-L283
[ "def", "total_tax", "(", "self", ")", ":", "return", "float", "(", "-", "abs", "(", "round", "(", "self", ".", "account", ".", "history_table", ".", "tax", ".", "sum", "(", ")", ",", "2", ")", ")", ")" ]
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.profit_construct
利润构成 Returns: dict -- 利润构成表
QUANTAXIS/QAARP/QARisk.py
def profit_construct(self): """利润构成 Returns: dict -- 利润构成表 """ return { 'total_buyandsell': round( self.profit_money - self.total_commission - self.total_tax, 2 ), 'total_tax': self.total_tax, 'total_commission': self.total_commission, 'total_profit': self.profit_money }
def profit_construct(self): """利润构成 Returns: dict -- 利润构成表 """ return { 'total_buyandsell': round( self.profit_money - self.total_commission - self.total_tax, 2 ), 'total_tax': self.total_tax, 'total_commission': self.total_commission, 'total_profit': self.profit_money }
[ "利润构成" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L286-L305
[ "def", "profit_construct", "(", "self", ")", ":", "return", "{", "'total_buyandsell'", ":", "round", "(", "self", ".", "profit_money", "-", "self", ".", "total_commission", "-", "self", ".", "total_tax", ",", "2", ")", ",", "'total_tax'", ":", "self", ".",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.profit_money
盈利额 Returns: [type] -- [description]
QUANTAXIS/QAARP/QARisk.py
def profit_money(self): """盈利额 Returns: [type] -- [description] """ return float(round(self.assets.iloc[-1] - self.assets.iloc[0], 2))
def profit_money(self): """盈利额 Returns: [type] -- [description] """ return float(round(self.assets.iloc[-1] - self.assets.iloc[0], 2))
[ "盈利额" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L308-L315
[ "def", "profit_money", "(", "self", ")", ":", "return", "float", "(", "round", "(", "self", ".", "assets", ".", "iloc", "[", "-", "1", "]", "-", "self", ".", "assets", ".", "iloc", "[", "0", "]", ",", "2", ")", ")" ]
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.annualize_return
年化收益 Returns: [type] -- [description]
QUANTAXIS/QAARP/QARisk.py
def annualize_return(self): """年化收益 Returns: [type] -- [description] """ return round( float(self.calc_annualize_return(self.assets, self.time_gap)), 2 )
def annualize_return(self): """年化收益 Returns: [type] -- [description] """ return round( float(self.calc_annualize_return(self.assets, self.time_gap)), 2 )
[ "年化收益" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L334-L345
[ "def", "annualize_return", "(", "self", ")", ":", "return", "round", "(", "float", "(", "self", ".", "calc_annualize_return", "(", "self", ".", "assets", ",", "self", ".", "time_gap", ")", ")", ",", "2", ")" ]
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.benchmark_data
基准组合的行情数据(一般是组合,可以调整)
QUANTAXIS/QAARP/QARisk.py
def benchmark_data(self): """ 基准组合的行情数据(一般是组合,可以调整) """ return self.fetch[self.benchmark_type]( self.benchmark_code, self.account.start_date, self.account.end_date )
def benchmark_data(self): """ 基准组合的行情数据(一般是组合,可以调整) """ return self.fetch[self.benchmark_type]( self.benchmark_code, self.account.start_date, self.account.end_date )
[ "基准组合的行情数据", "(", "一般是组合", "可以调整", ")" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L396-L404
[ "def", "benchmark_data", "(", "self", ")", ":", "return", "self", ".", "fetch", "[", "self", ".", "benchmark_type", "]", "(", "self", ".", "benchmark_code", ",", "self", ".", "account", ".", "start_date", ",", "self", ".", "account", ".", "end_date", ")"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.benchmark_assets
基准组合的账户资产队列
QUANTAXIS/QAARP/QARisk.py
def benchmark_assets(self): """ 基准组合的账户资产队列 """ return ( self.benchmark_data.close / float(self.benchmark_data.close.iloc[0]) * float(self.assets[0]) )
def benchmark_assets(self): """ 基准组合的账户资产队列 """ return ( self.benchmark_data.close / float(self.benchmark_data.close.iloc[0]) * float(self.assets[0]) )
[ "基准组合的账户资产队列" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L407-L415
[ "def", "benchmark_assets", "(", "self", ")", ":", "return", "(", "self", ".", "benchmark_data", ".", "close", "/", "float", "(", "self", ".", "benchmark_data", ".", "close", ".", "iloc", "[", "0", "]", ")", "*", "float", "(", "self", ".", "assets", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.benchmark_annualize_return
基准组合的年化收益 Returns: [type] -- [description]
QUANTAXIS/QAARP/QARisk.py
def benchmark_annualize_return(self): """基准组合的年化收益 Returns: [type] -- [description] """ return round( float( self.calc_annualize_return( self.benchmark_assets, self.time_gap ) ), 2 )
def benchmark_annualize_return(self): """基准组合的年化收益 Returns: [type] -- [description] """ return round( float( self.calc_annualize_return( self.benchmark_assets, self.time_gap ) ), 2 )
[ "基准组合的年化收益" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L425-L440
[ "def", "benchmark_annualize_return", "(", "self", ")", ":", "return", "round", "(", "float", "(", "self", ".", "calc_annualize_return", "(", "self", ".", "benchmark_assets", ",", "self", ".", "time_gap", ")", ")", ",", "2", ")" ]
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.beta
beta比率 组合的系统性风险
QUANTAXIS/QAARP/QARisk.py
def beta(self): """ beta比率 组合的系统性风险 """ try: res = round( float( self.calc_beta( self.profit_pct.dropna(), self.benchmark_profitpct.dropna() ) ), 2 ) except: print('贝塔计算错误。。') res = 0 return res
def beta(self): """ beta比率 组合的系统性风险 """ try: res = round( float( self.calc_beta( self.profit_pct.dropna(), self.benchmark_profitpct.dropna() ) ), 2 ) except: print('贝塔计算错误。。') res = 0 return res
[ "beta比率", "组合的系统性风险" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L450-L468
[ "def", "beta", "(", "self", ")", ":", "try", ":", "res", "=", "round", "(", "float", "(", "self", ".", "calc_beta", "(", "self", ".", "profit_pct", ".", "dropna", "(", ")", ",", "self", ".", "benchmark_profitpct", ".", "dropna", "(", ")", ")", ")",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.alpha
alpha比率 与市场基准收益无关的超额收益率
QUANTAXIS/QAARP/QARisk.py
def alpha(self): """ alpha比率 与市场基准收益无关的超额收益率 """ return round( float( self.calc_alpha( self.annualize_return, self.benchmark_annualize_return, self.beta, 0.05 ) ), 2 )
def alpha(self): """ alpha比率 与市场基准收益无关的超额收益率 """ return round( float( self.calc_alpha( self.annualize_return, self.benchmark_annualize_return, self.beta, 0.05 ) ), 2 )
[ "alpha比率", "与市场基准收益无关的超额收益率" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L471-L485
[ "def", "alpha", "(", "self", ")", ":", "return", "round", "(", "float", "(", "self", ".", "calc_alpha", "(", "self", ".", "annualize_return", ",", "self", ".", "benchmark_annualize_return", ",", "self", ".", "beta", ",", "0.05", ")", ")", ",", "2", ")"...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.sharpe
夏普比率
QUANTAXIS/QAARP/QARisk.py
def sharpe(self): """ 夏普比率 """ return round( float( self.calc_sharpe(self.annualize_return, self.volatility, 0.05) ), 2 )
def sharpe(self): """ 夏普比率 """ return round( float( self.calc_sharpe(self.annualize_return, self.volatility, 0.05) ), 2 )
[ "夏普比率" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L488-L500
[ "def", "sharpe", "(", "self", ")", ":", "return", "round", "(", "float", "(", "self", ".", "calc_sharpe", "(", "self", ".", "annualize_return", ",", "self", ".", "volatility", ",", "0.05", ")", ")", ",", "2", ")" ]
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.plot_assets_curve
资金曲线叠加图 @Roy T.Burns 2018/05/29 修改百分比显示错误
QUANTAXIS/QAARP/QARisk.py
def plot_assets_curve(self, length=14, height=12): """ 资金曲线叠加图 @Roy T.Burns 2018/05/29 修改百分比显示错误 """ plt.style.use('ggplot') plt.figure(figsize=(length, height)) plt.subplot(211) plt.title('BASIC INFO', fontsize=12) plt.axis([0, length, 0, 0.6]) plt.axis('off') i = 0 for item in ['account_cookie', 'portfolio_cookie', 'user_cookie']: plt.text( i, 0.5, '{} : {}'.format(item, self.message[item]), fontsize=10, rotation=0, wrap=True ) i += (length / 2.8) i = 0 for item in ['benchmark_code', 'time_gap', 'max_dropback']: plt.text( i, 0.4, '{} : {}'.format(item, self.message[item]), fontsize=10, ha='left', rotation=0, wrap=True ) i += (length / 2.8) i = 0 for item in ['annualize_return', 'bm_annualizereturn', 'profit']: plt.text( i, 0.3, '{} : {} %'.format(item, self.message.get(item, 0) * 100), fontsize=10, ha='left', rotation=0, wrap=True ) i += length / 2.8 i = 0 for item in ['init_cash', 'last_assets', 'volatility']: plt.text( i, 0.2, '{} : {} '.format(item, self.message[item]), fontsize=10, ha='left', rotation=0, wrap=True ) i += length / 2.8 i = 0 for item in ['alpha', 'beta', 'sharpe']: plt.text( i, 0.1, '{} : {}'.format(item, self.message[item]), ha='left', fontsize=10, rotation=0, wrap=True ) i += length / 2.8 plt.subplot(212) self.assets.plot() self.benchmark_assets.xs(self.benchmark_code, level=1).plot() asset_p = mpatches.Patch( color='red', label='{}'.format(self.account.account_cookie) ) asset_b = mpatches.Patch( label='benchmark {}'.format(self.benchmark_code) ) plt.legend(handles=[asset_p, asset_b], loc=0) plt.title('ASSET AND BENCKMARK') return plt
def plot_assets_curve(self, length=14, height=12): """ 资金曲线叠加图 @Roy T.Burns 2018/05/29 修改百分比显示错误 """ plt.style.use('ggplot') plt.figure(figsize=(length, height)) plt.subplot(211) plt.title('BASIC INFO', fontsize=12) plt.axis([0, length, 0, 0.6]) plt.axis('off') i = 0 for item in ['account_cookie', 'portfolio_cookie', 'user_cookie']: plt.text( i, 0.5, '{} : {}'.format(item, self.message[item]), fontsize=10, rotation=0, wrap=True ) i += (length / 2.8) i = 0 for item in ['benchmark_code', 'time_gap', 'max_dropback']: plt.text( i, 0.4, '{} : {}'.format(item, self.message[item]), fontsize=10, ha='left', rotation=0, wrap=True ) i += (length / 2.8) i = 0 for item in ['annualize_return', 'bm_annualizereturn', 'profit']: plt.text( i, 0.3, '{} : {} %'.format(item, self.message.get(item, 0) * 100), fontsize=10, ha='left', rotation=0, wrap=True ) i += length / 2.8 i = 0 for item in ['init_cash', 'last_assets', 'volatility']: plt.text( i, 0.2, '{} : {} '.format(item, self.message[item]), fontsize=10, ha='left', rotation=0, wrap=True ) i += length / 2.8 i = 0 for item in ['alpha', 'beta', 'sharpe']: plt.text( i, 0.1, '{} : {}'.format(item, self.message[item]), ha='left', fontsize=10, rotation=0, wrap=True ) i += length / 2.8 plt.subplot(212) self.assets.plot() self.benchmark_assets.xs(self.benchmark_code, level=1).plot() asset_p = mpatches.Patch( color='red', label='{}'.format(self.account.account_cookie) ) asset_b = mpatches.Patch( label='benchmark {}'.format(self.benchmark_code) ) plt.legend(handles=[asset_p, asset_b], loc=0) plt.title('ASSET AND BENCKMARK') return plt
[ "资金曲线叠加图" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L643-L733
[ "def", "plot_assets_curve", "(", "self", ",", "length", "=", "14", ",", "height", "=", "12", ")", ":", "plt", ".", "style", ".", "use", "(", "'ggplot'", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "length", ",", "height", ")", ")", "plt", ...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Risk.plot_signal
使用热力图画出买卖信号
QUANTAXIS/QAARP/QARisk.py
def plot_signal(self, start=None, end=None): """ 使用热力图画出买卖信号 """ start = self.account.start_date if start is None else start end = self.account.end_date if end is None else end _, ax = plt.subplots(figsize=(20, 18)) sns.heatmap( self.account.trade.reset_index().drop( 'account_cookie', axis=1 ).set_index('datetime').loc[start:end], cmap="YlGnBu", linewidths=0.05, ax=ax ) ax.set_title( 'SIGNAL TABLE --ACCOUNT: {}'.format(self.account.account_cookie) ) ax.set_xlabel('Code') ax.set_ylabel('DATETIME') return plt
def plot_signal(self, start=None, end=None): """ 使用热力图画出买卖信号 """ start = self.account.start_date if start is None else start end = self.account.end_date if end is None else end _, ax = plt.subplots(figsize=(20, 18)) sns.heatmap( self.account.trade.reset_index().drop( 'account_cookie', axis=1 ).set_index('datetime').loc[start:end], cmap="YlGnBu", linewidths=0.05, ax=ax ) ax.set_title( 'SIGNAL TABLE --ACCOUNT: {}'.format(self.account.account_cookie) ) ax.set_xlabel('Code') ax.set_ylabel('DATETIME') return plt
[ "使用热力图画出买卖信号" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L775-L796
[ "def", "plot_signal", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "start", "=", "self", ".", "account", ".", "start_date", "if", "start", "is", "None", "else", "start", "end", "=", "self", ".", "account", ".", "end_date...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Performance.pnl_lifo
使用后进先出法配对成交记录
QUANTAXIS/QAARP/QARisk.py
def pnl_lifo(self): """ 使用后进先出法配对成交记录 """ X = dict( zip( self.target.code, [LifoQueue() for i in range(len(self.target.code))] ) ) pair_table = [] for _, data in self.target.history_table_min.iterrows(): while True: if X[data.code].qsize() == 0: X[data.code].put((data.datetime, data.amount, data.price)) break else: l = X[data.code].get() if (l[1] * data.amount) < 0: # 原有多仓/ 平仓 或者原有空仓/平仓 if abs(l[1]) > abs(data.amount): temp = (l[0], l[1] + data.amount, l[2]) X[data.code].put_nowait(temp) if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], abs(data.amount), data.price, l[2] ] ) break else: pair_table.append( [ data.code, l[0], data.datetime, abs(data.amount), l[2], data.price ] ) break elif abs(l[1]) < abs(data.amount): data.amount = data.amount + l[1] if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], l[1], data.price, l[2] ] ) else: pair_table.append( [ data.code, l[0], data.datetime, l[1], l[2], data.price ] ) else: if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], abs(data.amount), data.price, l[2] ] ) break else: pair_table.append( [ data.code, l[0], data.datetime, abs(data.amount), l[2], data.price ] ) break else: X[data.code].put_nowait(l) X[data.code].put_nowait( (data.datetime, data.amount, data.price) ) break pair_title = [ 'code', 'sell_date', 'buy_date', 'amount', 'sell_price', 'buy_price' ] pnl = pd.DataFrame(pair_table, columns=pair_title).set_index('code') pnl = pnl.assign( unit=pnl.code.apply(lambda x: self.market_preset.get_unit(x)), pnl_ratio=(pnl.sell_price / pnl.buy_price) - 1, sell_date=pd.to_datetime(pnl.sell_date), buy_date=pd.to_datetime(pnl.buy_date) ) pnl = pnl.assign( pnl_money=(pnl.sell_price - pnl.buy_price) * pnl.amount * pnl.unit, hold_gap=abs(pnl.sell_date - pnl.buy_date), if_buyopen=(pnl.sell_date - pnl.buy_date) > datetime.timedelta(days=0) ) pnl = pnl.assign( openprice=pnl.if_buyopen.apply( lambda pnl: 1 if pnl else 0) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_price, opendate=pnl.if_buyopen.apply( lambda pnl: 1 if pnl else 0) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_date.map(str), closeprice=pnl.if_buyopen.apply( lambda pnl: 0 if pnl else 1) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_price, closedate=pnl.if_buyopen.apply( lambda pnl: 0 if pnl else 1) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_date.map(str)) return pnl.set_index('code')
def pnl_lifo(self): """ 使用后进先出法配对成交记录 """ X = dict( zip( self.target.code, [LifoQueue() for i in range(len(self.target.code))] ) ) pair_table = [] for _, data in self.target.history_table_min.iterrows(): while True: if X[data.code].qsize() == 0: X[data.code].put((data.datetime, data.amount, data.price)) break else: l = X[data.code].get() if (l[1] * data.amount) < 0: # 原有多仓/ 平仓 或者原有空仓/平仓 if abs(l[1]) > abs(data.amount): temp = (l[0], l[1] + data.amount, l[2]) X[data.code].put_nowait(temp) if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], abs(data.amount), data.price, l[2] ] ) break else: pair_table.append( [ data.code, l[0], data.datetime, abs(data.amount), l[2], data.price ] ) break elif abs(l[1]) < abs(data.amount): data.amount = data.amount + l[1] if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], l[1], data.price, l[2] ] ) else: pair_table.append( [ data.code, l[0], data.datetime, l[1], l[2], data.price ] ) else: if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], abs(data.amount), data.price, l[2] ] ) break else: pair_table.append( [ data.code, l[0], data.datetime, abs(data.amount), l[2], data.price ] ) break else: X[data.code].put_nowait(l) X[data.code].put_nowait( (data.datetime, data.amount, data.price) ) break pair_title = [ 'code', 'sell_date', 'buy_date', 'amount', 'sell_price', 'buy_price' ] pnl = pd.DataFrame(pair_table, columns=pair_title).set_index('code') pnl = pnl.assign( unit=pnl.code.apply(lambda x: self.market_preset.get_unit(x)), pnl_ratio=(pnl.sell_price / pnl.buy_price) - 1, sell_date=pd.to_datetime(pnl.sell_date), buy_date=pd.to_datetime(pnl.buy_date) ) pnl = pnl.assign( pnl_money=(pnl.sell_price - pnl.buy_price) * pnl.amount * pnl.unit, hold_gap=abs(pnl.sell_date - pnl.buy_date), if_buyopen=(pnl.sell_date - pnl.buy_date) > datetime.timedelta(days=0) ) pnl = pnl.assign( openprice=pnl.if_buyopen.apply( lambda pnl: 1 if pnl else 0) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_price, opendate=pnl.if_buyopen.apply( lambda pnl: 1 if pnl else 0) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_date.map(str), closeprice=pnl.if_buyopen.apply( lambda pnl: 0 if pnl else 1) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_price, closedate=pnl.if_buyopen.apply( lambda pnl: 0 if pnl else 1) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_date.map(str)) return pnl.set_index('code')
[ "使用后进先出法配对成交记录" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L1015-L1155
[ "def", "pnl_lifo", "(", "self", ")", ":", "X", "=", "dict", "(", "zip", "(", "self", ".", "target", ".", "code", ",", "[", "LifoQueue", "(", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "target", ".", "code", ")", ")", "]", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Performance.plot_pnlratio
画出pnl比率散点图
QUANTAXIS/QAARP/QARisk.py
def plot_pnlratio(self): """ 画出pnl比率散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_ratio) plt.gcf().autofmt_xdate() return plt
def plot_pnlratio(self): """ 画出pnl比率散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_ratio) plt.gcf().autofmt_xdate() return plt
[ "画出pnl比率散点图" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L1313-L1320
[ "def", "plot_pnlratio", "(", "self", ")", ":", "plt", ".", "scatter", "(", "x", "=", "self", ".", "pnl", ".", "sell_date", ".", "apply", "(", "str", ")", ",", "y", "=", "self", ".", "pnl", ".", "pnl_ratio", ")", "plt", ".", "gcf", "(", ")", "."...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Performance.plot_pnlmoney
画出pnl盈亏额散点图
QUANTAXIS/QAARP/QARisk.py
def plot_pnlmoney(self): """ 画出pnl盈亏额散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_money) plt.gcf().autofmt_xdate() return plt
def plot_pnlmoney(self): """ 画出pnl盈亏额散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_money) plt.gcf().autofmt_xdate() return plt
[ "画出pnl盈亏额散点图" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L1322-L1328
[ "def", "plot_pnlmoney", "(", "self", ")", ":", "plt", ".", "scatter", "(", "x", "=", "self", ".", "pnl", ".", "sell_date", ".", "apply", "(", "str", ")", ",", "y", "=", "self", ".", "pnl", ".", "pnl_money", ")", "plt", ".", "gcf", "(", ")", "."...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_Performance.win_rate
胜率 胜率 盈利次数/总次数
QUANTAXIS/QAARP/QARisk.py
def win_rate(self): """胜率 胜率 盈利次数/总次数 """ data = self.pnl try: return round(len(data.query('pnl_money>0')) / len(data), 2) except ZeroDivisionError: return 0
def win_rate(self): """胜率 胜率 盈利次数/总次数 """ data = self.pnl try: return round(len(data.query('pnl_money>0')) / len(data), 2) except ZeroDivisionError: return 0
[ "胜率" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L1346-L1356
[ "def", "win_rate", "(", "self", ")", ":", "data", "=", "self", ".", "pnl", "try", ":", "return", "round", "(", "len", "(", "data", ".", "query", "(", "'pnl_money>0'", ")", ")", "/", "len", "(", "data", ")", ",", "2", ")", "except", "ZeroDivisionErr...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
CronTabItem.next_time
Get the local time of the next schedule time this job will run. :param bool asc: Format the result with ``time.asctime()`` :returns: The epoch time or string representation of the epoch time that the job should be run next
QUANTAXIS/QASetting/crontab.py
def next_time(self, asc=False): """Get the local time of the next schedule time this job will run. :param bool asc: Format the result with ``time.asctime()`` :returns: The epoch time or string representation of the epoch time that the job should be run next """ _time = time.localtime(time.time() + self.next()) if asc: return time.asctime(_time) return time.mktime(_time)
def next_time(self, asc=False): """Get the local time of the next schedule time this job will run. :param bool asc: Format the result with ``time.asctime()`` :returns: The epoch time or string representation of the epoch time that the job should be run next """ _time = time.localtime(time.time() + self.next()) if asc: return time.asctime(_time) return time.mktime(_time)
[ "Get", "the", "local", "time", "of", "the", "next", "schedule", "time", "this", "job", "will", "run", ".", ":", "param", "bool", "asc", ":", "Format", "the", "result", "with", "time", ".", "asctime", "()", ":", "returns", ":", "The", "epoch", "time", ...
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/crontab.py#L51-L62
[ "def", "next_time", "(", "self", ",", "asc", "=", "False", ")", ":", "_time", "=", "time", ".", "localtime", "(", "time", ".", "time", "(", ")", "+", "self", ".", "next", "(", ")", ")", "if", "asc", ":", "return", "time", ".", "asctime", "(", "...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_fetch_get_future_transaction_realtime
期货实时tick
QUANTAXIS/QAFetch/__init__.py
def QA_fetch_get_future_transaction_realtime(package, code): """ 期货实时tick """ Engine = use(package) if package in ['tdx', 'pytdx']: return Engine.QA_fetch_get_future_transaction_realtime(code) else: return 'Unsupport packages'
def QA_fetch_get_future_transaction_realtime(package, code): """ 期货实时tick """ Engine = use(package) if package in ['tdx', 'pytdx']: return Engine.QA_fetch_get_future_transaction_realtime(code) else: return 'Unsupport packages'
[ "期货实时tick" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/__init__.py#L272-L280
[ "def", "QA_fetch_get_future_transaction_realtime", "(", "package", ",", "code", ")", ":", "Engine", "=", "use", "(", "package", ")", "if", "package", "in", "[", "'tdx'", ",", "'pytdx'", "]", ":", "return", "Engine", ".", "QA_fetch_get_future_transaction_realtime",...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_indicator_MA
MA Arguments: DataFrame {[type]} -- [description] Returns: [type] -- [description]
QUANTAXIS/QAIndicator/indicators.py
def QA_indicator_MA(DataFrame,*args,**kwargs): """MA Arguments: DataFrame {[type]} -- [description] Returns: [type] -- [description] """ CLOSE = DataFrame['close'] return pd.DataFrame({'MA{}'.format(N): MA(CLOSE, N) for N in list(args)})
def QA_indicator_MA(DataFrame,*args,**kwargs): """MA Arguments: DataFrame {[type]} -- [description] Returns: [type] -- [description] """ CLOSE = DataFrame['close'] return pd.DataFrame({'MA{}'.format(N): MA(CLOSE, N) for N in list(args)})
[ "MA", "Arguments", ":", "DataFrame", "{", "[", "type", "]", "}", "--", "[", "description", "]", "Returns", ":", "[", "type", "]", "--", "[", "description", "]" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L58-L69
[ "def", "QA_indicator_MA", "(", "DataFrame", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "CLOSE", "=", "DataFrame", "[", "'close'", "]", "return", "pd", ".", "DataFrame", "(", "{", "'MA{}'", ".", "format", "(", "N", ")", ":", "MA", "(", "CL...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_indicator_MACD
MACD CALC
QUANTAXIS/QAIndicator/indicators.py
def QA_indicator_MACD(DataFrame, short=12, long=26, mid=9): """ MACD CALC """ CLOSE = DataFrame['close'] DIF = EMA(CLOSE, short)-EMA(CLOSE, long) DEA = EMA(DIF, mid) MACD = (DIF-DEA)*2 return pd.DataFrame({'DIF': DIF, 'DEA': DEA, 'MACD': MACD})
def QA_indicator_MACD(DataFrame, short=12, long=26, mid=9): """ MACD CALC """ CLOSE = DataFrame['close'] DIF = EMA(CLOSE, short)-EMA(CLOSE, long) DEA = EMA(DIF, mid) MACD = (DIF-DEA)*2 return pd.DataFrame({'DIF': DIF, 'DEA': DEA, 'MACD': MACD})
[ "MACD", "CALC" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L82-L92
[ "def", "QA_indicator_MACD", "(", "DataFrame", ",", "short", "=", "12", ",", "long", "=", "26", ",", "mid", "=", "9", ")", ":", "CLOSE", "=", "DataFrame", "[", "'close'", "]", "DIF", "=", "EMA", "(", "CLOSE", ",", "short", ")", "-", "EMA", "(", "C...
bb1fe424e4108b62a1f712b81a05cf829297a5c0
train
QA_indicator_DMI
趋向指标 DMI
QUANTAXIS/QAIndicator/indicators.py
def QA_indicator_DMI(DataFrame, M1=14, M2=6): """ 趋向指标 DMI """ HIGH = DataFrame.high LOW = DataFrame.low CLOSE = DataFrame.close OPEN = DataFrame.open TR = SUM(MAX(MAX(HIGH-LOW, ABS(HIGH-REF(CLOSE, 1))), ABS(LOW-REF(CLOSE, 1))), M1) HD = HIGH-REF(HIGH, 1) LD = REF(LOW, 1)-LOW DMP = SUM(IFAND(HD>0,HD>LD,HD,0), M1) DMM = SUM(IFAND(LD>0,LD>HD,LD,0), M1) DI1 = DMP*100/TR DI2 = DMM*100/TR ADX = MA(ABS(DI2-DI1)/(DI1+DI2)*100, M2) ADXR = (ADX+REF(ADX, M2))/2 return pd.DataFrame({ 'DI1': DI1, 'DI2': DI2, 'ADX': ADX, 'ADXR': ADXR })
def QA_indicator_DMI(DataFrame, M1=14, M2=6): """ 趋向指标 DMI """ HIGH = DataFrame.high LOW = DataFrame.low CLOSE = DataFrame.close OPEN = DataFrame.open TR = SUM(MAX(MAX(HIGH-LOW, ABS(HIGH-REF(CLOSE, 1))), ABS(LOW-REF(CLOSE, 1))), M1) HD = HIGH-REF(HIGH, 1) LD = REF(LOW, 1)-LOW DMP = SUM(IFAND(HD>0,HD>LD,HD,0), M1) DMM = SUM(IFAND(LD>0,LD>HD,LD,0), M1) DI1 = DMP*100/TR DI2 = DMM*100/TR ADX = MA(ABS(DI2-DI1)/(DI1+DI2)*100, M2) ADXR = (ADX+REF(ADX, M2))/2 return pd.DataFrame({ 'DI1': DI1, 'DI2': DI2, 'ADX': ADX, 'ADXR': ADXR })
[ "趋向指标", "DMI" ]
QUANTAXIS/QUANTAXIS
python
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L95-L118
[ "def", "QA_indicator_DMI", "(", "DataFrame", ",", "M1", "=", "14", ",", "M2", "=", "6", ")", ":", "HIGH", "=", "DataFrame", ".", "high", "LOW", "=", "DataFrame", ".", "low", "CLOSE", "=", "DataFrame", ".", "close", "OPEN", "=", "DataFrame", ".", "ope...
bb1fe424e4108b62a1f712b81a05cf829297a5c0